Apache Solr: Setup and Searching with Spring Boot

In Previous tutorial we have gone through basic setup and query with Solr server.

In this post i’ll show you how to index your documents and perform search with Java, especially using Spring Boot here.

Prerequisites & Assumption

Required tools

  • STS (Good to have)
  • Maven/Gradle
  • Java (:) Definitely)

Assumption

You should have Solr distribution and running, visit previous post if you don’t have.

Create Project

I am using STS here to create project, follow steps below to create project.

  • Create Spring starter Project (If you don’t know how to do it than visit my previous post).
  • Select Solr dependency from NoSQL group(shown in image below)
  • Click Finish.

You can download zip using url also: http://start.spring.io/starter.zip
?name=Boot_Solr_Basic
&groupId=com.kode12
&artifactId=bootsolrbasic
&version=0.0.1-SNAPSHOT
&description=Demo+project+for+Spring+Boot+and+Solr
&packageName=com.kode12
&type=maven-project
&packaging=jar
&javaVersion=1.8
&language=java
&bootVersion=1.4.2.RELEASE
&dependencies=data-solr

Code and Configuration

Basic project structure with necessary files looks like

Let’s look content of all required files one by one.

pom.xml

Path: classpath
Content:

Detail:
Artifact spring-boot-starter-data-solr will get all required dependency for Solr.

BootSolrBasicApplication.java

Path: com.kode12
Content:

Detail:
Automatically created and we are not using in our demo.

application.properties

Location: src/main/resources
Content:

Detail:
spring.data.solr.host is a built-in property provided by boot only
http://127.0.0.1:8983/solr/test provides host, port, and core name which is test here.

Employee.java

Location: com.kode12.vo
Content:

Detail:
This is just a pojo class and used to map document and object.
@Field annotation is can be used with property or setter method, this denotes that attribute which is marked with @Field annotation is able to take part in Solr indexing.

SolrEmployeeRepository.java

Location: com.kode12.repository
Content:

Detail:
This is same as other Repository interface which we used to in hibernate. This interface extends SolrCrudRepository where Employee is a class and Long is a Serializable field name.

Test Cases

Now we have everything ready and it’s good to go.
I am using a JUnit Test case to test some methods.

BootSolrBasicApplicationTests.java

Location: src/main/reaources
Content:

Insert your code snippet to perform operation form below list.

Insert Test Data

Get total no of documents in core

Search By Name

Search By Id

As you all know we used SolrCrudRepository which provides many useful methods, you can invoke it without any custom implementation. Explore more about SolrCrudRepository here.

This is all about basic things which we can do using spring boot, will come up with some other useful Solr tutorial in upcoming tutorials.

Share current post by copy: https://goo.gl/HAXDN0
Happy Learning!
:)

Thanks, Yogesh P