| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299 | == Getting started=== Maven RepositoryThe low-level Java REST client is hosted onhttp://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.elasticsearch.client%22[MavenCentral]. The minimum Java version required is `1.7`.The low-level REST client is subject to the same release cycle aselasticsearch. Replace the version with the desired client version, firstreleased with `5.0.0-alpha4`. There  is no relation between the client versionand the elasticsearch version that the client can communicate with. Thelow-level REST client is compatible with all elasticsearch versions.==== Maven configurationHere is how you can configure the dependency using maven as a dependency manager.Add the following to your `pom.xml` file:["source","xml",subs="attributes"]--------------------------------------------------<dependency>    <groupId>org.elasticsearch.client</groupId>    <artifactId>rest</artifactId>    <version>{version}</version></dependency>--------------------------------------------------==== Gradle configurationHere is how you can configure the dependency using gradle as a dependency manager.Add the following to your `build.gradle` file:["source","groovy",subs="attributes"]--------------------------------------------------dependencies {    compile 'org.elasticsearch.client:rest:{version}'}--------------------------------------------------=== DependenciesThe low-level Java REST client internally uses thehttp://hc.apache.org/httpcomponents-asyncclient-dev/[Apache Http Async Client] to send http requests. It depends on the following artifacts, namely the async http client and its own transitive dependencies:- org.apache.httpcomponents:httpasyncclient- org.apache.httpcomponents:httpcore-nio- org.apache.httpcomponents:httpclient- org.apache.httpcomponents:httpcore- commons-codec:commons-codec- commons-logging:commons-logging=== InitializationA `RestClient` instance can be built through the corresponding`RestClientBuilder` class, created via `RestClient#builder(HttpHost...)`static method. The only required argument is one or more hosts that theclient will communicate with, provided as instances ofhttps://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpHost.html[HttpHost] as follows:[source,java]--------------------------------------------------RestClient restClient = RestClient.builder(        new HttpHost("localhost", 9200, "http"),        new HttpHost("localhost", 9201, "http")).build();--------------------------------------------------The `RestClient` class is thread-safe and ideally has the same lifecycle asthe application that uses it. It is important that it gets closed when nolonger needed so that all the resources used by it get properly released,as well as the underlying http client instance and its threads:[source,java]--------------------------------------------------restClient.close();--------------------------------------------------`RestClientBuilder` also allows to optionally set the following configurationparameters while building the `RestClient` instance:`setDefaultHeaders`:: default headers that need to be sent with each request,to prevent having to specify them with each single request`setMaxRetryTimeoutMillis`:: the timeout that should be honoured in casemultiple attempts are made for the same request. The default value is 10seconds, same as the default socket timeout. In case the socket timeout iscustomized, the maximum retry timeout should be adjusted accordingly`setFailureListener`:: a listener that gets notified every time a nodefails,  in case actions need to be taken. Used internally when sniffing onfailure is enabled`setRequestConfigCallback`:: callback that allows to modify the defaultrequest configuration (e.g. request timeouts, authentication, or anything thatthe https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.Builder.html[`org.apache.http.client.config.RequestConfig.Builder`] allows to set)`setHttpClientConfigCallback`:: callback that allows to modify the http client configuration (e.g. encrypted communication over ssl, or anything that thehttp://hc.apache.org/httpcomponents-asyncclient-dev/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`] allows to set)=== Performing requestsOnce the `RestClient` has been created, requests can be sent by calling one ofthe available `performRequest` or `performRequestAsync` method variants.The `performRequest` methods are synchronous and they return the `Response`directly, meaning that the client will block and wait for a response to be returned.The `performRequestAsync` variants, which return `void` and accept an extra`ResponseListener` as an argument, are executed asynchronously. The providedlistener will be notified upon completion or failure.[source,java]--------------------------------------------------// Synchronous variantsResponse performRequest(String method, String endpoint,                        Header... headers)    throws IOException;Response performRequest(String method, String endpoint,                        Map<String, String> params, Header... headers)    throws IOException;Response performRequest(String method, String endpoint,                        Map<String, String> params,                        HttpEntity entity,                        Header... headers)    throws IOException;Response performRequest(String method, String endpoint,                        Map<String, String> params,                        HttpEntity entity,                        HttpAsyncResponseConsumerFactory responseConsumerFactory,                        Header... headers)    throws IOException;// Asynchronous variantsvoid performRequestAsync(String method, String endpoint,                         ResponseListener responseListener,                         Header... headers);void performRequestAsync(String method, String endpoint,                         Map<String, String> params,                         ResponseListener responseListener,                         Header... headers);void performRequestAsync(String method, String endpoint,                         Map<String, String> params,                         HttpEntity entity,                         ResponseListener responseListener,                         Header... headers);void performRequestAsync(String method, String endpoint,                         Map<String, String> params,                         HttpEntity entity,                         HttpAsyncResponseConsumerFactory responseConsumerFactory,                         ResponseListener responseListener,                         Header... headers);--------------------------------------------------==== Request ArgumentsThe following are the arguments accepted by the different methods:`method`:: the http method or verb`endpoint`:: the request path, which identifies the Elasticsearch API tocall (e.g. `/_cluster/health`)`params`:: the optional parameters to be sent as querystring parameters`entity`:: the optional request body enclosed in an`org.apache.http.HttpEntity` object`responseConsumerFactory`:: the optional factory that is used to create anhttp://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`] callback instance per request attempt. Controls how the response body gets streamed from a non-blocking HTTP connection on the client side. When not provided, the default implementation is used which buffers the whole response body in heap memory, up to 100 MB`responseListener`:: the listener to be notified upon asynchronousrequest success or failure`headers`:: optional request headers=== Reading responsesThe `Response` object, either returned by the synchronous `performRequest` methods orreceived as an argument in `ResponseListener#onSuccess(Response)`, wraps theresponse object returned by the http client and exposes the following information:`getRequestLine`:: information about the performed request`getHost`:: the host that returned the response`getStatusLine`:: the response status line`getHeaders`:: the response headers, which can also be retrieved by namethough `getHeader(String)``getEntity`:: the response body enclosed in anhttps://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`] objectWhen performing a request, an exception is thrown (or received as an argument in `ResponseListener#onFailure(Exception)` in the following scenarios:`IOException`:: communication problem (e.g. SocketTimeoutException etc.)`ResponseException`:: a response was returned, but its status code indicatedan error (not `2xx`). A `ResponseException` originates from a validhttp response, hence it exposes its corresponding `Response` object which givesaccess to the returned response.NOTE: A `ResponseException` is **not** thrown for `HEAD` requests that returna `404` status code because it is an expected `HEAD` response that simplydenotes that the resource is not found. All other HTTP methods (e.g., `GET`)throw a `ResponseException` for `404` responses.=== Example requestsHere are a couple of examples:[source,java]--------------------------------------------------Response response = restClient.performRequest("GET", "/",        Collections.singletonMap("pretty", "true"));System.out.println(EntityUtils.toString(response.getEntity()));//index a documentHttpEntity entity = new NStringEntity(        "{\n" +        "    \"user\" : \"kimchy\",\n" +        "    \"post_date\" : \"2009-11-15T14:12:12\",\n" +        "    \"message\" : \"trying out Elasticsearch\"\n" +        "}", ContentType.APPLICATION_JSON);Response indexResponse = restClient.performRequest(        "PUT",        "/twitter/tweet/1",        Collections.<String, String>emptyMap(),        entity);--------------------------------------------------Note that the low-level client doesn't expose any helper for json marshallingand un-marshalling. Users are free to use the library that they prefer for thatpurpose.The underlying Apache Async Http Client ships with differenthttps://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`] implementations that allow to provide the request body in different formats(stream, byte array, string etc.). As for reading the response body, the`HttpEntity#getContent` method comes handy which returns an `InputStream`reading from the previously buffered response body. As an alternative, it ispossible to provide a customhttp://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`] that controls how bytes are read and buffered.The following is a basic example of how async requests can be sent:[source,java]--------------------------------------------------int numRequests = 10;final CountDownLatch latch = new CountDownLatch(numRequests);for (int i = 0; i < numRequests; i++) {    restClient.performRequestAsync(        "PUT",        "/twitter/tweet/" + i,        Collections.<String, String>emptyMap(),        //assume that the documents are stored in an entities array        entities[i],        new ResponseListener() {            @Override            public void onSuccess(Response response) {                System.out.println(response);                latch.countDown();            }            @Override            public void onFailure(Exception exception) {                latch.countDown();            }        }    );}//wait for all requests to be completedlatch.await();--------------------------------------------------=== LoggingThe Java REST client uses the same logging library that the Apache Async HttpClient uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging], which comes with support for a number of popular logging implementations. Thejava packages to enable logging for are `org.elasticsearch.client` for theclient itself and `org.elasticsearch.client.sniffer` for the sniffer.The request tracer logging can also be enabled to log every request andcorresponding response in curl format. That comes handy when debugging, forinstance in case a request needs to be manually executed to check whether itstill yields the same response as it did. Enable trace logging for the `tracer`package to have such log lines printed out. Do note that this type of logging isexpensive and should not be enabled at all times in production environments,but rather temporarily used only when needed.
 |