

Table of Contents
1. Overview
In this article, we will be going to discuss how to integrate Solr with spring boot. Spring boot started data Solr is the extension of spring data which used to integrate Solr with spring boot.Need to add spring-boot-starter-data-solr maven dependency in pom.xml
Here we have discussed step by step process and complete example with output to understand spring boot with solr.
2. Example
Spring Boot Solr Project Structure
2.1 Solr Configuration
Start Solr
The first step in this example is to start solr server and verify it’s running or not.
Create Core
Create core name SpringBootDocumentExample using Solr dashboard GUI or create core command.
schema.xml
Add below fields in solr schema.xml file
<field name="id" type="string" indexed="true" stored="true" required="true" /> <field name="docType" type="text_general" indexed="true" stored="true" /> <field name="docTitle" type="text_general" indexed="true" stored="true" />
2.2 pom.xml
spring-boot-starter-data-solr
for solr
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringBootSolrExample</groupId> <artifactId>SpringBootSolrExample</artifactId> <version>1.0-SNAPSHOT</version> <description>Spring boot solr example</description> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-solr</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.3 application.properties
spring.data.solr.host
require solr url. Make sure that Solr is running on specified URL.
spring.data.solr.host=http://localhost:8983/solr
2.4 SpringBootConfig
package com.javadeveloperzone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Created by JavaDeveloperZone on 16-12-2017. */ @SpringBootApplication @ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute public class SpringBootConfig { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootConfig.class, args); // it wil start application } }
2.5 Creating a Document
Before we can query Solr we have to add documents to the index. To define a document we create a POJO called Document and add Solrj annotations to it.
package com.javadeveloperzone.model; import org.apache.solr.client.solrj.beans.Field; import org.springframework.data.annotation.Id; import org.springframework.data.solr.core.mapping.SolrDocument; @SolrDocument(solrCoreName = "SpringBootDocumentExample") public class Document { @Id @Field private String id; @Field private String docType; @Field private String docTitle; public Document() { } public Document(String id, String docType, String docTitle){ this.id = id; this.docTitle = docTitle; this.docType = docType; } public void setId(String id){ this.id = id; } public String getId(){ return this.id; } @Override public String toString() { return "Document{" + "id='" + id + '\'' + ", docType='" + docType + '\'' + ", docTitle='" + docTitle + '\'' + '}'; } public String getDocType() { return docType; } public void setDocType(String docType) { this.docType = docType; } public String getDocTitle() { return docTitle; } public void setDocTitle(String docTitle) { this.docTitle = docTitle; } }
2.5 DocumentRepository
Spring Data uses repositories to simplify the usage of various data access technologies. A repository is basically an interface whose implementation is dynamically generated by Spring Data on application start.
Here we have created four methods to get documents based on criteria.Refer comments for more details.
package com.javadeveloperzone.repository; import java.util.List; import com.javadeveloperzone.model.Document; import org.springframework.data.solr.repository.SolrCrudRepository; public interface DocumentRepository extends SolrCrudRepository<Document, String> { List<Document> findByDocTitleEndsWith(String title); // find documents whose docTitle ends with specified string List<Document> findByDocTitleStartsWith(String title); // find documents whose docTitle starts with specified string List<Document> findByDocTypeEndsWith(String type); //find documents whose docType ends with specified string List<Document> findByDocTypeStartsWith(String type);//find documents whose docType start with specified string }
2.7 SolrDocumentController
package com.javadeveloperzone.controller; import com.javadeveloperzone.model.Document; import com.javadeveloperzone.repository.DocumentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by JavaDeveloperZone on 16-12-2017. */ @RestController public class SolrDocumentController { @Autowired private DocumentRepository documentRepository; @RequestMapping("/") public String SpringBootSolrExample() { return "Welcome to Spring Boot solr Example"; } @RequestMapping("/delete") public String deleteAllDocuments() { try { //delete all documents from solr core documentRepository.deleteAll(); return "documents deleted succesfully!"; }catch (Exception e){ return "Failed to delete documents"; } } @RequestMapping("/save") public String saveAllDocuments() { //Store Documents documentRepository.save(Arrays.asList(new Document("1", "pdf","Java Dev Zone"), new Document("2", "msg", "subject:reinvetion"), new Document("3", "pdf", "Spring boot sessions"), new Document("4", "docx", "meeting agenda"), new Document("5", "docx", "Spring boot + solr"))); return "5 documents saved!!!"; } @RequestMapping("/getAll") public List<Document> getAllDocs() { List<Document> documents = new ArrayList<>(); // iterate all documents and add it to list for (Document doc : this.documentRepository.findAll()) { documents.add(doc); } return documents; } }
2.8 Build Application
[INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building SpringBootSolrExample 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ SpringBootSolrExample --- [INFO] Deleting G:\study\Blogs\Applications\SpringBootSolrExample\target [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS
2.9. Run Application
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2017-12-18 22:25:46.113 INFO 1588 --- [ main] com.javadeveloperzone.SpringBootConfig : Starting SpringBootConfig on nitin-PC with PID 1588 (G:\study\Blogs\Applications\SpringBootSolrExample\target\classes started by nitin in G:\study\Blogs\Applications\SpringBootSolrExample) 2017-12-18 22:26:04.032 INFO 1588 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-12-18 22:26:04.033 INFO 1588 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 17280 ms 2017-12-18 22:26:05.457 INFO 1588 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-12-18 22:26:05.706 INFO 1588 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-12-18 22:26:05.715 INFO 1588 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-12-18 22:26:05.716 INFO 1588 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-12-18 22:26:05.716 INFO 1588 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2017-12-18 22:26:12.703 INFO 1588 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2017-12-18 22:26:13.176 INFO 1588 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-12-18 22:26:13.176 INFO 1588 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-12-18 22:26:13.738 INFO 1588 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-12-18 22:26:17.962 INFO 1588 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-12-18 22:26:20.543 INFO 1588 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2017-12-18 22:26:20.743 INFO 1588 --- [ main] com.javadeveloperzone.SpringBootConfig : Started SpringBootConfig in 38.769 seconds (JVM running for 43.934)
2.10 Output
1 Save Documents
http://localhost:8080/save
After executing above request Solr core contains five documents.
2 View Documents
http://localhost:8080/getAll
3 Delete Documents
http://localhost:8080/delete
After executing above request solr core contains zero documents as below.
3. References
1 comment. Leave new
Can I get source code in Github?