Integrating Elasticsearch with Spring Boot: A Step‑by‑Step Guide

This article explains how to integrate Elasticsearch into a Spring Boot project, covering version compatibility, supported access methods, dependency setup, configuration, entity mapping with annotations, repository creation, and unit testing to verify successful indexing and retrieval.

DataFunSummit
DataFunSummit
DataFunSummit
Integrating Elasticsearch with Spring Boot: A Step‑by‑Step Guide

After introducing the features and advantages of Elasticsearch, this guide demonstrates how to implement a search engine in a Spring Boot project step by step.

1. Spring Boot Support for Elasticsearch

Before Spring Boot, using Elasticsearch required extensive client wrappers and complex configuration. Spring Boot simplifies this with the spring-boot-starter-data-elasticsearch starter, which provides convenient access to Elasticsearch data.

Note that Elasticsearch versions 5.x, 6.x, and 7.x differ significantly, and Spring Data Elasticsearch, Spring Boot, and Elasticsearch have strict version compatibility. For example, Spring Boot 2.1 pairs with Spring Data Elasticsearch 3.1.2. The official compatibility matrix is shown below.

Spring Data Elasticsearch

Spring Boot

Elasticsearch

3.2.x

2.2.x

6.8.4

3.1.x

2.1.x

6.2.2

3.0.x

2.0.x

5.5.0

2.1.x

1.5.x

2.4.0

It is recommended to follow the official version mapping to avoid compatibility issues.

2. Ways to Operate Elasticsearch in Spring Boot

Because of version compatibility concerns, Spring Boot offers several ways to interact with Elasticsearch, such as Repositories, JestClient, and Rest API. Spring currently recommends using the Repository and RestTemplate approaches, as illustrated in the diagram below.

Spring Boot Elasticsearch Architecture
Spring Boot Elasticsearch Architecture

Spring Boot provides ElasticsearchRepository and ElasticsearchRestTemplate for CRUD operations on indexed data.

ElasticsearchRepository : Extends Spring Data's Repository interface, supporting database‑like CRUD operations and named queries.

ElasticsearchRestTemplate : A wrapper around Elasticsearch's Rest API, offering extensive query capabilities similar to other Spring Template classes.

3. Integrating Elasticsearch into a Spring Boot Project

The spring-boot-starter-data-elasticsearch starter provides convenient data retrieval functions. The integration steps are as follows:

1. Add the Elasticsearch dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2. Configure Elasticsearch

spring.elasticsearch.rest.uris=http://10.2.1.231:9200

This property sets the Elasticsearch server address; multiple addresses can be separated by commas. Configuration keys may vary across Spring Data Elasticsearch versions.

3. Create a document entity

Define a Java class annotated with @Document to map it to an Elasticsearch index. Example:

@Document(indexName = "book", replicas = 0)
public class Book {
    @Id
    private Long id;
    @Field(analyzer = "ik_max_word", type = FieldType.Text)
    private String bookName;
    @Field(type = FieldType.Keyword)
    private String author;
    private float price;
    private int page;
    @Field(type = FieldType.Keyword, fielddata = true)
    private String category;
    // getters, setters, constructors omitted for brevity
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{\"Book\":{");
        sb.append("\"id\":").append(id);
        sb.append(",\"bookName\":\"").append(bookName).append('"');
        sb.append(",\"page\":\"").append(page).append('"');
        sb.append(",\"price\":\"").append(price).append('"');
        sb.append(",\"category\":\"").append(category).append('"');
        sb.append(",\"author\":\"").append(author).append('"');
        sb.append("}}"");
        return sb.toString();
    }
}

The @Document annotation maps the class to an Elasticsearch index and defines settings such as indexName, shards, replicas, and refreshInterval. The @Id marks the primary key, while @Field configures field types, indexing, storage, and analyzers (e.g., ik_max_word).

4. Create a repository interface

public interface BookRepository extends ElasticsearchRepository<Book, Integer> {
    List<Book> findByBookNameLike(String bookName);
}

This interface works similarly to JPA repositories, enabling custom query methods.

5. Verify with a unit test

@Test
public void testSave() {
    Book book = new Book();
    book.setId(1);
    book.setBookName("Journey to the West");
    book.setAuthor("Wu Cheng'en");
    repository.save(book);
    Book newBook = repository.findById(1).orElse(null);
    System.out.println(newBook);
}

Running the test inserts a document into Elasticsearch and retrieves it by ID, confirming successful integration.

Test Result
Test Result

The output shows that the indexed data was saved correctly and can be queried by its ID, demonstrating that Elasticsearch has been successfully integrated into the Spring Boot application.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javasearch enginebackend-developmentElasticsearchSpring Boot
DataFunSummit
Written by

DataFunSummit

Official account of the DataFun community, dedicated to sharing big data and AI industry summit news and speaker talks, with regular downloadable resource packs.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.