With Elasticsearch 5.x, the Elasticsearch team has provided a custom low-level HTTP client to communicate with Elasticsearch. Its main features are as follows:
You need an up-and-running Elasticsearch installation as we described in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.
A Maven tool, or an IDE that natively supports it for Java programming such as Eclipse or IntelliJ IDEA, must be installed.
The code for this recipe is in the chapter_14/http_es_client
directory.
For creating RestClient
, we will perform the following steps:
search.maven.org
. To enable compilation in your Maven pom.xml
project just add the following code:<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>rest</artifactId> <version>5.0.0</version> </dependency>
get
method, the code will look like the following:package com.packtpub; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import java.io.IOException; public class App { public static void main(String[] args) { RestClient client = RestClient.builder( new HttpHost("localhost", 9200, "http")).build(); try { Response response = client.performRequest("GET", "/test-index/test-type/1"); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println("Method failed: " + response.getStatusLine()); } else { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); } } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } }
{"_index":"test-index","_type":"test- type","_id":"1","_version":1,"exists":true, "_source" : {...}}
Internally the Elasticseach RestClient
uses Apache HttpComponents and wraps it with more convenient methods.
We perform the previous steps to create and use a RestClient
:
RestClient
object.RestClient client = RestClient.builder( new HttpHost("localhost", 9200, "http")).build();
builder
method accepts a multi-value HttpHost
(in this way you can pass a list of HTTP addresses) and returns RestClientBuilder
under the hood.RestClientBuilder
allows client communication to be customized by several methods such as:setDefaultHeaders(Header[] defaultHeaders)
: This allows the custom headers that must be sent for every request to be provided.setMaxRetryTimeoutMillis(int maxRetryTimeoutMillis)
: This allows the max retry timeout to be defined if there are multiple attempts for the same request.setPathPrefix(String pathPrefix)
: This allows a custom path prefix to be defined for every request.setFailureListener(FailureListener failureListener)
: This allows a custom failure listener to be provided, which is called in an instance of node failure. This can be used to provide user defined behavior in the case of node failure.setHttpClientConfigCallback(RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback)
: This allows modification to the HTTP client communication, such as adding compression or an encryption layer.setRequestConfigCallback(RestClientBuilder.RequestConfigCallback requestConfigCallback)
: This allows the configuration of request authentications, timeout, and other properties that can be set a request level.RestClient
, we can execute some requests against it via the several performRequest
for synchronous calls and performRequestAsync
methods for asynchronous ones.String method
: This is theHTTP method or verb to be used in the call (required)String endpoint
: This is the API endpoint (required). In the previous example, it is /test-index/test-type/1
Map<String, String> params
: This is a map of values to be passed as query parametersHttpEntity entity
: This is the body of the request. It's a org/apache/http/HttpEntity
(http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html?is-external=true)HttpAsyncResponseConsumer<HttpResponse> responseConsumer
: This is used to manage responses in an asynchronous request (http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html). By default, it's used to keep all the responses in heap memory (the top memory limit is 100Mb)ResponseListener responseListener
: This is used to register callbacks during asynchronous callsHeader... headers
: They are additional headers passed during the callResponse response = client.performRequest("GET", "/test- index/test-type/1");
org.elasticsearch.client.Response
that wraps the Apache HttpComponents response one: for this reason, the code to manage the response is the same as the previous recipe.3.141.19.185