Using Solr From Java

SolrJ

(warning) Solr1.3

Solrj is a robust Java client for adding, deleting and updating documents with Solr. Solrj includes an option to access an embedded solr instance without the need to run an HTTP server.

Translating requests to SolrJ

SolrJ can call to any solrconfig.xml registered request handler. Given a request handler like this:

  <requestHandler name="/spellCheckCompRH" class="solr.SearchHandler">
    <lst name="defaults">
      <!-- omp = Only More Popular -->
      <str name="spellcheck.onlyMorePopular">false</str>
      <!-- exr = Extended Results -->
      <str name="spellcheck.extendedResults">false</str>
      <!--  The number of suggestions to return -->
      <str name="spellcheck.count">1</str>
    </lst>
    <arr name="last-components">
      <str>spellcheck</str>
    </arr>
  </requestHandler>

This SolrJ code will call the handler:

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;

import java.net.MalformedURLException;

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

    // http://localhost:8983/solr/spellCheckCompRH?q=epod&spellcheck=on&spellcheck.build=true
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set("qt", "/spellCheckCompRH");
    params.set("q", "epod");
    params.set("spellcheck", "on");
    params.set("spellcheck.build", "true");

    QueryResponse response = solr.query(params);
    System.out.println("response = " + response);
  }
}

SimplePostTool

(warning) Solr1.2

Solr includes a simple class to post data: SimplePostTool.java

You can find it jarred up in /example/exampledocs/post.jar. For more information on how to use it run java -jar post.jar -help

  • No labels