SolrJ Client API

SolrJ is built in Java technologies to connect with Solr from a Java application over HTTP.

Solr and SolrJ both are built-in Java technologies, so communication between them is easy and straightforward. While uploading a document, Solr needs all documents in XML or JSON format. SolrJ uses an internal binary protocol by default, called JavaBin. Normally, the client application sends an update request using HTTP POST with JSON or XML format, but the SolrJ client can send the update request as JSON, XML, or Solr's internal binary JavaBin format. The JavaBin protocol is more efficient than XML or JSON.

Apart from normal communication to Solr, SolrJ also supports load balancing across Solr nodes, automatically discovers locations of Solr servers in a SolrCloud mode, and easily handles bulk indexing for large amounts of data. It is also possible to embed Solr within a Java application and connect to it directly without establishing an HTTP connection to the server.

To create a SolrJ client, we do not need to worry much about the libraries; SolrJ libraries are already available in the Solr structure. Just navigate to %SOLR_HOME%/dist. You will find solr-solrj.jar (with a specific number); copy that jar and add it to your Java application build path. That's the only library required for your SolrJ implementation! Additionally needed libraries are available inside the %SOLR_HOME%/dist/solrj-lib directory; add all those to the Java application class path. Once the configuration is done, we can communicate to Solr using SolrJ.

Here is the simple SolrJ client that connects to the Solr API to run a search query:

package com.demo.solr.solrj;

import java.io.IOException;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrJSearchClientAPI {
public static Logger _log = LoggerFactory.getLogger(SolrJSearchClientAPI.class);

public static void main(String[] args){

String hostURL = "http://localhost:8983/solr/techproducts";
HttpSolrClient solr = new HttpSolrClient.Builder(hostURL).build();

//set response parser
//solr.setParser(new XMLResponseParser());

//query configurations
SolrQuery query = new SolrQuery();
query.set("q", "ipod");

query.set("fl", "id,name");
/*alternate way to configure fl parameter
* query.setFields("id","name");*/

/*select different request handler
query.setRequestHandler("/spell");*/

try {
QueryResponse response = solr.query(query);
_log.info(response.toString());
} catch (IOException e) {
_log.error(e.getMessage());
} catch (SolrServerException e) {
_log.error(e.getMessage());
}
}
}

Response:

{responseHeader={status=0,QTime=1,params={q=ipod,fl=id,name,wt=javabin,version=2}},response={numFound=3,start=0,docs=[SolrDocument{id=IW-02, name=iPod & iPod Mini USB 2.0 Cable}, SolrDocument{id=F8V7067-APL-KIT, name=Belkin Mobile Power Cord for iPod w/ Dock}, SolrDocument{id=MA147LL/A, name=Apple 60 GB iPod with Video Playback Black}]},spellcheck={suggestions={},correctlySpelled=false,collations={}}}

To query from the Solr instances running on the cloud using a zkHostString key:

String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
CloudSolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();

Let's run a client that adds a document (builds an index). In our selected core, techproducts, let's add one more product:

package com.demo.solr.solrj;

import java.io.IOException;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrJAddDocumentClientAPI {
public static Logger _log = LoggerFactory.getLogger(SolrJAddDocumentClientAPI.class);

public static void main(String[] args){

String hostURL = "http://localhost:8983/solr/techproducts";
HttpSolrClient solr = new HttpSolrClient.Builder(hostURL).build();

SolrInputDocument document = new SolrInputDocument();

document.addField("id","HPPRO445");
document.addField("name","HP Probook 445");
document.addField("manu","Hewlett Packard");
document.addField("features", "8GB DDR3LSD RAM");
document.addField("weight","1.2");
document.addField("price","800");

try {
UpdateResponse response = solr.add(document);
solr.commit();
_log.info(response.toString());
} catch (SolrServerException e) {
_log.error(e.getMessage());
} catch (IOException e) {
_log.error(e.getMessage());
}
}
}

Through this client, a new product, HP Probook 445, has been added to techproducts. Now if we search for the query q=HP Probook 445, we will get the following response if the product was added successfully:

{
"responseHeader":{
"status":0,
"QTime":8,
"params":{
"q":"HP Probook 445"}},
"response":{"numFound":1,"start":0,"docs":[
{
"id":"HPPRO445",
"name":"HP Probook 445",
"manu":"Hewlett Packard",
"features":["8GB DDR3LSD RAM"],
"weight":1.2,
"price":800.0,
"price_c":"800,USD",
"_version_":1592089897249800192,
"price_c____l_ns":80000}]
},
"spellcheck":{
"suggestions":[],
"correctlySpelled":false,
"collations":[]}
}

Here we have added a single product, but if we have a product list (bulk) to add, we can do it like this:

package com.demo.solr.solrj;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrJAddDocumentsClientAPI {

public static Logger _log = LoggerFactory.getLogger(SolrJAddDocumentsClientAPI.class);

public static void main(String[] args) {

String hostURL = "http://localhost:8983/solr/techproducts";
HttpSolrClient solr = new HttpSolrClient.Builder(hostURL).build();

List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>();

SolrInputDocument document1 = new SolrInputDocument();
document1.addField("id","id1");
document1.addField("name","product1");
documentList.add(document1);

SolrInputDocument document2 = new SolrInputDocument();
document2.addField("id","id2");
document2.addField("name","product2");
documentList.add(document2);

//...
//...

SolrInputDocument documentn = new SolrInputDocument();
documentn.addField("id","idn");
documentn.addField("name","productn");
documentList.add(documentn);

try {
UpdateResponse response = solr.add(documentList);
solr.commit();
_log.info(response.toString());
} catch (SolrServerException e) {
_log.error(e.getMessage());
} catch (IOException e) {
_log.error(e.getMessage());
}
}
}

For bulk processes, Solr provides a thread-safe class called ConcurrentUpdateSolrClient, which first holds all the documents in buffers and then writes to the HTTP connections.

Using SolrJ, we can delete a document (index) as follows:

package com.demo.solr.solrj;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrJDeleteDocumentClientAPI {
public static Logger _log = LoggerFactory.getLogger(SolrJDeleteDocumentClientAPI.class);

public static void main(String[] args){

String hostURL = "http://localhost:8983/solr/techproducts";
HttpSolrClient solr = new HttpSolrClient.Builder(hostURL).build();

try {
UpdateResponse response = solr.deleteById("HPPRO445");
solr.commit();
_log.info(response.toString());
} catch (SolrServerException e) {
_log.error(e.getMessage());
} catch (IOException e) {
_log.error(e.getMessage());
}
}
}

Now if we search for the query q=HP Probook 445, it should not return any results if it was deleted successfully. In the same way, we delete documents in bulk:

solr.deleteById(List<String> ids);
After adding/updating/deleting, don't forget to commit the transaction using solr.commit(); otherwise, the indexes will not be affected.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.234.70