Smit Shah's Blog


Smit Shah's Blog


Spring Boot Integrate with Elasticsearch

Smit Shah's photo
Smit Shah
·Feb 2, 2023·

2 min read

In this article, we will explore how to set up the elastic search as a DB, in a few simple steps.

You can go and set up a default application via

Once you have set up your project, you can add the following dependencies to your pom.xml file:


Create a configuration class to set up the Elasticsearch client:

public class ElasticsearchConfig {

    private String esHost;

    private int esPort;

    private String esClusterName;

    public RestHighLevelClient client() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, esPort, "http"))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);

In the application properties file, add the following settings to configure the Elasticsearch host and cluster name:

Lets create a book document:

@Document(indexName = "books", type = "book")
public class Book {
    private String id;
    private String name;
    private String author;
    private String genre;

    // getters and setters

Create a repository interface that extends ElasticsearchRepository:

public interface BookRepository extends ElasticsearchRepository<Book, String> {

Lets now create a BookService:

public class BookService {

    private final BookRepository bookRepository;

    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;

    public List<Book> findByName(String name) {
        return bookRepository.findByName(name);

    public Book save(Book book) {

    public void deleteById(String id) {

Lets integrate all the components together:

public class BookController {
    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;

    public Book create(@RequestBody Book book) {

Now we can test the insert operation by sending a POST request to the /api/books endpoint with the book data in the request body.

For example, we can use a tool like cURL to send the request:

curl -X POST \
  http://localhost:8080/api/books \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "The Great Gatsby",
    "author": "F. Scott Fitzgerald",
    "genre": "Novel"

That's all! Its that simple to integrate elasticsearch into any spring boot applications.

Feel free to share your thoughts and feedback on comments or Twitter at @smit_shah_95

Share this