usage.asciidoc 19 KB

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