usage.asciidoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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` or `performRequestAsync` method variants.
  75. The `performRequest` methods are synchronous and they return the `Response`
  76. directly, meaning that the client will block and wait for a response to be returned.
  77. The `performRequestAsync` variants, which return `void` and accept an extra
  78. `ResponseListener` as an argument, are executed asynchronously. The provided
  79. listener will be notified upon completion or failure.
  80. [source,java]
  81. --------------------------------------------------
  82. // Synchronous variants
  83. Response performRequest(String method, String endpoint,
  84. Header... headers)
  85. throws IOException;
  86. Response performRequest(String method, String endpoint,
  87. Map<String, String> params, Header... headers)
  88. throws IOException;
  89. Response performRequest(String method, String endpoint,
  90. Map<String, String> params,
  91. HttpEntity entity,
  92. Header... headers)
  93. throws IOException;
  94. Response performRequest(String method, String endpoint,
  95. Map<String, String> params,
  96. HttpEntity entity,
  97. HttpAsyncResponseConsumer<HttpResponse> responseConsumer,
  98. Header... headers)
  99. throws IOException;
  100. // Asynchronous variants
  101. void performRequestAsync(String method, String endpoint,
  102. ResponseListener responseListener,
  103. Header... headers);
  104. void performRequestAsync(String method, String endpoint,
  105. Map<String, String> params,
  106. ResponseListener responseListener,
  107. Header... headers);
  108. void performRequestAsync(String method, String endpoint,
  109. Map<String, String> params,
  110. HttpEntity entity,
  111. ResponseListener responseListener,
  112. Header... headers);
  113. void performRequestAsync(String method, String endpoint,
  114. Map<String, String> params,
  115. HttpEntity entity,
  116. ResponseListener responseListener,
  117. HttpAsyncResponseConsumer<HttpResponse> responseConsumer,
  118. Header... headers);
  119. --------------------------------------------------
  120. ==== Request Arguments
  121. The following are the arguments accepted by the different methods:
  122. `method`:: the http method or verb
  123. `endpoint`:: the request path, which identifies the Elasticsearch API to
  124. call (e.g. `/_cluster/health`)
  125. `params`:: the optional parameters to be sent as querystring parameters
  126. `entity`:: the optional request body enclosed in an
  127. `org.apache.http.HttpEntity` object
  128. `responseConsumer`:: the optional
  129. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  130. callback. Controls how the response body gets streamed from a non-blocking
  131. HTTP connection on the client side. When not provided, the default
  132. implementation is used which buffers the whole response body in heap memory
  133. `responseListener`:: the listener to be notified upon asynchronous
  134. request success or failure
  135. `headers`:: optional request headers
  136. === Reading responses
  137. The `Response` object, either returned by the synchronous `performRequest` methods or
  138. received as an argument in `ResponseListener#onSuccess(Response)`, wraps the
  139. response object returned by the http client and exposes the following information:
  140. `getRequestLine`:: information about the performed request
  141. `getHost`:: the host that returned the response
  142. `getStatusLine`:: the response status line
  143. `getHeaders`:: the response headers, which can also be retrieved by name
  144. though `getHeader(String)`
  145. `getEntity`:: the response body enclosed in an
  146. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  147. object
  148. When performing a request, an exception is thrown (or received as an argument
  149. in `ResponseListener#onFailure(Exception)` in the following scenarios:
  150. `IOException`:: communication problem (e.g. SocketTimeoutException etc.)
  151. `ResponseException`:: a response was returned, but its status code indicated
  152. an error (not `2xx`). A `ResponseException` originates from a valid
  153. http response, hence it exposes its corresponding `Response` object which gives
  154. access to the returned response.
  155. NOTE: A `ResponseException` is **not** thrown for `HEAD` requests that return
  156. a `404` status code because it is an expected `HEAD` response that simply
  157. denotes that the resource is not found. All other HTTP methods (e.g., `GET`)
  158. throw a `ResponseException` for `404` responses.
  159. === Example requests
  160. Here are a couple of examples:
  161. [source,java]
  162. --------------------------------------------------
  163. Response response = restClient.performRequest("GET", "/",
  164. Collections.singletonMap("pretty", "true"));
  165. System.out.println(EntityUtils.toString(response.getEntity()));
  166. //index a document
  167. HttpEntity entity = new NStringEntity(
  168. "{\n" +
  169. " \"user\" : \"kimchy\",\n" +
  170. " \"post_date\" : \"2009-11-15T14:12:12\",\n" +
  171. " \"message\" : \"trying out Elasticsearch\"\n" +
  172. "}", ContentType.APPLICATION_JSON);
  173. Response indexResponse = restClient.performRequest(
  174. "PUT",
  175. "/twitter/tweet/1",
  176. Collections.<String, String>emptyMap(),
  177. entity);
  178. --------------------------------------------------
  179. Note that the low-level client doesn't expose any helper for json marshalling
  180. and un-marshalling. Users are free to use the library that they prefer for that
  181. purpose.
  182. The underlying Apache Async Http Client ships with different
  183. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  184. implementations that allow to provide the request body in different formats
  185. (stream, byte array, string etc.). As for reading the response body, the
  186. `HttpEntity#getContent` method comes handy which returns an `InputStream`
  187. reading from the previously buffered response body. As an alternative, it is
  188. possible to provide a custom
  189. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  190. that controls how bytes are read and buffered.
  191. The following is a basic example of how async requests can be sent:
  192. [source,java]
  193. --------------------------------------------------
  194. int numRequests = 10;
  195. final CountDownLatch latch = new CountDownLatch(numRequests);
  196. for (int i = 0; i < numRequests; i++) {
  197. restClient.performRequestAsync(
  198. "PUT",
  199. "/twitter/tweet/" + i,
  200. Collections.<String, String>emptyMap(),
  201. //assume that the documents are stored in an entities array
  202. entities[i],
  203. new ResponseListener() {
  204. @Override
  205. public void onSuccess(Response response) {
  206. System.out.println(response);
  207. latch.countDown();
  208. }
  209. @Override
  210. public void onFailure(Exception exception) {
  211. latch.countDown();
  212. }
  213. }
  214. );
  215. }
  216. //wait for all requests to be completed
  217. latch.await();
  218. --------------------------------------------------
  219. === Logging
  220. The Java REST client uses the same logging library that the Apache Async Http
  221. Client uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging],
  222. which comes with support for a number of popular logging implementations. The
  223. java packages to enable logging for are `org.elasticsearch.client` for the
  224. client itself and `org.elasticsearch.client.sniffer` for the sniffer.
  225. The request tracer logging can also be enabled to log every request and
  226. corresponding response in curl format. That comes handy when debugging, for
  227. instance in case a request needs to be manually executed to check whether it
  228. still yields the same response as it did. Enable trace logging for the `tracer`
  229. package to have such log lines printed out. Do note that this type of logging is
  230. expensive and should not be enabled at all times in production environments,
  231. but rather temporarily used only when needed.