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.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;

public class SolrjPopulator {
  public static void main(String[] args) throws IOException, SolrServerException {
    HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr");
    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);
      server.add(doc);
      if(i%100==0) server.commit();  // periodically flush
    }
    server.commit();
  }
}

Search using SolrJ

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

import java.net.MalformedURLException;

public class SolrJSearcher {
  public static void main(String[] args) throws MalformedURLException, SolrServerException {
    HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr");

    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 = solr.query(query);
    SolrDocumentList results = response.getResults();
    for (int i = 0; i < results.size(); ++i) {
      System.out.println(results.get(i));
    }
  }
}