usage.asciidoc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 either
  183. `performRequest` or `performRequestAsync`. `performRequest` is synchronous and
  184. will block the calling thread and return the `Response` when the request is
  185. successful or throw an exception if it fails. `performRequestAsync` is
  186. asynchronous and accepts a `ResponseListener` argument that it calls with a
  187. `Response` when the request is successful or with an `Exception` if it4 fails.
  188. This is synchronous:
  189. ["source","java",subs="attributes,callouts,macros"]
  190. --------------------------------------------------
  191. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-sync]
  192. --------------------------------------------------
  193. <1> The HTTP method (`GET`, `POST`, `HEAD`, etc)
  194. <2> The endpoint on the server
  195. And this is asynchronous:
  196. ["source","java",subs="attributes,callouts,macros"]
  197. --------------------------------------------------
  198. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async]
  199. --------------------------------------------------
  200. <1> The HTTP method (`GET`, `POST`, `HEAD`, etc)
  201. <2> The endpoint on the server
  202. <3> Handle the response
  203. <4> Handle the failure
  204. You can add request parameters to the request object:
  205. ["source","java",subs="attributes,callouts,macros"]
  206. --------------------------------------------------
  207. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-parameters]
  208. --------------------------------------------------
  209. You can set the body of the request to any `HttpEntity`:
  210. ["source","java",subs="attributes,callouts,macros"]
  211. --------------------------------------------------
  212. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-body]
  213. --------------------------------------------------
  214. IMPORTANT: The `ContentType` specified for the `HttpEntity` is important
  215. because it will be used to set the `Content-Type` header so that Elasticsearch
  216. can properly parse the content.
  217. You can also set it to a `String` which will default to
  218. a `ContentType` of `application/json`.
  219. ["source","java",subs="attributes,callouts,macros"]
  220. --------------------------------------------------
  221. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-body-shorter]
  222. --------------------------------------------------
  223. And you can set a list of headers to send with the request:
  224. ["source","java",subs="attributes,callouts,macros"]
  225. --------------------------------------------------
  226. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-headers]
  227. --------------------------------------------------
  228. You can also customize the response consumer used to buffer the asynchronous
  229. responses. The default consumer will buffer up to 100MB of response on the
  230. JVM heap. If the response is larger then the request will fail. You could,
  231. for example, lower the maximum size which might be useful if you are running
  232. in a heap constrained environment:
  233. ["source","java",subs="attributes,callouts,macros"]
  234. --------------------------------------------------
  235. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response-consumer]
  236. --------------------------------------------------
  237. ==== Multiple parallel asynchronous actions
  238. The client is quite happy to execute many actions in parallel. The following
  239. example indexes many documents in parallel. In a real world scenario you'd
  240. probably want to use the `_bulk` API instead, but the example is illustative.
  241. ["source","java",subs="attributes,callouts,macros"]
  242. --------------------------------------------------
  243. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async-example]
  244. --------------------------------------------------
  245. <1> Process the returned response
  246. <2> Handle the returned exception, due to communication error or a response
  247. with status code that indicates an error
  248. [[java-rest-low-usage-responses]]
  249. === Reading responses
  250. The `Response` object, either returned by the synchronous `performRequest` methods or
  251. received as an argument in `ResponseListener#onSuccess(Response)`, wraps the
  252. response object returned by the http client and exposes some additional information.
  253. ["source","java",subs="attributes,callouts,macros"]
  254. --------------------------------------------------
  255. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response2]
  256. --------------------------------------------------
  257. <1> Information about the performed request
  258. <2> The host that returned the response
  259. <3> The response status line, from which you can for instance retrieve the status code
  260. <4> The response headers, which can also be retrieved by name though `getHeader(String)`
  261. <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`]
  262. object
  263. When performing a request, an exception is thrown (or received as an argument
  264. in `ResponseListener#onFailure(Exception)` in the following scenarios:
  265. `IOException`:: communication problem (e.g. SocketTimeoutException)
  266. `ResponseException`:: a response was returned, but its status code indicated
  267. an error (not `2xx`). A `ResponseException` originates from a valid
  268. http response, hence it exposes its corresponding `Response` object which gives
  269. access to the returned response.
  270. NOTE: A `ResponseException` is **not** thrown for `HEAD` requests that return
  271. a `404` status code because it is an expected `HEAD` response that simply
  272. denotes that the resource is not found. All other HTTP methods (e.g., `GET`)
  273. throw a `ResponseException` for `404` responses unless the `ignore` parameter
  274. contains `404`. `ignore` is a special client parameter that doesn't get sent
  275. to Elasticsearch and contains a comma separated list of error status codes.
  276. It allows to control whether some error status code should be treated as an
  277. expected response rather than as an exception. This is useful for instance
  278. with the get api as it can return `404` when the document is missing, in which
  279. case the response body will not contain an error but rather the usual get api
  280. response, just without the document as it was not found.
  281. Note that the low-level client doesn't expose any helper for json marshalling
  282. and un-marshalling. Users are free to use the library that they prefer for that
  283. purpose.
  284. The underlying Apache Async Http Client ships with different
  285. https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  286. implementations that allow to provide the request body in different formats
  287. (stream, byte array, string etc.). As for reading the response body, the
  288. `HttpEntity#getContent` method comes handy which returns an `InputStream`
  289. reading from the previously buffered response body. As an alternative, it is
  290. possible to provide a custom
  291. http://hc.apache.org/httpcomponents-core-ga/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  292. that controls how bytes are read and buffered.
  293. [[java-rest-low-usage-logging]]
  294. === Logging
  295. The Java REST client uses the same logging library that the Apache Async Http
  296. Client uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging],
  297. which comes with support for a number of popular logging implementations. The
  298. java packages to enable logging for are `org.elasticsearch.client` for the
  299. client itself and `org.elasticsearch.client.sniffer` for the sniffer.
  300. The request tracer logging can also be enabled to log every request and
  301. corresponding response in curl format. That comes handy when debugging, for
  302. instance in case a request needs to be manually executed to check whether it
  303. still yields the same response as it did. Enable trace logging for the `tracer`
  304. package to have such log lines printed out. Do note that this type of logging is
  305. expensive and should not be enabled at all times in production environments,
  306. but rather temporarily used only when needed.