usage.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.elasticsearch.client%22[Maven
  12. Central]. The minimum Java version required is `1.8`.
  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. https://hc.apache.org/httpcomponents-asyncclient-4.1.x/[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-4.4.x/current/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-failure-listener]
  153. --------------------------------------------------
  154. <1> Set a listener that gets notified every time a node fails, in case actions
  155. need to be taken. Used internally when sniffing on failure is enabled.
  156. ["source","java",subs="attributes,callouts,macros"]
  157. --------------------------------------------------
  158. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-node-selector]
  159. --------------------------------------------------
  160. <1> Set the node selector to be used to filter the nodes the client will send
  161. requests to among the ones that are set to the client itself. This is useful
  162. for instance to prevent sending requests to dedicated master nodes when
  163. sniffing is enabled. By default the client sends requests to every configured
  164. node.
  165. ["source","java",subs="attributes,callouts,macros"]
  166. --------------------------------------------------
  167. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-request-config-callback]
  168. --------------------------------------------------
  169. <1> Set a callback that allows to modify the default request configuration
  170. (e.g. request timeouts, authentication, or anything that the
  171. https://hc.apache.org/httpcomponents-client-4.5.x/current/httpclient/apidocs/org/apache/http/client/config/RequestConfig.Builder.html[`org.apache.http.client.config.RequestConfig.Builder`]
  172. allows to set)
  173. ["source","java",subs="attributes,callouts,macros"]
  174. --------------------------------------------------
  175. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-client-config-callback]
  176. --------------------------------------------------
  177. <1> Set a callback that allows to modify the http client configuration
  178. (e.g. encrypted communication over ssl, or anything that the
  179. https://hc.apache.org/httpcomponents-asyncclient-4.1.x/current/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`]
  180. allows to set)
  181. [[java-rest-low-usage-requests]]
  182. === Performing requests
  183. Once the `RestClient` has been created, requests can be sent by calling either
  184. `performRequest` or `performRequestAsync`. `performRequest` is synchronous and
  185. will block the calling thread and return the `Response` when the request is
  186. successful or throw an exception if it fails. `performRequestAsync` is
  187. asynchronous and accepts a `ResponseListener` argument that it calls with a
  188. `Response` when the request is successful or with an `Exception` if it fails.
  189. This is synchronous:
  190. ["source","java",subs="attributes,callouts,macros"]
  191. --------------------------------------------------
  192. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-sync]
  193. --------------------------------------------------
  194. <1> The HTTP method (`GET`, `POST`, `HEAD`, etc)
  195. <2> The endpoint on the server
  196. And this is asynchronous:
  197. ["source","java",subs="attributes,callouts,macros"]
  198. --------------------------------------------------
  199. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async]
  200. --------------------------------------------------
  201. <1> The HTTP method (`GET`, `POST`, `HEAD`, etc)
  202. <2> The endpoint on the server
  203. <3> Handle the response
  204. <4> Handle the failure
  205. You can add request parameters to the request object:
  206. ["source","java",subs="attributes,callouts,macros"]
  207. --------------------------------------------------
  208. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-parameters]
  209. --------------------------------------------------
  210. You can set the body of the request to any `HttpEntity`:
  211. ["source","java",subs="attributes,callouts,macros"]
  212. --------------------------------------------------
  213. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-body]
  214. --------------------------------------------------
  215. IMPORTANT: The `ContentType` specified for the `HttpEntity` is important
  216. because it will be used to set the `Content-Type` header so that Elasticsearch
  217. can properly parse the content.
  218. You can also set it to a `String` which will default to
  219. a `ContentType` of `application/json`.
  220. ["source","java",subs="attributes,callouts,macros"]
  221. --------------------------------------------------
  222. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-body-shorter]
  223. --------------------------------------------------
  224. [[java-rest-low-usage-request-options]]
  225. ==== RequestOptions
  226. The `RequestOptions` class holds parts of the request that should be shared
  227. between many requests in the same application. You can make a singleton
  228. instance and share it between all requests:
  229. ["source","java",subs="attributes,callouts,macros"]
  230. --------------------------------------------------
  231. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-options-singleton]
  232. --------------------------------------------------
  233. <1> Add any headers needed by all requests.
  234. <2> Customize the response consumer.
  235. `addHeader` is for headers that are required for authorization or to work with
  236. a proxy in front of Elasticsearch. There is no need to set the `Content-Type`
  237. header because the client will automatically set that from the `HttpEntity`
  238. attached to the request.
  239. You can set the `NodeSelector` which controls which nodes will receive
  240. requests. `NodeSelector.SKIP_DEDICATED_MASTERS` is a good choice.
  241. You can also customize the response consumer used to buffer the asynchronous
  242. responses. The default consumer will buffer up to 100MB of response on the
  243. JVM heap. If the response is larger then the request will fail. You could,
  244. for example, lower the maximum size which might be useful if you are running
  245. in a heap constrained environment like the example above.
  246. Once you've created the singleton you can use it when making requests:
  247. ["source","java",subs="attributes,callouts,macros"]
  248. --------------------------------------------------
  249. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-options-set-singleton]
  250. --------------------------------------------------
  251. You can also customize these options on a per request basis. For example, this
  252. adds an extra header:
  253. ["source","java",subs="attributes,callouts,macros"]
  254. --------------------------------------------------
  255. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-options-customize-header]
  256. --------------------------------------------------
  257. ==== Multiple parallel asynchronous actions
  258. The client is quite happy to execute many actions in parallel. The following
  259. example indexes many documents in parallel. In a real world scenario you'd
  260. probably want to use the `_bulk` API instead, but the example is illustrative.
  261. ["source","java",subs="attributes,callouts,macros"]
  262. --------------------------------------------------
  263. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async-example]
  264. --------------------------------------------------
  265. <1> Process the returned response
  266. <2> Handle the returned exception, due to communication error or a response
  267. with status code that indicates an error
  268. ==== Cancelling asynchronous requests
  269. The `performRequestAsync` method returns a `Cancellable` that exposes a single
  270. public method called `cancel`. Such method can be called to cancel the on-going
  271. request. Cancelling a request will result in aborting the http request through
  272. the underlying http client. On the server side, this does not automatically
  273. translate to the execution of that request being cancelled, which needs to be
  274. specifically implemented in the API itself.
  275. The use of the `Cancellable` instance is optional and you can safely ignore this
  276. if you don't need it. A typical usecase for this would be using this together with
  277. frameworks like Rx Java or the Kotlin's `suspendCancellableCoRoutine`. Cancelling
  278. no longer needed requests is a good way to avoid putting unnecessary
  279. load on Elasticsearch.
  280. ["source","java",subs="attributes,callouts,macros"]
  281. --------------------------------------------------
  282. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-async-cancel]
  283. --------------------------------------------------
  284. <1> Process the returned response, in case it was ready before the request got cancelled
  285. <2> Handle the returned exception, which will most likely be a `CancellationException` as the request got cancelled
  286. [[java-rest-low-usage-responses]]
  287. === Reading responses
  288. The `Response` object, either returned by the synchronous `performRequest` methods or
  289. received as an argument in `ResponseListener#onSuccess(Response)`, wraps the
  290. response object returned by the http client and exposes some additional information.
  291. ["source","java",subs="attributes,callouts,macros"]
  292. --------------------------------------------------
  293. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-response2]
  294. --------------------------------------------------
  295. <1> Information about the performed request
  296. <2> The host that returned the response
  297. <3> The response status line, from which you can for instance retrieve the status code
  298. <4> The response headers, which can also be retrieved by name though `getHeader(String)`
  299. <5> The response body enclosed in an https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  300. object
  301. When performing a request, an exception is thrown (or received as an argument
  302. in `ResponseListener#onFailure(Exception)` in the following scenarios:
  303. `IOException`:: communication problem (e.g. SocketTimeoutException)
  304. `ResponseException`:: a response was returned, but its status code indicated
  305. an error (not `2xx`). A `ResponseException` originates from a valid
  306. http response, hence it exposes its corresponding `Response` object which gives
  307. access to the returned response.
  308. NOTE: A `ResponseException` is **not** thrown for `HEAD` requests that return
  309. a `404` status code because it is an expected `HEAD` response that simply
  310. denotes that the resource is not found. All other HTTP methods (e.g., `GET`)
  311. throw a `ResponseException` for `404` responses unless the `ignore` parameter
  312. contains `404`. `ignore` is a special client parameter that doesn't get sent
  313. to Elasticsearch and contains a comma separated list of error status codes.
  314. It allows to control whether some error status code should be treated as an
  315. expected response rather than as an exception. This is useful for instance
  316. with the get api as it can return `404` when the document is missing, in which
  317. case the response body will not contain an error but rather the usual get api
  318. response, just without the document as it was not found.
  319. Note that the low-level client doesn't expose any helper for json marshalling
  320. and un-marshalling. Users are free to use the library that they prefer for that
  321. purpose.
  322. The underlying Apache Async Http Client ships with different
  323. https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html[`org.apache.http.HttpEntity`]
  324. implementations that allow to provide the request body in different formats
  325. (stream, byte array, string etc.). As for reading the response body, the
  326. `HttpEntity#getContent` method comes handy which returns an `InputStream`
  327. reading from the previously buffered response body. As an alternative, it is
  328. possible to provide a custom
  329. https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore-nio/apidocs/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.html[`org.apache.http.nio.protocol.HttpAsyncResponseConsumer`]
  330. that controls how bytes are read and buffered.
  331. [[java-rest-low-usage-logging]]
  332. === Logging
  333. The Java REST client uses the same logging library that the Apache Async Http
  334. Client uses: https://commons.apache.org/proper/commons-logging/[Apache Commons Logging],
  335. which comes with support for a number of popular logging implementations. The
  336. java packages to enable logging for are `org.elasticsearch.client` for the
  337. client itself and `org.elasticsearch.client.sniffer` for the sniffer.
  338. The request tracer logging can also be enabled to log every request and
  339. corresponding response in curl format. That comes handy when debugging, for
  340. instance in case a request needs to be manually executed to check whether it
  341. still yields the same response as it did. Enable trace logging for the `tracer`
  342. package to have such log lines printed out. Do note that this type of logging is
  343. expensive and should not be enabled at all times in production environments,
  344. but rather temporarily used only when needed.
  345. ==== Logback
  346. ===== Trace Logs
  347. In order to enable trace logs for logback, we have to use https://www.slf4j.org/legacy.html#jclOverSLF4J[jcl-over-slf4j bridging module].
  348. 1. Add the following to your Gradle setting:
  349. [source,groovy]
  350. dependencies {
  351. implementation('org.slf4j:slf4j-api:1.8.0-beta2')
  352. implementation('ch.qos.logback:logback-classic:1.3.0-alpha4')
  353. implementation('org.slf4j:jcl-over-slf4j:1.8.0-beta2')
  354. }
  355. 2. Exclude `commons-logging.jar`:
  356. [source,groovy]
  357. dependencies {
  358. configurations.all {
  359. exclude group: "commons-logging", module: "commons-logging"
  360. }
  361. }
  362. 3. Add a tracer logger in Logback configuration:
  363. [source,xml]
  364. <logger name="tracer" level="TRACE" additivity="false">
  365. <appender-ref ref="your_appender_block_name" />
  366. </logger>
  367. ===== RestClient Debug Logs
  368. To enable debug logs for `RestClient` class, add the following to your Logback configuration:
  369. [source,xml]
  370. <logger name="org.elasticsearch.client.RestClient" level="DEBUG" additivity="false">
  371. <appender-ref ref="your_appender_block_name" />
  372. </logger>