preloader

A Quick Guide to Elasticsearch Java clients [Part 2]

In the previous blog post, we’ve seen how to setup a local Elasticsearch server and how to use Jest Java client, in this part we’ll see how to use Spring data elasticsearch.

A Quick Guide to Elasticsearch Java clients [Part 2]

Spring data elasticsearch

For Spring users there is Elasticsearch library under the spring data project (Official documentation).

To use spring data elasticsearch add the following dependency into pom.xml for Maven projects:

<dependencies>

    <dependency>

        <groupId>org.springframework.data</groupId>

        <artifactId>spring-data-elasticsearch</artifactId>

        <version>3.0.5.RELEASE</version>

    </dependency>

</dependencies>

<repositories>

    <repository&gt

        <id>spring-libs-release</id>

        <name>Spring Releases</name>

        <url>https://repo.spring.io/libs-release</url>

        <snapshots>

            <enabled>false</enabled>

        </snapshots>

    </repository>

</repositories>

Or for Gradle projects in your build.gradle:

dependencies {

    compile ‘org.springframework.data:spring-data-elasticsearch:3.0.5.RELEASE’

} repositories {

    maven {

        url ‘https://repo.spring.io/libs-release’

    }

}

Spring data elasticsearch provides an easy way of configuration using Java-based configuration class annotated with @Configuration.

ElasticsearchTemplate similar to JdbcTemplate, or RestTemplate, is the helper class that exposes common Elasticsearch functionality like indexing, querying, scan and scroll for pagination, with POJO to document mapping included.

A really strong feature of spring data elasticsearch is the ability to express mapping metadata using annotations like @Document, @Id, @Filed on indexing entity, and interacting with Elasticsearch server using Spring Repository interface proxies, which is familiar territory for Spring users. These interfaces can be extended with custom methods. When following a naming convention, search query type can be parsed and determined automatically, for e.g. if we imagine:

interface ElasticSearchCommentsRepository extends Repository<Comment, Long> {

       List<Comment> findByMessageAndUser(String message, String user);

}

method findByMessageAndUser is going to be automatically parsed and will generate appropriate search query:

{ “bool” :

    { “must” :

        [

            { “field” : {“message” : “?”} },

            { “field” : {“user” : “?”} }

        ]

    }

}

Find more info on query method parsing in this section of the documentation.

If this is not enough in terms of custom queries, we could annotate methods with @Query and provide a string query, similar to what we’ve seen earlier. Another option is to just implement an interface with concrete implementation for methods, which can provide more flexibility and might be more easily maintainable than a bunch of string queries.

There is also the NativeSearchQueryBuilder class, which enables plugging in Elasticsearch query builders, if we have them on the classpath, enabling more control and fine-tuning of the search queries. For e.g. if we would like to search for comments of a specific user, we could do something like this:

SearchQuery searchQuery = new NativeSearchQueryBuilder()

.withQuery(matchQuery(“user”, “user1”))

.build();

List<Comment> comments = elasticSearchTemplate.queryForList(searchQuery, Comment.class);

If the result set is too big, it is a good idea to get results paginated. This is done by retrieving Elasticsearch scrolls, which are identified by scroll id. For the example on how to do this, take a look at following part of the documentation and also at Elastic scrolls.

Summary

Spring data elasticsearch is a good option for Spring-based projects. It provides ease of configuration, automatic POJO to document mapping, and a familiar way of querying elasticsearch through either repository proxies or template helper class. Interface proxies enable automatic query generation, which removes the need for query builders and manual building of queries in most cases (but that option is left on the table if need be). One thing to keep in mind though when considering migration to a newer version of Elasticsearch server has spring data release train kept up. In case of incompatible versions, migrating to newer versions of the Elasticsearch server might be challenging.

In the next blog post, we are going to go over some features of the official Elasticsearch Java client, with the focus on Java High-Level REST Client.

Related Blog Posts:

Links and references:

About the author:

Dragan Torbica is a Software Engineer with 7 years of experience mostly in Java and Spring. He believes that software is not something that can be manufactured nor can it be delivered faster by merely adding more lines of code and that writing good software requires skill and careful attention. Currently, he’s working for BrightMarbles.io as Senior Software Developer and Technical Team Lead.