Create a servlet project in myeclipse

Source: Internet
Author: User
Tags solr
Document directory
  • Setting the classpath
  • Commonshttpsolrserver
  • Embeddedsolrserver
  • Usage
Step 1: create a web project Step 2: Create it (servlet) in this project Step 3: start Tomcat (or other Web servers) Step 4: In myeclipse8.5, right-click it (servlet) and click Run.
 

Solrj is a Java client to access SOLR. it offers a Java interface to add, update, and query the SOLR index. this page describes the use of the solrj releases stored with SOLR 1.4.x releases, with the 1.4.x war files.

For information on using solrj with solr1.3 and solr1.2, see the sol1_1.3 page.

Setting the classpath

There are several folders containing jars used by solrj:/Dist,/Dist/solrj-lib and/lib. a minimal set of jars (You may find need of others depending on your usage scenario) to use solrj is as follows:

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
Maven

Solrj is available in the official Maven repository. Add the following dependency to your pom. XML to use solrj

        <dependency>               <artifactId>solr-solrj</artifactId>               <groupId>org.apache.solr</groupId>               <version>1.4.0</version>               <type>jar</type>               <scope>compile</scope>        </dependency>

If you need to use the embeddedsolrserver, you need to add the SOLR-core dependency too.

        <dependency>               <artifactId>solr-core</artifactId>               <groupId>org.apache.solr</groupId>               <version>1.4.0</version>               <type>jar</type>               <scope>compile</scope>        </dependency>

If you see any exceptions saying noclassdeffounderror, you will also need to include:

        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-simple</artifactId>            <version>1.5.6</version>        </dependency> 
Commonshttpsolrserver

The commonshttpsolrserver uses the Apache commons HTTP client to connect to SOLR.

  String url = "http://localhost:8983/solr";  /*    CommonsHttpSolrServer is thread-safe and if you are using the following constructor,    you *MUST* re-use the same instance for all requests.  If instances are created on    the fly, it can cause a connection leak. The recommended practice is to keep a    static instance of CommonsHttpSolrServer per solr server url and share it for all requests.    See https://issues.apache.org/jira/browse/SOLR-861 for more details  */  SolrServer server = new CommonsHttpSolrServer( url );
Changing other connection settings

Commonshttpsolrserver allows setting Connection Properties.

  String url = "http://localhost:8983/solr"  CommonsHttpSolrServer server = new CommonsHttpSolrServer( url );  server.setSoTimeout(1000);  // socket read timeout  server.setConnectionTimeout(100);  server.setDefaultMaxConnectionsPerHost(100);  server.setMaxTotalConnections(100);  server.setFollowRedirects(false);  // defaults to false  // allowCompression defaults to false.  // Server side must support gzip or deflate for this to have any effect.  server.setAllowCompression(true);  server.setMaxRetries(1); // defaults to 0.  > 1 not recommended.  server.setParser(new XMLResponseParser()); // binary parser is used by default
Embeddedsolrserver

The embeddedsolrserver provides the same interface without requiring an HTTP connection.

  // Note that the following property could be set through JVM level arguments too  System.setProperty("solr.solr.home", "/home/shalinsmangar/work/oss/branch-1.3/example/solr");  CoreContainer.Initializer initializer = new CoreContainer.Initializer();  CoreContainer coreContainer = initializer.initialize();  EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, "");

If you want to use multicore features, then you shocould use this:

    File home = new File( "/path/to/solr/home" );    File f = new File( home, "solr.xml" );    CoreContainer container = new CoreContainer();    container.load( "/path/to/solr/home", f );    EmbeddedSolrServer server = new EmbeddedSolrServer( container, "core name as defined in solr.xml" );    ...

If you need to use SOLR in an embedded application, this is the recommended approach. It allows you to work with the same interface whether or not you have access to HTTP.

Note -- embeddedsolrserver works only with handlers registered in solrconfig. xml. A requesthandler must be mapped to/update for a request to/update to function.

Usage

Solrj is designed as an extendable framework to pass solrrequest to the solrserver and return a solrresponse.

For simplicity, the most common commands are modeled in the solrserver:

Adding data to SOLR
  • Get an instance of server first
    SolrServer server = getSolrServer();

TheGetsolrserver ()Method body can be as follows if you use a remote server,

public SolrServer getSolrServer(){    //the instance can be reused    return new CommonsHttpSolrServer();}

If it is a local server use the following,

public SolrServer getSolrServer(){    //the instance can be reused    return new EmbeddedSolrServer();}
  • If you want to clean up the index before adding data do this
    server.deleteByQuery( "*:*" );// delete everything!
  • Construct a document
    SolrInputDocument doc1 = new SolrInputDocument();    doc1.addField( "id", "id1", 1.0f );    doc1.addField( "name", "doc1", 1.0f );    doc1.addField( "price", 10 );
  • Construct another document. Each document can be independently be added but it is more efficient to do a batch update. Every callSolrserverIs an HTTP call (this is not true for embeddedsolrserver ).

    SolrInputDocument doc2 = new SolrInputDocument();    doc2.addField( "id", "id2", 1.0f );    doc2.addField( "name", "doc2", 1.0f );    doc2.addField( "price", 20 );
  • Create a collection of documents
    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();    docs.add( doc1 );    docs.add( doc2 );
  • Add the documents to SOLR
    server.add( docs );
  • Do a commit
    server.commit();
  • To immediately commit after adding documents, you cocould use:
  UpdateRequest req = new UpdateRequest();  req.setAction( UpdateRequest.ACTION.COMMIT, false, false );  req.add( docs );  UpdateResponse rsp = req.process( server );
Streaming documents for an update

In most cases streamingupdatesolrserver will suit your needs. Alternatively, the workaround presented below can be applied.

This is the most optimal way of updating all your docs in one HTTP request.

CommonsHttpSolrServer server = new CommonsHttpSolrServer();Iterator<SolrInputDocument> iter = new Iterator<SolrInputDocument>(){     public boolean hasNext() {        boolean result ;        // set the result to true false to say if you have more documensts        return result;      }      public SolrInputDocument next() {        SolrInputDocument result = null;        // construct a new document here and set it to result        return result;      }};server.add(iter);

You may also useAddbeans (iterator <?> Beansiter)Method To write pojos

Directly adding pojos to SOLR
  • Create a Java Bean with annotations.@ FieldAnnotation can be applied to a field or a setter method. If the field name is different from the bean field name give the aliased name in the annotation itself as shown in the categories field.

import org.apache.solr.client.solrj.beans.Field; public class Item {    @Field    String id;    @Field("cat")    String[] categories;    @Field    List<String> features;  }

The@ FieldAnnotation can be applied on Setter methods as well example:

    @Field("cat")   public void setCategory(String[] c){       this.categories = c;   }

There shoshould be a corresponding getter method (without annotation) for reading attributes

  • Get an instance of server
    SolrServer server = getSolrServer();
  • Create the bean instances
    Item item = new Item();    item.id = "one";    item.categories =  new String[] { "aaa", "bbb", "ccc" };
  • Add to SOLR
   server.addBean(item);
  • Adding multiple beans together
  List<Item> beans ;  //add Item objects to the list  server.addBeans(beans);

Note -- reuse the instance of solrserver if you are using this feature (for performance)

Setting the requestwriter

Solrj lets you upload content in XML and binary format. the default is set to be XML. use the following to upload using binary format. this is the same format which solrj uses to fetch results, and can greatly improve performance as it reduces ces xml into alling overhead.

    server.setRequestWriter(new BinaryRequestWriter());

Note -- be sure you have also enabled the "binaryupdaterequesthandler" in your solrconfig. XML for example like:

    <requestHandler name="/update/javabin" class="solr.BinaryUpdateRequestHandler" />
Reading data from SOLR
  • Get an instance of server first
    SolrServer server = getSolrServer();
  • Construct a solrquery

    SolrQuery query = new SolrQuery();    query.setQuery( "*:*" );    query.addSortField( "price", SolrQuery.ORDER.asc );
  • Query the server
    QueryResponse rsp = server.query( query );
  • Get the results
 SolrDocumentList docs = rsp.getResults();
  • To read documents as beans, the bean must be annotated as given in the example.

   List<Item> beans = rsp.getBeans(Item.class);
Advanced usage

Solrj provides a APIs to create queries instead of hand coding the query. Following is an example of a faceted query.

  SolrServer server = getSolrServer();  SolrQuery solrQuery = new  SolrQuery().                setQuery("ipod").                setFacet(true).                setFacetMinCount(1).                setFacetLimit(8).                addFacetField("category").                addFacetField("inStock");  QueryResponse rsp = server.query(solrQuery);

All the setter/Add Methods return its instance. Hence these CILS can be chained

Highlighting

Highlighting parameters are set like other common parameters.

    SolrQuery query = new SolrQuery();    query.setQuery("foo");    query.setHighlight(true).setHighlightSnippets(1); //set other params as needed    query.setParam("hl.fl", "content");    QueryResponse queryResponse = getSolrServer().query(query);

Then to get back the highlight results you need something like this:

    Iterator<SolrDocument> iter = queryResponse.getResults().iterator();    while (iter.hasNext()) {      SolrDocument resultDoc = iter.next();      String content = (String) resultDoc.getFieldValue("content");      String id = (String) resultDoc.getFieldValue("id"); //id is the uniqueKey field      if (queryResponse.getHighlighting().get(id) != null) {        List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get("content");      }    }

Solrj (Last edited 2010-10-02 20:43:14 by allistaircrossley)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.