What is Apache Solr:
Apache Solr is a search sever that includes the full-text search engine called Apache Lucene. It takes the piece of information (called documents) that are indexed according to the cores. When a query is performed, solr goes through the index and return the matching documents.
Now let’s start the hands-on.
Step 1: Install Solr from the following link.
Step 2: Start the solr on your local.
Go to the directory and on the terminal type:
bin/solr start
Now before we go further,
click here just go through the basic query parameters used in Solr.
Well it’s time to code.
Step 3: Add maven dependency in pom.xml
org.apache.solr
solr-solrj
6.4.1
Step 4: Create an object of SolrClient and initialize it with the URI & port being used (byDefault: 8983).
SolrClient client = new HttpSolrClient("http://my-solr-server:8983/solr");
Step 5: Create an object of SolrQuery
SolrQuery query = new SolrQuery();
query.setParam(CommonParams.QT, coreName); //optional
CommonParams provide the parameters used in Solr. QT stands for query type that selects which Request Handler should handle the request.
For this coreName you can use the following functions. The functioning of the following functions is exactly the same as of the basic parameters used in Solr.
query.add(CommonParams.START, “value”);
query.add(CommonParams.ROWS, “value”);
query.add(CommonParams.FL, “fieldName”);
query.addSort("field
Name
",
ORDER.desc); //
Order.asc
for asscending
query.add(CommonParams.Q, “fieldName:fieldValue”);
query.add(CommonParams.FQ, “fieldName:fieldValue”);
Step 6: Get the response from Solr
QueryResponse response = client.query(coreName, query);
To get the results from the response use the function
response.getResults();
To know the number of rows retrieved use the function
response.getResults().getNumFound();
response.getResults() provides documents and it can be traversed using SolrDocument object.
SolrDocument doc = new SolrDocument();
for(doc : response.getResults())
Three basic functions that you need to know for using SolrDocument onject are:
doc.getFieldNames();
doc.getFieldValue(“fieldName”);
doc.getFirstValue(“completeFieldsSet”);
Hope it would be helpful. Go try it out.
References:
- https://cwiki.apache.org/confluence/display/solr/Common+Query+Parameters
- https://cwiki.apache.org/confluence/display/solr/Apache+Solr+Reference+Guide
Excellent
thanks