Rest API search engine with Spring Boot and Spring Data Elasticsearch
--
In this story, we’ll see how to use Spring Boot with Spring Data Elasticsearch.
· Prerequisites
· Overview
∘ What is Elasticsearch?
∘ Why Elasticsearch?
∘ Elasticsearch Setup with Docker
· Getting Started
∘ Configuring Elasticsearch in Spring Boot
∘ Elasticsearch Object Mapping
∘ Elasticsearch Repositories
∘ Service Layer
∘ Book Controller
· Testing
· Conclusion
· References
Prerequisites
This is the list of all the prerequisites:
- Spring Boot 3.0.2
- Maven 3.8.+
- Java 17
- Postman / insomnia or any other API testing tool.
- Docker installed
Overview
What is Elasticsearch?
Elasticsearch is a distributed, free and open search and analytics engine for all types of data, including textual, numerical, geospatial, structured, and unstructured. Elasticsearch is built on Apache Lucene and was first released in 2010 by Elasticsearch N.V. (now known as Elastic). Known for its simple REST APIs, distributed nature, speed, and scalability, Elasticsearch is the central component of the Elastic Stack, a set of free and open tools for data ingestion, enrichment, storage, analysis, and visualization.
Why Elasticsearch?
Elasticsearch is fast. Because Elasticsearch is built on top of Lucene, it excels at full-text search. Elasticsearch is also a near real-time search platform, meaning the latency from the time a document is indexed until it becomes searchable is very short — typically one second. As a result, Elasticsearch is well suited for time-sensitive use cases such as security analytics and infrastructure monitoring.
Elasticsearch is distributed by nature. The documents stored in Elasticsearch are distributed across different containers known as shards, which are duplicated to provide redundant copies of the data in case of hardware failure. The distributed nature of Elasticsearch allows it to scale out to hundreds (or even thousands) of servers and handle petabytes of data.
Elasticsearch comes with a wide set of features. In addition to its speed, scalability, and resiliency, Elasticsearch has a number of powerful built-in features that make storing and searching data even more efficient, such as data rollups and index lifecycle management.
The Elastic Stack simplifies data ingest, visualization, and reporting. Integration with Beats and Logstash makes it easy to process data before indexing into Elasticsearch. And Kibana provides real-time visualization of Elasticsearch data as well as UIs for quickly accessing application performance monitoring (APM), logs, and infrastructure metrics data.
Elasticsearch Setup with Docker
For this demo, We’ll use the Docker image from Dockerhub with a single-node Elasticsearch instance running in development mode. Docker images are available from the Elastic Docker registry.
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e "ES_JAVA_OPTS=-Xms512m -Xmx512m" -e "xpack.security.enabled=false" -t docker.elastic.co/elasticsearch/elasticsearch:8.6.0
Getting Started
We will start by creating a simple Spring project from start.spring.io, with the following dependencies: Spring Web, Spring Data Elasticsearch, Lombok, and Validation.
Configuring Elasticsearch in Spring Boot
The main step is to add Elasticsearch connection settings in the application.yml file:
spring:
data:
elasticsearch:
cluster-name: docker-cluster
# Comma-separated cluster node addresses. If not specified, starts a client node.
cluster-nodes: localhost:9200
# Enable Elasticsearch repositories.
repositories:
enabled: true
rest:
uris: http://localhost:9200
Elasticsearch Object Mapping
Spring Data Elasticsearch Object Mapping is the process that maps a Java object — the domain entity — into the JSON representation that is stored in Elasticsearch and back. In Elasticsearch, Document is a collection for the representation of an object in an index.
@Document
: Applied at the class level to indicate this class is a candidate for mapping to the database.@Id
: Applied at the field level to mark the field used for identity purpose.@Field
: Applied at the field level and defines properties of the field.
Elasticsearch Repositories
The Spring Data Elasticsearch project provides two ways to access the Elasticsearch datasource.
ElasticsearchTemplate
helper class that increases productivity performing common ES operations. Includes integrated object mapping between documents and POJOs.- Automatic implementation of
Repository
interfaces including support for custom finder methods.
In this story, we will use Repository interfaces. we are creating a BookRepository interface that implements ElasticsearchRepository.
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
}
Service Layer
The service layer implementation class (BookServiceImpl) will be injected by the BookRepository.
Book Controller
Testing
Now we are all done with our code. We can run our application and test it.
- Create Book
- Get All Book
- Delete book
We can use ElasticHQ which helps to monitor and manage ElasticSearch clusters. It is freely available and distributed under the Apache Software License.
Conclusion
We’ve built a simple Rest API with Spring Boot and Spring Data Elasticsearch.
The complete source code is available on GitHub.
If you enjoyed this article, please give it a few claps 👏.
Thanks for reading!