usage.asciidoc 14 KB

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