DEV Community

priteshbaviskar
priteshbaviskar

Posted on

Spring Boot(v.2.3.1 and above) + Elasticsearch

If you are like me who have spent endless hours trying to connect ElasticSearch with Spring Boot with no luck yet, this is for you!

There are probably hundreds of tutorials out there but none of them explicitly describe on how to configure a Spring Boot (versions 2.3.1 and above) with Elasticsearch.

Both, Elasticsearch and Spring Boot have been constantly rolling out newer versions, better than the previous ones at the same time making it painstakingly difficult to manage compatibility issues.

Most of the tutorials and examples on Stackoverflow and the Internet are based upon an older version of SB wherein it is necessary to define a RestHighLevelClient

Even the official documentation of Elastic recommends using a RestHighLevelClient with Spring.

All of the above makes sense with a older version of Spring Boot or if you are using a Spring web application with a separate configuration for Spring Data Elastic.

Since v2.3.1, in order to configure Elasticsearch with your SpringBoot application, all you have to do is add the following dependency-

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

Enter fullscreen mode Exit fullscreen mode

That’s it. Spring Boot provides a default ElasticsearchRestTemplate. ElasticsearchRestTemplate is part of release 4 of Spring Data ES which provides out of box support for CRUD operations on ES.

Example to add documents to an index named products —


IndexQuery indexQuery = new IndexQueryBuilder()
        .withId(productDocument.getProductID().toString())
        .withObject(productDocument)
        .build();
return elasticsearchRestTemplate.index(indexQuery, IndexCoordinates.of("products"));
Enter fullscreen mode Exit fullscreen mode

That’s all!

There’s no need of creating another RestHighLevelClient or managing any other version specific dependencies to make this work.

More information on ElasticsearchRestTemplate can be found on the Spring official ES doc here.

Hope this helps!

Oldest comments (0)