• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Integrate Spring Data ElasticSearch in Spring Boot

October 23, 2017 by javainterviewpoint Leave a Comment

In this article, we will learn how to Integrate Spring Data ElasticSearch in Spring Boot Application. ElasticSearch is one of the popular full-text search engine based on Lucene. We will be extending ElasticSearchRepository provided by Spring Data. Lets dig into the code

Folder Structure:

Integrate Spring Data ElasticSearch in Spring Boot

  1. Create a Maven Webapp project (maven-archetype-quickstart) “SpringBootElasticSearch” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <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>com.javainterviewpoint</groupId>
      <artifactId>SpringBootElasticSearch</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>SpringBootElasticSearch</name>
      <url>https://www.javainterviewpoint.com/</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.1.RELEASE</version>
    	</parent>
    
    	<dependencies>
    		  <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            </dependency> 
            
           	<dependency>
                <groupId>net.java.dev.jna</groupId>
                <artifactId>jna</artifactId>
                <scope>runtime</scope>
            </dependency>
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    				<configuration>
    					<source>1.8</source>
    					<target>1.8</target>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
  3. Create the Java classes SpringBootElasticSearchApp.java, Student.java and StudentRepository.java under com.javainterviewpoint folder.

Other Posts which you may like …

  • Spring Boot Hello World Example with Maven
  • Spring Boot Hello World Example in Eclipse
  • Spring Boot RESTful Web Services Example
  • Spring Boot Kotlin RESTful Web Services CRUD Example
  • How to Create Deployable WAR | Spring Boot | SpringBootServletInitializer
  • Spring Boot – How to Change Embedded Tomcat default port
  • Fix missing src/main/java folder in Eclipse Maven Project
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • JAX-RS REST @Produces both XML and JSON Example
  • JAX-RS REST @Consumes both XML and JSON Example
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services
  • Spring REST Hello World Example – JSON and XML responses
  • ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
  • Fix missing src/main/java folder in Eclipse
  • Spring MVC CRUD Example with MySql + JdbcTemplate

Integrate Spring Data ElasticSearch in Spring Boot

Dependency Tree

[INFO] com.javainterviewpoint:SpringBootElasticSearch:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-data-elasticsearch:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] |  |  +- org.springframework:spring-core:jar:4.3.6.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:compile
[INFO] |  \- org.springframework.data:spring-data-elasticsearch:jar:2.1.0.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:4.3.6.RELEASE:compile
[INFO] |     |  +- org.springframework:spring-aop:jar:4.3.6.RELEASE:compile
[INFO] |     |  +- org.springframework:spring-beans:jar:4.3.6.RELEASE:compile
[INFO] |     |  \- org.springframework:spring-expression:jar:4.3.6.RELEASE:compile
[INFO] |     +- org.springframework:spring-tx:jar:4.3.6.RELEASE:compile
[INFO] |     +- org.springframework.data:spring-data-commons:jar:1.13.0.RELEASE:compile
[INFO] |     +- commons-lang:commons-lang:jar:2.6:compile
[INFO] |     +- joda-time:joda-time:jar:2.9.7:compile
[INFO] |     +- org.elasticsearch:elasticsearch:jar:2.4.4:compile
[INFO] |     |  +- org.apache.lucene:lucene-core:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-backward-codecs:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-analyzers-common:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-queries:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-memory:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-highlighter:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-queryparser:jar:5.5.2:compile
[INFO] |     |  |  \- org.apache.lucene:lucene-sandbox:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-suggest:jar:5.5.2:compile
[INFO] |     |  |  \- org.apache.lucene:lucene-misc:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-join:jar:5.5.2:compile
[INFO] |     |  |  \- org.apache.lucene:lucene-grouping:jar:5.5.2:compile
[INFO] |     |  +- org.apache.lucene:lucene-spatial:jar:5.5.2:compile
[INFO] |     |  |  +- org.apache.lucene:lucene-spatial3d:jar:5.5.2:compile
[INFO] |     |  |  \- com.spatial4j:spatial4j:jar:0.5:compile
[INFO] |     |  +- com.google.guava:guava:jar:18.0:compile
[INFO] |     |  +- org.elasticsearch:securesm:jar:1.0:compile
[INFO] |     |  +- com.carrotsearch:hppc:jar:0.7.1:compile
[INFO] |     |  +- com.fasterxml.jackson.dataformat:jackson-dataformat-smile:jar:2.8.6:compile
[INFO] |     |  +- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:jar:2.8.6:compile
[INFO] |     |  +- com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:jar:2.8.6:compile
[INFO] |     |  +- io.netty:netty:jar:3.10.6.Final:compile
[INFO] |     |  +- com.ning:compress-lzf:jar:1.0.2:compile
[INFO] |     |  +- com.tdunning:t-digest:jar:3.0:compile
[INFO] |     |  +- org.hdrhistogram:HdrHistogram:jar:2.1.6:compile
[INFO] |     |  +- commons-cli:commons-cli:jar:1.3.1:compile
[INFO] |     |  \- com.twitter:jsr166e:jar:1.1.0:compile
[INFO] |     +- com.fasterxml.jackson.core:jackson-core:jar:2.8.6:compile
[INFO] |     +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.6:compile
[INFO] |     |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO] |     +- org.slf4j:slf4j-api:jar:1.7.22:compile
[INFO] |     \- org.slf4j:jcl-over-slf4j:jar:1.7.22:compile
[INFO] \- net.java.dev.jna:jna:jar:4.2.2:runtime

application.properties

Place the application.properties file under the src/resources folder

#Spring Data ElasticSearch Configuration
spring.data.elasticsearch.cluster-nodes=localhost:9300

StundentRepository.java

package com.javainterviewpoint;

import java.util.List;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends ElasticsearchRepository<Student,Long>
{
    List<Student> findByName(String name);
    
    List<Student> findByAge(int age);
}

We will be extending ElasticsearchRepository, Spring Data will create an implementation of StudentRepository automatically during runtime.

SpringBootElasticSearchApp.java

package com.javainterviewpoint;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages =
{ "com.javainterviewpoint" })
public class SpringBootElasticSearchApp implements CommandLineRunner
{

    @Resource
    StudentRepository studentRepository;

    public static void main(String[] args)
    {
        SpringApplication.run(SpringBootElasticSearchApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception
    {
        Student student1 = new Student(1, "JIP1", 11);
        Student student2 = new Student(2, "JIP2", 22);
        Student student3 = new Student(3, "JIP3", 33);
        Student student4 = new Student(4, "JIP4", 44);
        Student student5 = new Student(5, "JIP5", 55);
        Student student6 = new Student(6, "JIP6", 66);

        // Saving Student to StudentRepository
        studentRepository.save(student1);
        studentRepository.save(student2);
        studentRepository.save(student3);
        studentRepository.save(student4);
        studentRepository.save(student5);
        studentRepository.save(student6);

        // Getting all Students
        System.out.println("***** Getting All Students *******");
        for (Student student : studentRepository.findAll())
        {
            System.out.println(student);
        }
        
        // Getting the student with Id 4
        System.out.println("***** Student with Id 4 *******");
        System.out.println(studentRepository.findOne((long) 4));


        // Getting the student with Name JIP3
        System.out.println("***** Student with Name JIP3 *******");
        System.out.println(studentRepository.findByName("JIP3"));

        // Getting the student with Age 22
        System.out.println("***** Student with ID 2 *******");
        System.out.println(studentRepository.findByAge(22));
        
        //Delete the Student with Id 5
        studentRepository.delete((long) 5);
        //Check whether the student is deleted or not
        System.out.println("***** Student with id 5 : "+(studentRepository.findOne((long) 5)));
    }
}

The SpringBootElasticSearchApp class main() method is the triggering point of our application, it in-turn calls Spring Boot’s SpringApplication class run() method which bootstrap our SpringBootElasticSearchApp application. We have used @Repository annotation to inject our StudentRepository.

Student.java

package com.javainterviewpoint;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "javainterviewpoint", type = "student")
public class Student
{
    @Id
    private long id;
    
    private String name;
    
    private long age;

    public Student()
    {
        super();
    }
    public Student(long id, String name, long age)
    {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public long getId()
    {
        return id;
    }
    public void setId(long id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public long getAge()
    {
        return age;
    }
    public void setAge(long age)
    {
        this.age = age;
    }
    
    @Override
    public String toString()
    {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

We have used @Document annotation for Spring Data Elasticsearch in order to denote our Student class as an Spring Data module. Our Student class is a simple pojo class consisting of getters and setters for the properties id, name, age.

Output:
Download elasticsearch-2.4.5 from https://www.elastic.co/ after extracting goto “elasticsearch-2.4.5\bin” and run “elasticsearch.bat”
Spring Data ElasticSearch
Run SpringBootElasticSearchApp using “mvn spring-boot:run”

  ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2017-10-17 16:22:02.217  INFO 6532 --- [           main] c.j.SpringBootElasticSearchApp           : Starting SpringBootElasticSearchApp on DA56CZ8VD02 with PID 6532 (C:\Jackson\sts-3.8.4.RELEASE\JIPWorkspace\SpringBootElasticSearch\target\classes started by xbbl47m in C:\Jackson\sts-3.8.4.RELEASE\JIPWorkspace\SpringBootElasticSearch)
2017-10-17 16:22:02.220  INFO 6532 --- [           main] c.j.SpringBootElasticSearchApp           : No active profile set, falling back to default profiles: default
2017-10-17 16:22:02.278  INFO 6532 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]5ad851c9: startup date [Tue Oct 17 16:22:02 IST 2017]; root of context hierarchy
2017-10-17 16:22:02.976  INFO 6532 --- [           main] org.elasticsearch.plugins                : [Deadly Ernest] modules [], plugins [], sites []
2017-10-17 16:22:03.771  INFO 6532 --- [           main] o.s.d.e.c.TransportClientFactoryBean     : adding transport node : localhost:9300
2017-10-17 16:22:04.296  INFO 6532 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
***** Getting All Students *******
Student [id=5, name=JIP5, age=55]
Student [id=2, name=JIP2, age=22]
Student [id=4, name=JIP4, age=44]
Student [id=6, name=JIP6, age=66]
Student [id=1, name=JIP1, age=11]
Student [id=3, name=JIP3, age=33]
***** Student with Id 4 *******
Student [id=4, name=JIP4, age=44]
***** Student with Name JIP3 *******
[Student [id=3, name=JIP3, age=33]]
***** Student with ID 2 *******
[Student [id=2, name=JIP2, age=22]]
***** Student with id 5 : null

   Download Source Code

Filed Under: Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·