usage.asciidoc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. == Getting started
  2. === Maven Repository
  3. The low-level Java REST client is hosted on
  4. http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.elasticsearch.client%22[Maven
  5. Central]. The minimum Java version required is `1.7`.
  6. Here is how you can configure the dependency using maven as a dependency manager.
  7. Add the following to your `pom.xml` file:
  8. ["source","xml",subs="attributes"]
  9. --------------------------------------------------
  10. <dependency>
  11. <groupId>org.elasticsearch.client</groupId>
  12. <artifactId>rest</artifactId>
  13. <version>{version}</version>
  14. </dependency>
  15. --------------------------------------------------
  16. The low-level REST client is subject to the same release cycle as
  17. elasticsearch. Replace `${es.version}` with the desired client version, first
  18. released with `5.0.0-alpha4`. There is no relation between the client version
  19. and the elasticsearch version that the client can communicate with. The
  20. low-level REST client is compatible with all elasticsearch versions.
  21. === Dependencies
  22. The low-level Java REST client internally uses the
  23. http://hc.apache.org/httpcomponents-asyncclient-dev/[Apache Http Async Client]
  24. to send http requests. It depends on the following artifacts, namely the async
  25. http client and its own transitive dependencies:
  26. - org.apache.httpcomponents:httpasyncclient
  27. - org.apache.httpcomponents:httpcore-nio
  28. - org.apache.httpcomponents:httpclient
  29. - org.apache.httpcomponents:httpcore
  30. - commons-codec:commons-codec
  31. - commons-logging:commons-logging
  32. === Initialization
  33. A `RestClient` instance can be built through the corresponding
  34. `RestClientBuilder` class, created via `RestClient#builder(HttpHost...)`
  35. static method. The only required argument is one or more hosts that the
  36. client will communicate with, provided as instances of
  37. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpHost.html[HttpHost]
  38. as follows:
  39. [source,java]
  40. --------------------------------------------------
  41. RestClient restClient = RestClient.builder(
  42. new HttpHost("http", "localhost", 9200),
  43. new HttpHost("http", "localhost", 9201)).build();
  44. --------------------------------------------------
  45. The `RestClient` class is thread-safe and ideally has the same lifecycle as
  46. the application that uses it. It is important that it gets closed when no
  47. longer needed so that all the resources used by it get properly released,
  48. as well as the underlying http client instance and its threads:
  49. [source,java]
  50. --------------------------------------------------
  51. restClient.close();
  52. --------------------------------------------------
  53. `RestClientBuilder` also allows to optionally set the following configuration
  54. parameters while building the `RestClient` instance:
  55. `setDefaultHeaders`:: default headers that need to be sent with each request,
  56. to prevent having to specify them with each single request
  57. `setMaxRetryTimeoutMillis`:: the timeout that should be honoured in case
  58. multiple attempts are made for the same request. The default value is 10
  59. seconds, same as the default socket timeout. In case the socket timeout is
  60. customized, the maximum retry timeout should be adjusted accordingly
  61. `setFailureListener`:: a listener that gets notified every time a node
  62. fails, in case actions need to be taken. Used internally when sniffing on
  63. failure is enabled
  64. `setRequestConfigCallback`:: callback that allows to modify the default
  65. request configuration (e.g. request timeouts, authentication, or anything that
  66. the https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.Builder.html[`org.apache.http.client.config.RequestConfig.Builder`]
  67. allows to set)
  68. `setHttpClientConfigCallback`:: callback that allows to modify the http client
  69. configuration (e.g. encrypted communication over ssl, or anything that the
  70. http://hc.apache.org/httpcomponents-asyncclient-dev/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`]
  71. allows to set)
  72. === Performing requests
  73. Once the `RestClient` has been created, requests can be sent by calling one of
  74. the available `performRequest` method variants. The ones that return the
  75. `Response` are executed synchronously, meaning that the client will block and
  76. wait for a response to be returned. The `performRequest` variants that return
  77. `void` accept a `ResponseListener` as an argument and are executed
  78. asynchronously. The provided listener will be notified upon completion or
  79. failure. The following are the arguments accepted by the different
  80. `performRequest` methods:
  81. `method`:: the http method or verb
  82. `endpoint`:: the request path, which identifies the Elasticsearch api to
  83. call (e.g. `/_cluster/health`)
  84. `params`:: the optional parameters to be sent as querystring parameters
  85. `entity`:: the optional request body enclosed in an
  86. `org.apache.http.HttpEntity` object
  87. `responseConsumer`:: the optional
  88. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  89. callback. Controls how the response body gets streamed from a non-blocking
  90. HTTP connection on the client side. When not provided, the default
  91. implementation is used which buffers the whole response body in heap memory
  92. `responseListener`:: the listener to be notified upon request success or failure
  93. whenever the async `performRequest` method variants are used
  94. `headers`:: optional request headers
  95. === Reading responses
  96. The `Response` object, either returned by the sync `performRequest` methods or
  97. received as an argument in `ResponseListener#onSucces(Response)`, wraps the
  98. response object returned by the http client and exposes the following information:
  99. `getRequestLine`:: information about the performed request
  100. `getHost`:: the host that returned the response
  101. `getStatusLine`:: the response status line
  102. `getHeaders`:: the response headers, which can also be retrieved by name
  103. though `getHeader(String)`
  104. `getEntity`:: the response body enclosed in an
  105. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  106. object
  107. When performing a request, an exception is thrown (or received as an argument
  108. in `ResponseListener#onSucces(Exception)` in the following scenarios:
  109. `IOException`:: communication problem (e.g. SocketTimeoutException etc.)
  110. `ResponseException`:: a response was returned, but its status code indicated
  111. an error (either `4xx` or `5xx`). A `ResponseException` originates from a valid
  112. http response, hence it exposes its corresponding `Response` object which gives
  113. access to the returned response.
  114. === Example requests
  115. Here are a couple of examples:
  116. [source,java]
  117. --------------------------------------------------
  118. Response response = restClient.performRequest("GET", "/",
  119. Collections.singletonMap("pretty", "true"));
  120. System.out.println(EntityUtils.toString(response.getEntity()));
  121. //index a document
  122. HttpEntity entity = new NStringEntity(
  123. "{\n" +
  124. " \"user\" : \"kimchy\",\n" +
  125. " \"post_date\" : \"2009-11-15T14:12:12\",\n" +
  126. " \"message\" : \"trying out Elasticsearch\"\n" +
  127. "}", ContentType.APPLICATION_JSON);
  128. Response indexResponse = restClient.performRequest(
  129. "PUT",
  130. "/twitter/tweet/1",
  131. Collections.<String, String>emptyMap(),
  132. entity);
  133. --------------------------------------------------
  134. Note that the low-level client doesn't expose any helper for json marshalling
  135. and un-marshalling. Users are free to use the library that they prefer for that
  136. purpose.
  137. The underlying Apache Async Http Client ships with different
  138. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  139. implementations that allow to provide the request body in different formats
  140. (stream, byte array, string etc.). As for reading the response body, the
  141. `HttpEntity#getContent` method comes handy which returns an `InputStream`
  142. reading from the previously buffered response body. As an alternative, it is
  143. possible to provide a custom
  144. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  145. that controls how bytes are read and buffered.
  146. The following is a basic example of how async requests can be sent:
  147. [source,java]
  148. --------------------------------------------------
  149. int numRequests = 10;
  150. final CountDownLatch latch = new CountDownLatch(numRequests);
  151. for (int i = 0; i < numRequests; i++) {
  152. restClient.performRequest(
  153. "PUT",
  154. "/twitter/tweet/" + i,
  155. Collections.<String, String>emptyMap(),
  156. //assume that the documents are stored in an entities array
  157. entities[i],
  158. new ResponseListener() {
  159. @Override
  160. public void onSuccess(Response response) {
  161. System.out.println(response);
  162. latch.countDown();
  163. }
  164. @Override
  165. public void onFailure(Exception exception) {
  166. latch.countDown();
  167. }
  168. }
  169. );
  170. }
  171. //wait for all requests to be completed
  172. latch.await();
  173. --------------------------------------------------
  174. === Logging
  175. The Java REST client uses the same logging library that the Apache Async Http
  176. Client uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging],
  177. which comes with support for a number of popular logging implementations. The
  178. java packages to enable logging for are `org.elasticsearch.client` for the
  179. client itself and `org.elasticsearch.client.sniffer` for the sniffer.
  180. The request tracer logging can also be enabled to log every request and
  181. corresponding response in curl format. That comes handy when debugging, for
  182. instance in case a request needs to be manually executed to check whether it
  183. still yields the same response as it did. Enable trace logging for the `tracer`
  184. package to have such log lines printed out. Do note that this type of logging is
  185. expensive and should not be enabled at all times in production environments,
  186. but rather temporarily used only when needed.