Elasticsearch Java API Examples and Unit Testing

In this article, we briefly see some examples about basic functionalities of Elasticsearch using its native Java API. Then, we try to create an embedded node for Unit Testing. This embedded Elastic node comes with a minimal configuration and all the necessary cleanup functions for test executions.

Maven dependencies

This is the Maven dependency for Elasticsearch.

Basic Functions

Indexing a Tweet

As mentioned above, our example is about an application like Twitter. Our entity is a Tweet object and we want to index each Tweet in our Elasticsearch cluster (i.e. there is a Elasticsearch cluster or a node running somewhere. More information can be found here.). A Tweet entity basically is somehow as follows:

This how we index a tweet:

As we discussed in our previous articles, index is like a schema in relational databases and type is like a table.  The value of INDEX_NAME is “twitter” and the value of TYPE is “tweet”.

Fetching a Tweet

Searching For Tweets

Unit Testing

We need to create a clean embedded Elasticsearch node for test executions and drop it when tests are done. After execution of each test, the data should be removed. In addition, there will be some files and leftovers after execution of tests from Elasticsearch. Those leftovers should be cleaned up.

Embedded Elasticsearch

Clean-up Functions

We should remove the local directory of the Elasticsearch as well as all the indices and the caches. These are done by adding several function to the Embedded Elasticsearch class as follows:

The cleanup function should be executed @After execution of each Test. This will ensure that you have a clean Elastic server for each test. A more comprehensive example can be found here.

Minimal Elastic Server Configuration

This is a minimal Elastic search configuration with the least disk IO interaction (i.e. it tries to keep Elastic data as much as possible in memory.) This helps to have faster test execution with minimal IO operations. You need to put this file into the resources folder of your test suite. Then, it gets detected automatically. I found this configuration file in the middle of Elastic sub-projects in Elastic company.


Facebooktwitterredditpinterestlinkedinmailby feather

One thought on “Elasticsearch Java API Examples and Unit Testing

  1. Thanks for your post 🙂

    I am trying to use an embedded elasticsearch server for some testing. It comes up fine (it seems), but then when I try to create an index I get

    IllegalIndexShardStateException[CurrentState[RECOVERING] operations only allowed when shard state is one of [POST_RECOVERY, STARTED, RELOCATED]];

    I have tried sleeping and have tried waiting for a green health status, but even after five minutes, my server is still recovering.

    Thoughts? Any ideas?


Leave a Reply

Your email address will not be published. Required fields are marked *