Search code examples
solrsolrj

solrJ error in HttpSolrServer and SolrServer


I have add the .jar files in java library , and try to connect to the solr, the code is below:

import java.net.MalformedURLException;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;

public class SolrQuery {
  public static void main(String[] args) throws MalformedURLException, SolrServerException {
    SolrServer server = new HttpSolrServer("http://localhost:8080/solr");
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("q", "1");

            QueryResponse response = server.query(params);

            System.out.println("response = " + response);

  }
} 

But when i try to run the program , i got error :

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    SolrServer cannot be resolved to a type
    HttpSolrServer cannot be resolved to a type
    The type org.apache.solr.common.params.SolrParams cannot be resolved. It is indirectly referenced from required .class files

How can i solve it?


Solution

  • In the server URL add collection/core name, where you indexed documents.

    SolrServer server = new HttpSolrServer("http://localhost:8080/solr/collection");

    Example Java Code For Your reference.

    * gives all documents indexed into solr. change * to keyword string you want to search.

    import org.apache.solr.client.solrj.SolrQuery;
    import org.apache.solr.client.solrj.SolrServerException;
    import org.apache.solr.client.solrj.impl.HttpSolrServer;
    import org.apache.solr.client.solrj.response.QueryResponse;
    import org.apache.solr.common.SolrDocumentList;
    
    public class SearchSolr {
    
        public static void main(String[] args) throws SolrServerException {
            HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr/collection1");
            SolrQuery query = new SolrQuery();
            query.setQuery("*"); 
            QueryResponse response = solr.query(query);
            SolrDocumentList results = response.getResults();
            for (int i = 0; i < results.size(); ++i) {
              System.out.println(results.get(i));
            }   
        }   
    }