Apache Solr 6 Basic Example | JavaInUse



SolrJ Basic Example



Overview

In this tutorial we get started with SolrJ by creating a simple example using Apache Solr 6. SolrJ is an API that makes it easy for Java applications to talk to Solr. SolrJ hides a lot of the details of connecting to Solr and allows your application to interact with Solr with simple high-level methods. The center of SolrJ is the org.apache.solr.client.solrj package, which contains just five main classes. Begin by creating a SolrClient, which represents the Solr instance you want to use. Then send SolrRequests or SolrQuerys and get back SolrResponses.
In previous tutorial we configured solr for adding the following fields for the core Person-
 <field name="name" type="string" indexed="true" stored="true"/>
 <field name="age" type="int" indexed="true" stored="true"/>

In this tutorial we will create a simple SolrJ client to index and query content for the core Person.

Code for indexing the document-


package com.javainuse;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.common.SolrInputDocument;

public class SolrjExample {
	public static void main(String[] args) throws IOException,
			SolrServerException {

		CommonsHttpSolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr/person");
		
		//Create solr document
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("name", "tester11");
		doc.addField("age", 38);
		server.add(doc);
		server.commit();
	}

}

Code for querying the document-


package com.javainuse;

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.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

public class SolrJQueryExample {

	public static void main(String[] args) throws SolrServerException,
			IOException {

		CommonsHttpSolrServer solr = new CommonsHttpSolrServer(
				"http://localhost:8983/solr/person");

		SolrQuery query = new SolrQuery();
		query.setQuery("*:*");
		query.addFilterQuery("name : tester1");

		QueryResponse response = solr.query(query);
		SolrDocumentList results = response.getResults();
		
		//iterate the results
		for (int i = 0; i < results.size(); ++i) {
			System.out.println(results.get(i));
		}

	}
}



See Also

Discontinuation of Google Search Appliance- Finding the best Alternative.
Apache Solr 6 Hello World Tutorial- Getting Started with Apache Solr 6