Configuring Spring Boot with ElasticSearch

Elasticsearch is an open-source, RESTful, distributed search/analytics engine built on Apache Lucene. In this tutorial we will learn how to connect to it from Spring Boot and store data in it.

Obviously, the first requirement is to install all products (Docker images are also available on DockerHub anyway). You can download the latest stable version of all ELK products at: https://www.elastic.co/downloads

Once downloaded, install the zip file in a folder of your like and you are done with the installation.

Creating the Spring Boot Project

If you are developing a simple Standalone application, all you need are is ElasticSearch dependency. From the CLI execute:

$ spring init -ddata-elasticsearch -artifactId data-elasticsearch-demo 

The following dependencies will be added:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependencies>
                
      <dependency>
                      
         <groupId>org.springframework.boot</groupId>
                      
         <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
              
      </dependency>
           
      <dependency>
                  
         <groupId>org.springframework.boot</groupId>
                  
         <artifactId>spring-boot-starter-web</artifactId>
              
      </dependency>
            
      <dependency>
                  
         <groupId>org.springframework.boot</groupId>
                  
         <artifactId>spring-boot-starter-test</artifactId>
                  
         <scope>test</scope>
              
      </dependency>
       
   </dependencies>
    
</project>

Before we start coding, it is important that we provide address and port of your ElasticSearch server, which by default is:

spring.data.elasticsearch.cluster-nodes=localhost:9300 

Coding the Spring Boot application

We will need at first a model object. We can call it Person:

package com.example.elasticsearch.model;

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

@Document(indexName = "springbootdemo", type = "person")
public class Person {
  @Id private String id;
  private String firstname;
  private String lastname;
  private int age;

  public Person() {}

  public Person(String id, String firstname, String lastname, int age) {
    this.id = id;
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public String getFirstname() {
    return this.firstname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public String getLastname() {
    return this.lastname;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getAge() {
    return this.age;
  }

  public String toString() {
    String info =
        String.format(
            "Person Info: id = %s, firstname = %s, lastname = %s, age = %d",
            id, firstname, lastname, age);
    return info;
  }
}

Then, we need a Repository interface that extends org.springframework.data.elasticsearch.repository.ElasticsearchRepository to provide CRUD access to our Model:

package com.example.elasticsearch.repository;

import java.util.List;
import com.example.elasticsearch.model.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface PersonRepository extends ElasticsearchRepository<Person, String> {
  List<Person> findByFirstname(String firstname);

  List<Person> findByAge(int age);
}

Finally, we will add an Application class which bootstraps SpringBoot and insert some documents in ElasticSearch:

package com.example.elasticsearch;
import java.util.List;
import javax.annotation.Resource;
import com.example.elasticsearch.model.Person;
import com.example.elasticsearch.repository.PersonRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class SpringBootElasticSearchApplication implements CommandLineRunner {
  @Resource PersonRepository personRepository;
  public static void main(String[] args) {
    SpringApplication.run(SpringBootElasticSearchApplication.class, args);
  }
  @Override public void run(String...arg0) throws Exception {
    Person p1 = new Person("1", "Jack", "Smith", 20);
    Person p2 = new Person("2", "Lucas", "Derrik", 30);
    Person p3 = new Person("3", "Andy", "Miller", 40);
    System.out.println("Save Persons");
    personRepository.save(p1);
    personRepository.save(p2);
    personRepository.save(p3);
    // findAll
    System.out.println("Find All");
    Iterable < Person > persons = personRepository.findAll();
    persons.forEach(System.out::println);
    // find customers by firstname = Peter         
    System.out.println("Find by firstname is Jack");
    List < Person > jack = personRepository.findByFirstname("Jack");
    jack.forEach(System.out::println);
    // find persons having age = 20         
    System.out.println("Find by age = 20");
    List < Person > pers_age_20 = personRepository.findByAge(20);
    pers_age_20.forEach(System.out::println);
    // delete a person having age = 20
    System.out.println("Delete a Person having age = 20");
    personRepository.delete(pers_age_20.get(0));
  }
}

That’s all. Run your application as you prefer (for example with java -jar target/application.jar) and check in your Elastic Search logs:

[2018-12-14T10:20:06,976][INFO ][o.e.c.m.MetaDataCreateIndexService] [1VrMuHj] [springbootdemo] creating index, cause [api], templates [], shards [5]/[1], mappings [] 

You can use Elastic Search REST API to check the list of indexes:

$ curl http://localhost:9200/_cat/indices?v health status index                                         uuid                   pri rep docs.count docs.deleted store.size pri.store.size yellow open   springbootdemo                                FMclnijGTiieo3iXzSLdtA   5   1          2            0      9.3kb          9.3kb 

Great. We can also query for entries in our index as follows:

 curl http://localhost:9200/springbootdemo/_search?pretty=true&q=*:* [1] 26576 ~:$ {   "took" : 1,   "timed_out" : false,   "_shards" : {     "total" : 5,     "successful" : 5,     "skipped" : 0,     "failed" : 0   },   "hits" : {     "total" : 2,     "max_score" : 1.0,     "hits" : [       {         "_index" : "springbootdemo",         "_type" : "person",         "_id" : "2",         "_score" : 1.0,         "_source" : {           "firstname" : "Lucas",           "lastname" : "Derrik",           "age" : 30         }       },       {         "_index" : "springbootdemo",         "_type" : "person",         "_id" : "3",         "_score" : 1.0,         "_source" : {           "firstname" : "Andy",           "lastname" : "Miller",           "age" : 40         }       }     ]   } } 

Enjoy Spring Boot and Elastic Search!

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon