curl -XGET "http://localhost:9200"
Elasticsearch with Spring Boot + Spring Data
Upasana | November 18, 2020 | | 14 views
In this article, we will discuss how to configure & use Elasticsearch Engine with Spring Boot & Spring Data using High Level REST Client provided by Elasticsearch.
Prerequisites
-
Java 8 or 11
-
Gradle
-
Elasticsearch 7.10
-
Spring Boot 2.4.0
-
Spring Data 4.1
Elasticsearch
Elasticsearch is an open source, distributed full-text search engine that provides REST api for indexing, searching etc. The major components of elasticsearch are:
- Document
-
Documents are JSON objects that are stored within an Elasticsearch index and are considered as the base unit of storage.
- Index
-
An index is like a database in a relational database. It has mapping which defines the type of document. An index maps to one or more primary shards and can have zero or more replica shards.
- Shard
-
Horizontally splits an index to distribute data around the cluster. The more the size of index, more shards are generally needed for its optimal performance. In Lucene terminology, Shard is a single Lucene index which contains part of documents from an Elasticsearch Index.
- Replica
-
Copy of index’s shard is known as replica, it is mainly fail-safe mechanism of Elasticsearch. This acts as a backup when a node crashes. Replicas also serve read requests, so adding replicas can help to increase search performance.
You need to make sure that Elasticsearch is up and running locally on port 9200, using the below command:
Gradle dependencies
First step is to create a Spring Boot application, you can do so by visiting https://start.spring.io
plugins {
id "java"
id 'org.springframework.boot' version "2.4.0"
id "io.spring.dependency-management" version "1.0.10.RELEASE"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-elasticsearch") (1)
}
1 | Spring data elasticsearch module |
Elasticsearch configuration
Spring Boot 2.4.0 does not require any special configuration for ElasticSearch, as everything is taken care by ElasticsearchRestClientAutoConfiguration
configuration class. We just need to provide the below configuration in application yal to trigger the automatic bean creation:
spring.elasticsearch.rest.uris: http://localhost:9200
spring.elasticsearch.rest.username: <username>
spring.elasticsearch.rest.password: <password>
Since TransportClient
is deprecated in favour of High Level REST Client, we will not discuss TransportClient
in this article.
If you want to customize the elastic search configuration, you can provide a bean of type …. TODO…
Java implementation
We need to create a main class for running spring boot application, model classes for Spring data elasticsearch, repository and service classes.
Entity class
@Document(indexName="books")
class Book {
@Id
private String id;
@Field(type = FieldType.text)
private String name;
@Field(type = FieldType.text)
private String summary;
@Field(type = FieldType.Integer)
private Integer price;
// getter/setter ...
}
Repository class
We need to define a domain class-specific repository interface for each entity. Typically, your repository interface extends Repository
, CrudRepository
, PagingAndSortingRepository
or ElasticsearchRepository
. ElasticsearchRepository interface extends PagingAndSortingRepository, thus enabling built in support for paging and sorting.
public interface BookRepository extends ElasticsearchRepository<Book, String> {
Page<Book> findByName(String name, Pageable pageable);
}
Service layer
Spring data Elasticsearch auto-creates indexes based on the domain mapping. But we can create indexes manually too using ElasticsearchTemplate
.
In this class we will explore:
-
Creating indexes manually
-
Indexing a document
-
Searching/paging documents
-
Updating a document
-
Deleting a document
-
Adding a custom method to repository
-
Partial updates to document
@Service
class BookService {
@Autowired
BookRepository bookRepository;
@Autowired
ElasticsearchTemplate elasticsearchTemplate;
public void createIndex() {
elasticsearchTemplate.indexOps(Book.class).create();
}
public void create() {
Book book = new Book();
bookRepository.save(book);
}
}
Spring Boot App
We need to create a main class that will bootstrap the spring container using a main method. This is the entrypoint for our spring boot application.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ElasticApp {
public static void main(String[] args) {
SpringApplication.run(Myapplication.class, args);
}
}
Top articles in this category:
- Spring Data ElasticSearch with Basic Auth
- Redis rate limiter in Spring Boot
- Sendgrid Dynamic Templates with Spring Boot
- Prevent Lost Updates in Database Transaction using Spring Hibernate
- Spring Boot 2.0 Reactive Web Performance Metrics
- Testing web layer in Spring Boot using WebMvcTest
- Basic Auth Security in Spring Boot 2