Elasticsearch REST Java Client

Abhijeet Kakade
Globant
Published in
4 min readJan 10, 2022

Elasticsearch is a document-based database and search engine based on Lucene library. It also provides lot of features like fuzzy search, aggregation, sorting, hits etc. Elasticsearch is distributed, indices can be divided into shards and each shard can have replicas.

In this blog we will go through below points

  • Options for connecting to Elasticsearch using java
  • Integration with microservices
  • Document API’s
  • synchronous and asynchronous calls

Options for connecting to Elasticsearch using java

1. Transport Client:

Before introduction of Java clients for elastic search Transport Client were used. This uses the REST API over HTTP. In this case user must put extra effort of marshalling the request and unmarshalling the response.

2. Rest Low Level Client:

The RestLowLevelClient internally uses Apache HTTP Async client. It uses minimal number of dependencies. This will also put extra effort on user to marshal and unmarshall the request and response. This will provide below features.

· Load balancing

· Failover

· Persistent connections

· Trace logging request and response

· Minimal dependencies

3. Rest High Level Client:

The RestHighLevelClient is built on top of RestLowLevelClient. This add few of the elastic search dependencies then the low level client. It exposes API specific methods which are responsible for taking the request object and returning the response object. High Level client takes responsibility of marshalling the request and unmarshalling the response which our coding easier. This is default client for elastic search.

Integration with microservices

  1. Maven Dependency

Very first step is to add the maven dependency to pom.xml as mentioned below.

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.14.0</version>
</dependency>

We need to have the java 1.8 and above to support this dependency. Refer here to know about the latest version of elastic search.

2. Initialize the RestHighLevelClient:

RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));

This will create a instance of RestHighLevelClient which will internally create instance of some low level clients. High level client will maintain pool of some low level clients connections. Once the use of high level client is done don’t forget to close it using client.close(). This will free up the low level client connections. Use close method to close the connections.

Documents API’s

  1. Index a document:

We need to create a IndexRequest as below.

Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest indexRequest = new IndexRequest("myIndex")
.id("1").source(jsonMap);

Here ‘myIndex’ is the index name and ‘1’ is the id of the document. We can also pass json string instead of map as below.

String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);

Execute the request as below.

IndexResponse indexResponse = client.index(request,
RequestOptions.DEFAULT);

While executing the request, the program will halt till IndexResponse is not returned from elastic search.

2) Get a document:

Create Get Request as below. Where ‘myIndex’ is the index name and ‘1’ is the document id.

GetRequest getRequest = new GetRequest(  "myIndex",   "1");

To execute the request, use the client.

GetResponse getResponse = client.get(getRequest,  
RequestOptions.DEFAULT);

You can get the document using below methods of GetResponse

- getResponse.getSourceAsString() :- this will return document as String.

- getResponse.getSourceAsMap() :- this will return a map of <String, Object>

- getResponse.getSourceAsBytes() :- this will return a byte array.

3) Delete a document:

DeleteRequest can be constructed as below using ‘myIndex’ as index and ‘1’ as document id.

DeleteRequest request = new DeleteRequest( "myIndex", "1");

Use our HighLevelClient to execute the request.

DeleteResponse deleteResponse = client.delete(request, 
RequestOptions.DEFAULT);

4) Update a document:

The UpdateRequest is built as below.

UpdateRequest request = new UpdateRequest( "myIndex", "1");

Here ‘myIndex’ is index and ‘1’ is id of the document which needs to be updated. Create a Map of updated fields and set it under doc as below.

Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("updated", new Date());
jsonMap.put("reason", "daily update");
UpdateRequest request = new UpdateRequest("myIndex", "1")
.doc(jsonMap);

Execute the request as below.

UpdateResponse updateResponse = client.update(request, 
RequestOptions.DEFAULT);

Synchronous and Asynchronous calls

All the calls for create, update, delete and get mentioned above are asynchronous calls. High level client also provides synchronous call methods for each of them. We just need to write postfix Async word to the synchronous call methods e.g: client.update() is a synchronous methode where as client.updateAsync() is a asynchronous method.

Also we have to add a ActionListener to get the Response. The code snippet to get execute the async call is as below.

ActionListener listener = new ActionListener<UpdateResponse>() {
@Override
public void onResponse(UpdateResponse updateResponse) {

}

@Override
public void onFailure(Exception e) {

}
};
client.updateAsync(request, RequestOptions.DEFAULT, listener);

Here we have to create a listener and pass the reference to updateAsync call. Whenever the call execution is completed the onResponse or onFailure method is triggered.

Conclusion

In this article, we have seen how to use Java client to perform some of the common Elasticsearch features.

--

--