migration.asciidoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. [[java-rest-high-level-migration]]
  2. == Migration Guide
  3. This section describes how to migrate existing code from the `TransportClient`
  4. to the Java High Level REST Client released with the version 5.6.0
  5. of Elasticsearch.
  6. === Motivations around a new Java client
  7. The existing `TransportClient` has been part of Elasticsearch since https://github.com/elastic/elasticsearch/blob/b3337c312765e51cec7bde5883bbc0a08f56fb65/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClient.java[its very first commit].
  8. It is a special client as it uses the transport protocol to communicate with Elasticsearch,
  9. which causes compatibility problems if the client is not on the same version as the
  10. Elasticsearch instances it talks to.
  11. We released a low-level REST client in 2016, which is based on the well known Apache HTTP
  12. client and it allows to communicate with an Elasticsearch cluster in any version using HTTP.
  13. On top of that we released the high-level REST client which is based on the low-level client
  14. but takes care of request marshalling and response un-marshalling.
  15. If you're interested in knowing more about these changes, we wrote a blog post about the
  16. https://www.elastic.co/blog/state-of-the-official-elasticsearch-java-clients[state of the official Elasticsearch Java clients].
  17. === Prerequisite
  18. The Java High Level Rest Client requires Java `1.8` and can be used to send requests
  19. to an <<java-rest-high-compatibility,Elasticsearch cluster in a compatible version>>.
  20. === How to migrate
  21. Adapting existing code to use the `RestHighLevelClient` instead of the `TransportClient`
  22. requires the following steps:
  23. - Update dependencies
  24. - Update client initialization
  25. - Update application code
  26. === Updating the dependencies
  27. Java application that uses the `TransportClient` depends on the
  28. `org.elasticsearch.client:transport` artifact. This dependency
  29. must be replaced by a new dependency on the high-level client.
  30. The <<java-rest-high-getting-started,Getting Started>> page shows
  31. typical configurations for Maven and Gradle and presents the
  32. <<java-rest-high-getting-started-dependencies, dependencies>> brought by the
  33. high-level client.
  34. === Changing the client's initialization code
  35. The `TransportClient` is typically initialized as follows:
  36. [source,java]
  37. --------------------------------------------------
  38. Settings settings = Settings.builder()
  39. .put("cluster.name", "prod").build();
  40. TransportClient transportClient = new PreBuiltTransportClient(settings)
  41. .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
  42. .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9301));
  43. --------------------------------------------------
  44. The initialization of a `RestHighLevelClient` is different. It requires to provide
  45. a <<java-rest-low-usage-initialization,low-level client builder>> as a constructor
  46. argument:
  47. ["source","java",subs="attributes,callouts,macros"]
  48. --------------------------------------------------
  49. include-tagged::{doc-tests}/MiscellaneousDocumentationIT.java[rest-high-level-client-init]
  50. --------------------------------------------------
  51. NOTE: The `RestClient` uses Elasticsearch's HTTP service which is
  52. bounded by default on `9200`. This port is different from the port
  53. used to connect to Elasticsearch with a `TransportClient`.
  54. The `RestHighLevelClient` is thread-safe. It is typically instantiated by the
  55. application at startup time or when the first request is executed.
  56. Once the `RestHighLevelClient` is initialized, it can be used to execute any
  57. of the <<java-rest-high-supported-apis,supported APIs>>.
  58. As with the `TransportClient`, the `RestHighLevelClient` must be closed when it
  59. is not needed anymore or when the application is stopped.
  60. The code that closes the `TransportClient`:
  61. [source,java]
  62. --------------------------------------------------
  63. transportClient.close();
  64. --------------------------------------------------
  65. must be replaced with:
  66. ["source","java",subs="attributes,callouts,macros"]
  67. --------------------------------------------------
  68. include-tagged::{doc-tests}/MiscellaneousDocumentationIT.java[rest-high-level-client-close]
  69. --------------------------------------------------
  70. === Changing the application's code
  71. The `RestHighLevelClient` supports the same request and response objects
  72. as the `TransportClient`, but exposes slightly different methods to
  73. send the requests.
  74. More importantly, the high-level client:
  75. - does not support request builders. The legacy methods like
  76. `client.prepareIndex()` must be changed to use
  77. request constructors like `new IndexRequest()` to create requests
  78. objects. The requests are then executed using synchronous or
  79. asynchronous dedicated methods like `client.index()` or `client.indexAsync()`.
  80. ==== How to migrate the way requests are built
  81. The Java API provides two ways to build a request: by using the request's constructor or by using
  82. a request builder. Migrating from the `TransportClient` to the high-level client can be
  83. straightforward if application's code uses the former, while changing usages of the latter can
  84. require more work.
  85. [[java-rest-high-level-migration-request-ctor]]
  86. ===== With request constructors
  87. When request constructors are used, like in the following example:
  88. ["source","java",subs="attributes,callouts,macros"]
  89. --------------------------------------------------
  90. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-ctor]
  91. --------------------------------------------------
  92. <1> Create an `IndexRequest` using its constructor
  93. The migration is very simple. The execution using the `TransportClient`:
  94. [source,java]
  95. --------------------------------------------------
  96. IndexResponse response = transportClient.index(indexRequest).actionGet();
  97. --------------------------------------------------
  98. Can be easily replaced to use the `RestHighLevelClient`:
  99. ["source","java",subs="attributes,callouts,macros"]
  100. --------------------------------------------------
  101. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-ctor-execution]
  102. --------------------------------------------------
  103. [[java-rest-high-level-migration-request-builder]]
  104. ===== With request builders
  105. The Java API provides a request builder for every type of request. They are exposed by the
  106. `TransportClient` through the many `prepare()` methods. Here are some examples:
  107. [source,java]
  108. --------------------------------------------------
  109. IndexRequestBuilder indexRequestBuilder = transportClient.prepareIndex(); // <1>
  110. DeleteRequestBuilder deleteRequestBuilder = transportClient.prepareDelete(); // <2>
  111. SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(); // <3>
  112. --------------------------------------------------
  113. <1> Create a `IndexRequestBuilder` using the `prepareIndex()` method from the `TransportClient`. The
  114. request builder encapsulates the `IndexRequest` to be executed.
  115. <2> Create a `DeleteRequestBuilder` using the `prepareDelete()` method from the `TransportClient`. The
  116. request builder encapsulates the `DeleteRequest` to be executed.
  117. <3> Create a `SearchRequestBuilder` using the `prepareSearch()` method from the `TransportClient`. The
  118. request builder encapsulates the `SearchRequest` to be executed.
  119. Since the Java High Level REST Client does not support request builders, applications that use
  120. them must be changed to use <<java-rest-high-level-migration-request-ctor,requests constructors>> instead.
  121. NOTE: While you are incrementally migrating your application and you have both the transport client
  122. and the high level client available you can always get the `Request` object from the `Builder` object
  123. by calling `Builder.request()`. We do not advise continuing to depend on the builders in the long run
  124. but it should be possible to use them during the transition from the transport client to the high
  125. level rest client.
  126. ==== How to migrate the way requests are executed
  127. The `TransportClient` allows to execute requests in both synchronous and asynchronous ways. This is also
  128. possible using the high-level client.
  129. ===== Synchronous execution
  130. The following example shows how a `DeleteRequest` can be synchronously executed using the `TransportClient`:
  131. [source,java]
  132. --------------------------------------------------
  133. DeleteRequest request = new DeleteRequest("index", "doc", "id"); // <1>
  134. DeleteResponse response = transportClient.delete(request).actionGet(); // <2>
  135. --------------------------------------------------
  136. <1> Create the `DeleteRequest` using its constructor
  137. <2> Execute the `DeleteRequest`. The `actionGet()` method blocks until a
  138. response is returned by the cluster.
  139. The same request synchronously executed using the high-level client is:
  140. ["source","java",subs="attributes,callouts,macros"]
  141. --------------------------------------------------
  142. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-sync-execution]
  143. --------------------------------------------------
  144. <1> Execute the `DeleteRequest`. The `delete()` method blocks until a
  145. response is returned by the cluster.
  146. ===== Asynchronous execution
  147. The following example shows how a `DeleteRequest` can be asynchronously executed using the `TransportClient`:
  148. [source,java]
  149. --------------------------------------------------
  150. DeleteRequest request = new DeleteRequest("index", "doc", "id"); // <1>
  151. transportClient.delete(request, new ActionListener<DeleteResponse>() { // <2>
  152. @Override
  153. public void onResponse(DeleteResponse deleteResponse) {
  154. // <3>
  155. }
  156. @Override
  157. public void onFailure(Exception e) {
  158. // <4>
  159. }
  160. });
  161. --------------------------------------------------
  162. <1> Create the `DeleteRequest` using its constructor
  163. <2> Execute the `DeleteRequest` by passing the request and a
  164. `ActionListener` that gets called on execution completion or
  165. failure. This method does not block and returns immediately.
  166. <3> The `onResponse()` method is called when the response is
  167. returned by the cluster.
  168. <4> The `onFailure()` method is called when an error occurs
  169. during the execution of the request.
  170. The same request asynchronously executed using the high-level client is:
  171. ["source","java",subs="attributes,callouts,macros"]
  172. --------------------------------------------------
  173. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-async-execution]
  174. --------------------------------------------------
  175. <1> Create the `DeleteRequest` using its constructor
  176. <2> Execute the `DeleteRequest` by passing the request and a
  177. `ActionListener` that gets called on execution completion or
  178. failure. This method does not block and returns immediately.
  179. <3> The `onResponse()` method is called when the response is
  180. returned by the cluster.
  181. <4> The `onFailure()` method is called when an error occurs
  182. during the execution of the request.
  183. [[java-rest-high-level-migration-cluster-health]]
  184. ==== Checking Cluster Health using the Low-Level REST Client
  185. Another common need is to check the cluster's health using the Cluster API. With
  186. the `TransportClient` it can be done this way:
  187. [source,java]
  188. --------------------------------------------------
  189. ClusterHealthResponse response = client.admin().cluster().prepareHealth().get(); // <1>
  190. ClusterHealthStatus healthStatus = response.getStatus(); // <2>
  191. if (healthStatus != ClusterHealthStatus.GREEN) {
  192. // <3>
  193. }
  194. --------------------------------------------------
  195. <1> Execute a `ClusterHealth` with default parameters
  196. <2> Retrieve the cluster's health status from the response
  197. <3> Handle the situation where the cluster's health is not green
  198. With the low-level client, the code can be changed to:
  199. ["source","java",subs="attributes,callouts,macros"]
  200. --------------------------------------------------
  201. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-cluster-health]
  202. --------------------------------------------------
  203. <1> Set up the request to wait for the cluster's health to become green if it isn't already.
  204. <2> Make the request and the get back a `Response` object.
  205. <3> Retrieve an `InputStream` object in order to read the response's content
  206. <4> Parse the response's content using Elasticsearch's helper class `XContentHelper`. This
  207. helper requires the content type of the response to be passed as an argument and returns
  208. a `Map` of objects. Values in the map can be of any type, including inner `Map` that are
  209. used to represent the JSON object hierarchy.
  210. <5> Retrieve the value of the `status` field in the response map, casts it as a `String`
  211. object and use the `ClusterHealthStatus.fromString()` method to convert it as a `ClusterHealthStatus`
  212. object. This method throws an exception if the value does not corresponds to a valid cluster
  213. health status.
  214. <6> Handle the situation where the cluster's health is not green
  215. Note that for convenience this example uses Elasticsearch's helpers to parse the JSON response
  216. body, but any other JSON parser could have been use instead.
  217. === Provide feedback
  218. We love to hear from you! Please give us your feedback about your migration
  219. experience and how to improve the Java High Level Rest Client on https://discuss.elastic.co/[our forum].