25 December 2010

Adding document to Solr Using Solr4j

Requirement:
commons-codec-1.3.jar
commons-io-1.4.jar
commons-httpclient-3.1.jar
wstx-asl-3.2.7.jar
slf4j-api-1.5.5.jar
jcl-over-slf4j-1.5.5.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
apache-solr-solrj-1.4.1.jar

Sample Java Code:




import java.io.IOException;
import java.io.StringWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.*;
import org.apache.solr.client.solrj.response.*;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.XML;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.params.FacetParams;

public class TestSolrClient
{
public static void main(String args[])
{
try {
String url = "http://localhost:8983/solr";
CommonsHttpSolrServer server = new CommonsHttpSolrServer(url);

SolrInputDocument doc = new SolrInputDocument();
doc.addField("field", "value", 1.0f );
UpdateResponse upres = server.add( doc );
upres = server.commit( true, true );
System.out.println( "COMMIT:"+upres.getResponse() );

upres = server.optimize( true, true );
System.out.println( "OPTIMIZE:"+upres.getResponse() );
} catch(Exception e) {
e.printStackTrace();
}
}
}

2 comments:

  1. This is a really fantastic post. We have been working with Solr for the last 3-4 years, and we have been constantly searching for some information on Solr4J. Your post is the only post we could find which refers to this invaluable Java class library. All other references are to Solrj, which as we all know, is not the same thing.

    Can you please help us a bit more and guide us to a source from where we could download Solr4j?

    ReplyDelete
    Replies
    1. Solr4j is included in Apache Solr. Download apache Solr from http://lucene.apache.org/solr/downloads.html. Unzip-untar tgz file. You will get the solr4j jar in apache-solr-xxxxx/dist directory. Name of jar file will be like apache-solr-solrj-xxxx.jar

      Delete