usage.asciidoc 16 KB

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