usage.asciidoc 16 KB

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