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