SolrJ Tutorial

Setting up the classpath

From /dist
	apache-solr-solrj-*.jar

From /dist/solrj-lib
	commons-codec-1.3.jar
	commons-httpclient-3.1.jar
	commons-io-1.4.jar
	jcl-over-slf4j-1.5.5.jar
	slf4j-api-1.5.5.jar

From /lib
	slf4j-jdk14-1.5.5.jar

Add documents using SolrJ


import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;

public class SolrjPopulator {
  public static void main(String[] args) throws IOException, SolrServerException {
    SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/collection1").build();
    for(int i=0;i<1000;++i) {
      SolrInputDocument doc = new SolrInputDocument();
      doc.addField("cat", "book");
      doc.addField("id", "book-" + i);
      doc.addField("name", "The Legend of the Hobbit part " + i);
      client.add(doc);
      if(i%100==0) client.commit();  // periodically flush
    }
    client.commit(); 
  }
}

Search using SolrJ


import java.io.IOException;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

public class SolrJSearcher {
    public static void main(String[] args) throws IOException, SolrServerException {
        SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/collection1").build();

        SolrQuery query = new SolrQuery();
        query.setQuery("sony digital camera");
        query.addFilterQuery("cat:electronics","store:amazon.com");
        query.setFields("id","price","merchant","cat","store");
        query.setStart(0);
        query.set("defType", "edismax");

        QueryResponse response = client.query(query);
        SolrDocumentList results = response.getResults();
        for (int i = 0; i < results.size(); ++i) {
            System.out.println(results.get(i));
        }
    }
}