usage.asciidoc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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-shading]]
  53. === Shading
  54. In order to avoid version conflicts, the dependencies can be shaded and packaged
  55. within the client in a single JAR file (sometimes called an "uber JAR" or "fat
  56. JAR"). Shading a dependency consists of taking its content (resources files and
  57. Java class files) and renaming some of its packages before putting them in the
  58. same JAR file as the low-level Java REST client. Shading a JAR can be
  59. accomplished by 3rd-party plugins for Gradle and Maven.
  60. Be advised that shading a JAR also has implications. Shading the Commons Logging
  61. layer, for instance, means that 3rd-party logging backends need to be shaded as
  62. well.
  63. [[java-rest-low-usage-shading-maven]]
  64. ==== Maven configuration
  65. Here is a configuration using the Maven
  66. https://maven.apache.org/plugins/maven-shade-plugin/index.html[Shade]
  67. plugin. Add the following to your `pom.xml` file:
  68. ["source","xml",subs="attributes"]
  69. --------------------------------------------------
  70. <build>
  71. <plugins>
  72. <plugin>
  73. <groupId>org.apache.maven.plugins</groupId>
  74. <artifactId>maven-shade-plugin</artifactId>
  75. <version>3.1.0</version>
  76. <executions>
  77. <execution>
  78. <phase>package</phase>
  79. <goals><goal>shade</goal></goals>
  80. <configuration>
  81. <relocations>
  82. <relocation>
  83. <pattern>org.apache.http</pattern>
  84. <shadedPattern>hidden.org.apache.http</shadedPattern>
  85. </relocation>
  86. <relocation>
  87. <pattern>org.apache.logging</pattern>
  88. <shadedPattern>hidden.org.apache.logging</shadedPattern>
  89. </relocation>
  90. <relocation>
  91. <pattern>org.apache.commons.codec</pattern>
  92. <shadedPattern>hidden.org.apache.commons.codec</shadedPattern>
  93. </relocation>
  94. <relocation>
  95. <pattern>org.apache.commons.logging</pattern>
  96. <shadedPattern>hidden.org.apache.commons.logging</shadedPattern>
  97. </relocation>
  98. </relocations>
  99. </configuration>
  100. </execution>
  101. </executions>
  102. </plugin>
  103. </plugins>
  104. </build>
  105. --------------------------------------------------
  106. [[java-rest-low-usage-shading-gradle]]
  107. ==== Gradle configuration
  108. Here is a configuration using the Gradle
  109. https://github.com/johnrengelman/shadow[ShadowJar] plugin. Add the following to
  110. your `build.gradle` file:
  111. ["source","groovy",subs="attributes"]
  112. --------------------------------------------------
  113. shadowJar {
  114. relocate 'org.apache.http', 'hidden.org.apache.http'
  115. relocate 'org.apache.logging', 'hidden.org.apache.logging'
  116. relocate 'org.apache.commons.codec', 'hidden.org.apache.commons.codec'
  117. relocate 'org.apache.commons.logging', 'hidden.org.apache.commons.logging'
  118. }
  119. --------------------------------------------------
  120. [[java-rest-low-usage-initialization]]
  121. === Initialization
  122. A `RestClient` instance can be built through the corresponding
  123. `RestClientBuilder` class, created via `RestClient#builder(HttpHost...)`
  124. static method. The only required argument is one or more hosts that the
  125. client will communicate with, provided as instances of
  126. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpHost.html[HttpHost]
  127. as follows:
  128. ["source","java",subs="attributes,callouts,macros"]
  129. --------------------------------------------------
  130. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init]
  131. --------------------------------------------------
  132. The `RestClient` class is thread-safe and ideally has the same lifecycle as
  133. the application that uses it. It is important that it gets closed when no
  134. longer needed so that all the resources used by it get properly released,
  135. as well as the underlying http client instance and its threads:
  136. ["source","java",subs="attributes,callouts,macros"]
  137. --------------------------------------------------
  138. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-close]
  139. --------------------------------------------------
  140. `RestClientBuilder` also allows to optionally set the following configuration
  141. parameters while building the `RestClient` instance:
  142. ["source","java",subs="attributes,callouts,macros"]
  143. --------------------------------------------------
  144. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-default-headers]
  145. --------------------------------------------------
  146. <1> Set the default headers that need to be sent with each request, to
  147. prevent having to specify them with each single request
  148. ["source","java",subs="attributes,callouts,macros"]
  149. --------------------------------------------------
  150. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-max-retry-timeout]
  151. --------------------------------------------------
  152. <1> Set the timeout that should be honoured in case multiple attempts are made
  153. for the same request. The default value is 30 seconds, same as the default
  154. socket timeout. In case the socket timeout is customized, the maximum retry
  155. timeout should be adjusted accordingly
  156. ["source","java",subs="attributes,callouts,macros"]
  157. --------------------------------------------------
  158. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-failure-listener]
  159. --------------------------------------------------
  160. <1> Set a listener that gets notified every time a node fails, in case actions
  161. need to be taken. Used internally when sniffing on failure is enabled.
  162. ["source","java",subs="attributes,callouts,macros"]
  163. --------------------------------------------------
  164. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-request-config-callback]
  165. --------------------------------------------------
  166. <1> Set a callback that allows to modify the default request configuration
  167. (e.g. request timeouts, authentication, or anything that the
  168. https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.Builder.html[`org.apache.http.client.config.RequestConfig.Builder`]
  169. allows to set)
  170. ["source","java",subs="attributes,callouts,macros"]
  171. --------------------------------------------------
  172. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-client-config-callback]
  173. --------------------------------------------------
  174. <1> Set a callback that allows to modify the http client configuration
  175. (e.g. encrypted communication over ssl, or anything that the
  176. http://hc.apache.org/httpcomponents-asyncclient-dev/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`]
  177. allows to set)
  178. [[java-rest-low-usage-requests]]
  179. === Performing requests
  180. Once the `RestClient` has been created, requests can be sent by calling one of
  181. the available `performRequest` or `performRequestAsync` method variants.
  182. The `performRequest` methods are synchronous and return the `Response` directly,
  183. meaning that the client will block and wait for a response to be returned.
  184. The `performRequestAsync` variants return `void` and accept an extra
  185. `ResponseListener` as an argument instead, meaning that they are executed
  186. asynchronously. The provided listener will be notified upon request completion
  187. or failure.
  188. ["source","java",subs="attributes,callouts,macros"]
  189. --------------------------------------------------
  190. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint]
  191. --------------------------------------------------
  192. <1> Send a request by providing only the verb and the endpoint, minimum set
  193. of required arguments
  194. ["source","java",subs="attributes,callouts,macros"]
  195. --------------------------------------------------
  196. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint-params]
  197. --------------------------------------------------
  198. <1> Send a request by providing the verb, the endpoint, and some querystring
  199. parameter
  200. ["source","java",subs="attributes,callouts,macros"]
  201. --------------------------------------------------
  202. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint-params-body]
  203. --------------------------------------------------
  204. <1> Send a request by providing the verb, the endpoint, optional querystring
  205. parameters and the request body enclosed in an `org.apache.http.HttpEntity`
  206. object
  207. IMPORTANT: The `ContentType` specified 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. ["source","java",subs="attributes,callouts,macros"]
  211. --------------------------------------------------
  212. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response-consumer]
  213. --------------------------------------------------
  214. <1> Send a request by providing the verb, the endpoint, optional querystring
  215. parameters, optional request body and the optional factory that is used to
  216. 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`]
  217. callback instance per request attempt. Controls how the response body gets
  218. streamed from a non-blocking HTTP connection on the client side. When not
  219. provided, the default implementation is used which buffers the whole response
  220. body in heap memory, up to 100 MB.
  221. ["source","java",subs="attributes,callouts,macros"]
  222. --------------------------------------------------
  223. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint-async]
  224. --------------------------------------------------
  225. <1> Define what needs to happen when the request is successfully performed
  226. <2> Define what needs to happen when the request fails, meaning whenever
  227. there's a connection error or a response with error status code is returned.
  228. <3> Send an async request by providing only the verb, the endpoint, and the
  229. response listener to be notified once the request is completed, minimum set
  230. of required arguments
  231. ["source","java",subs="attributes,callouts,macros"]
  232. --------------------------------------------------
  233. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint-params-async]
  234. --------------------------------------------------
  235. <1> Send an async request by providing the verb, the endpoint, some querystring
  236. parameter and the response listener to be notified once the request is completed
  237. ["source","java",subs="attributes,callouts,macros"]
  238. --------------------------------------------------
  239. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-verb-endpoint-params-body-async]
  240. --------------------------------------------------
  241. <1> Send an async request by providing the verb, the endpoint, optional
  242. querystring parameters, the request body enclosed in an
  243. `org.apache.http.HttpEntity` object and the response listener to be
  244. notified once the request is completed
  245. ["source","java",subs="attributes,callouts,macros"]
  246. --------------------------------------------------
  247. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response-consumer-async]
  248. --------------------------------------------------
  249. <1> Send an async request by providing the verb, the endpoint, optional
  250. querystring parameters, optional request body and the optional factory that is
  251. 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`]
  252. callback instance per request attempt. Controls how the response body gets
  253. streamed from a non-blocking HTTP connection on the client side. When not
  254. provided, the default implementation is used which buffers the whole response
  255. body in heap memory, up to 100 MB.
  256. The following is a basic example of how async requests can be sent:
  257. ["source","java",subs="attributes,callouts,macros"]
  258. --------------------------------------------------
  259. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async-example]
  260. --------------------------------------------------
  261. <1> Process the returned response
  262. <2> Handle the returned exception, due to communication error or a response
  263. with status code that indicates an error
  264. Each of the above listed method supports sending headers along with the
  265. request through a `Header` varargs argument as in the following examples:
  266. ["source","java",subs="attributes,callouts,macros"]
  267. --------------------------------------------------
  268. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-headers]
  269. --------------------------------------------------
  270. ["source","java",subs="attributes,callouts,macros"]
  271. --------------------------------------------------
  272. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-headers-async]
  273. --------------------------------------------------
  274. [[java-rest-low-usage-responses]]
  275. === Reading responses
  276. The `Response` object, either returned by the synchronous `performRequest` methods or
  277. received as an argument in `ResponseListener#onSuccess(Response)`, wraps the
  278. response object returned by the http client and exposes some additional information.
  279. ["source","java",subs="attributes,callouts,macros"]
  280. --------------------------------------------------
  281. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response2]
  282. --------------------------------------------------
  283. <1> Information about the performed request
  284. <2> The host that returned the response
  285. <3> The response status line, from which you can for instance retrieve the status code
  286. <4> The response headers, which can also be retrieved by name though `getHeader(String)`
  287. <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`]
  288. object
  289. When performing a request, an exception is thrown (or received as an argument
  290. in `ResponseListener#onFailure(Exception)` in the following scenarios:
  291. `IOException`:: communication problem (e.g. SocketTimeoutException)
  292. `ResponseException`:: a response was returned, but its status code indicated
  293. an error (not `2xx`). A `ResponseException` originates from a valid
  294. http response, hence it exposes its corresponding `Response` object which gives
  295. access to the returned response.
  296. NOTE: A `ResponseException` is **not** thrown for `HEAD` requests that return
  297. a `404` status code because it is an expected `HEAD` response that simply
  298. denotes that the resource is not found. All other HTTP methods (e.g., `GET`)
  299. throw a `ResponseException` for `404` responses unless the `ignore` parameter
  300. contains `404`. `ignore` is a special client parameter that doesn't get sent
  301. to Elasticsearch and contains a comma separated list of error status codes.
  302. It allows to control whether some error status code should be treated as an
  303. expected response rather than as an exception. This is useful for instance
  304. with the get api as it can return `404` when the document is missing, in which
  305. case the response body will not contain an error but rather the usual get api
  306. response, just without the document as it was not found.
  307. Note that the low-level client doesn't expose any helper for json marshalling
  308. and un-marshalling. Users are free to use the library that they prefer for that
  309. purpose.
  310. The underlying Apache Async Http Client ships with different
  311. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  312. implementations that allow to provide the request body in different formats
  313. (stream, byte array, string etc.). As for reading the response body, the
  314. `HttpEntity#getContent` method comes handy which returns an `InputStream`
  315. reading from the previously buffered response body. As an alternative, it is
  316. possible to provide a custom
  317. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  318. that controls how bytes are read and buffered.
  319. [[java-rest-low-usage-logging]]
  320. === Logging
  321. The Java REST client uses the same logging library that the Apache Async Http
  322. Client uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging],
  323. which comes with support for a number of popular logging implementations. The
  324. java packages to enable logging for are `org.elasticsearch.client` for the
  325. client itself and `org.elasticsearch.client.sniffer` for the sniffer.
  326. The request tracer logging can also be enabled to log every request and
  327. corresponding response in curl format. That comes handy when debugging, for
  328. instance in case a request needs to be manually executed to check whether it
  329. still yields the same response as it did. Enable trace logging for the `tracer`
  330. package to have such log lines printed out. Do note that this type of logging is
  331. expensive and should not be enabled at all times in production environments,
  332. but rather temporarily used only when needed.