migration.asciidoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. [[java-rest-high-level-migration]]
  2. == Migration Guide
  3. This section describes how to migrate existing code from the `TransportClient`
  4. to the new 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. - does not provide indices or cluster management APIs. Management
  81. operations can be executed by external scripts or
  82. <<java-rest-high-level-migration-manage-indices, using the low-level client>>.
  83. ==== How to migrate the way requests are built
  84. The Java API provides two ways to build a request: by using the request's constructor or by using
  85. a request builder. Migrating from the `TransportClient` to the high-level client can be
  86. straightforward if application's code uses the former, while changing usages of the latter can
  87. require more work.
  88. [[java-rest-high-level-migration-request-ctor]]
  89. ===== With request constructors
  90. When request constructors are used, like in the following example:
  91. ["source","java",subs="attributes,callouts,macros"]
  92. --------------------------------------------------
  93. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-ctor]
  94. --------------------------------------------------
  95. <1> Create an `IndexRequest` using its constructor
  96. The migration is very simple. The execution using the `TransportClient`:
  97. [source,java]
  98. --------------------------------------------------
  99. IndexResponse response = transportClient.index(indexRequest).actionGet();
  100. --------------------------------------------------
  101. Can be easily replaced to use the `RestHighLevelClient`:
  102. ["source","java",subs="attributes,callouts,macros"]
  103. --------------------------------------------------
  104. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-ctor-execution]
  105. --------------------------------------------------
  106. [[java-rest-high-level-migration-request-builder]]
  107. ===== With request builders
  108. The Java API provides a request builder for every type of request. They are exposed by the
  109. `TransportClient` through the many `prepare()` methods. Here are some examples:
  110. [source,java]
  111. --------------------------------------------------
  112. IndexRequestBuilder indexRequestBuilder = transportClient.prepareIndex(); // <1>
  113. DeleteRequestBuilder deleteRequestBuilder = transportClient.prepareDelete(); // <2>
  114. SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(); // <3>
  115. --------------------------------------------------
  116. <1> Create a `IndexRequestBuilder` using the `prepareIndex()` method from the `TransportClient`. The
  117. request builder encapsulates the `IndexRequest` to be executed.
  118. <2> Create a `DeleteRequestBuilder` using the `prepareDelete()` method from the `TransportClient`. The
  119. request builder encapsulates the `DeleteRequest` to be executed.
  120. <3> Create a `SearchRequestBuilder` using the `prepareSearch()` method from the `TransportClient`. The
  121. request builder encapsulates the `SearchRequest` to be executed.
  122. Since the Java High Level REST Client does not support request builders, applications that use
  123. them must be changed to use <<java-rest-high-level-migration-request-ctor,requests constructors>> instead.
  124. NOTE: While you are incrementally migrating your application and you have both the transport client
  125. and the high level client available you can always get the `Request` object from the `Builder` object
  126. by calling `Builder.request()`. We do not advise continuing to depend on the builders in the long run
  127. but it should be possible to use them during the transition from the transport client to the high
  128. level rest client.
  129. ==== How to migrate the way requests are executed
  130. The `TransportClient` allows to execute requests in both synchronous and asynchronous ways. This is also
  131. possible using the high-level client.
  132. ===== Synchronous execution
  133. The following example shows how a `DeleteRequest` can be synchronously executed using the `TransportClient`:
  134. [source,java]
  135. --------------------------------------------------
  136. DeleteRequest request = new DeleteRequest("index", "doc", "id"); // <1>
  137. DeleteResponse response = transportClient.delete(request).actionGet(); // <2>
  138. --------------------------------------------------
  139. <1> Create the `DeleteRequest` using its constructor
  140. <2> Execute the `DeleteRequest`. The `actionGet()` method blocks until a
  141. response is returned by the cluster.
  142. The same request synchronously executed using the high-level client is:
  143. ["source","java",subs="attributes,callouts,macros"]
  144. --------------------------------------------------
  145. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-sync-execution]
  146. --------------------------------------------------
  147. <1> Execute the `DeleteRequest`. The `delete()` method blocks until a
  148. response is returned by the cluster.
  149. ===== Asynchronous execution
  150. The following example shows how a `DeleteRequest` can be asynchronously executed using the `TransportClient`:
  151. [source,java]
  152. --------------------------------------------------
  153. DeleteRequest request = new DeleteRequest("index", "doc", "id"); // <1>
  154. transportClient.delete(request, new ActionListener<DeleteResponse>() { // <2>
  155. @Override
  156. public void onResponse(DeleteResponse deleteResponse) {
  157. // <3>
  158. }
  159. @Override
  160. public void onFailure(Exception e) {
  161. // <4>
  162. }
  163. });
  164. --------------------------------------------------
  165. <1> Create the `DeleteRequest` using its constructor
  166. <2> Execute the `DeleteRequest` by passing the request and a
  167. `ActionListener` that gets called on execution completion or
  168. failure. This method does not block and returns immediately.
  169. <3> The `onResponse()` method is called when the response is
  170. returned by the cluster.
  171. <4> The `onFailure()` method is called when an error occurs
  172. during the execution of the request.
  173. The same request asynchronously executed using the high-level client is:
  174. ["source","java",subs="attributes,callouts,macros"]
  175. --------------------------------------------------
  176. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-request-async-execution]
  177. --------------------------------------------------
  178. <1> Create the `DeleteRequest` using its constructor
  179. <2> Execute the `DeleteRequest` by passing the request and a
  180. `ActionListener` that gets called on execution completion or
  181. failure. This method does not block and returns immediately.
  182. <3> The `onResponse()` method is called when the response is
  183. returned by the cluster.
  184. <4> The `onFailure()` method is called when an error occurs
  185. during the execution of the request.
  186. [[java-rest-high-level-migration-manage-indices]]
  187. ==== Manage Indices using the Low-Level REST Client
  188. The low-level client is able to execute any kind of HTTP requests, and can
  189. therefore be used to call the APIs that are not yet supported by the high level client.
  190. For example, creating a new index with the `TransportClient` may look like this:
  191. [source,java]
  192. --------------------------------------------------
  193. Settings settings = Settings.builder() // <1>
  194. .put(SETTING_NUMBER_OF_SHARDS, 1)
  195. .put(SETTING_NUMBER_OF_REPLICAS, 0)
  196. .build();
  197. String mappings = XContentFactory.jsonBuilder() // <2>
  198. .startObject()
  199. .startObject("doc")
  200. .startObject("properties")
  201. .startObject("time")
  202. .field("type", "date")
  203. .endObject()
  204. .endObject()
  205. .endObject()
  206. .endObject()
  207. .string();
  208. CreateIndexResponse response = transportClient.admin().indices() // <3>
  209. .prepareCreate("my-index")
  210. .setSettings(indexSettings)
  211. .addMapping("doc", docMapping, XContentType.JSON)
  212. .get();
  213. if (response.isAcknowledged() == false) {
  214. // <4>
  215. }
  216. --------------------------------------------------
  217. <1> Define the settings of the index
  218. <2> Define the mapping for document of type `doc` using a
  219. `XContentBuilder`
  220. <3> Create the index with the previous settings and mapping
  221. using the `prepareCreate()` method. The execution is synchronous
  222. and blocks on the `get()` method until the remote cluster returns
  223. a response.
  224. <4> Handle the situation where the index has not been created
  225. The same operation executed with the low-level client could be:
  226. ["source","java",subs="attributes,callouts,macros"]
  227. --------------------------------------------------
  228. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-create-index]
  229. --------------------------------------------------
  230. <1> Define the settings of the index
  231. <2> Define the body of the HTTP request using a `XContentBuilder` with JSON format
  232. <3> Include the settings in the request body
  233. <4> Include the mappings in the request body
  234. <5> Convert the request body from `String` to a `HttpEntity` and
  235. set its content type (here, JSON)
  236. <6> Execute the request using the low-level client. The execution is synchronous
  237. and blocks on the `performRequest()` method until the remote cluster returns
  238. a response. The low-level client can be retrieved from an existing `RestHighLevelClient`
  239. instance through the `getLowLevelClient` getter method.
  240. <7> Handle the situation where the index has not been created
  241. [[java-rest-high-level-migration-cluster-health]]
  242. ==== Checking Cluster Health using the Low-Level REST Client
  243. Another common need is to check the cluster's health using the Cluster API. With
  244. the `TransportClient` it can be done this way:
  245. [source,java]
  246. --------------------------------------------------
  247. ClusterHealthResponse response = client.admin().cluster().prepareHealth().get(); // <1>
  248. ClusterHealthStatus healthStatus = response.getStatus(); // <2>
  249. if (healthStatus != ClusterHealthStatus.GREEN) {
  250. // <3>
  251. }
  252. --------------------------------------------------
  253. <1> Execute a `ClusterHealth` with default parameters
  254. <2> Retrieve the cluster's health status from the response
  255. <3> Handle the situation where the cluster's health is not green
  256. With the low-level client, the code can be changed to:
  257. ["source","java",subs="attributes,callouts,macros"]
  258. --------------------------------------------------
  259. include-tagged::{doc-tests}/MigrationDocumentationIT.java[migration-cluster-health]
  260. --------------------------------------------------
  261. <1> Call the cluster's health REST endpoint and wait for the cluster health to become green,
  262. then get back a `Response` object.
  263. <2> Retrieve an `InputStream` object in order to read the response's content
  264. <3> Parse the response's content using Elasticsearch's helper class `XContentHelper`. This
  265. helper requires the content type of the response to be passed as an argument and returns
  266. a `Map` of objects. Values in the map can be of any type, including inner `Map` that are
  267. used to represent the JSON object hierarchy.
  268. <4> Retrieve the value of the `status` field in the response map, casts it as a a `String`
  269. object and use the `ClusterHealthStatus.fromString()` method to convert it as a `ClusterHealthStatus`
  270. object. This method throws an exception if the value does not corresponds to a valid cluster
  271. health status.
  272. <5> Handle the situation where the cluster's health is not green
  273. Note that for convenience this example uses Elasticsearch's helpers to parse the JSON response
  274. body, but any other JSON parser could have been use instead.
  275. === Provide feedback
  276. We love to hear from you! Please give us your feedback about your migration
  277. experience and how to improve the Java High Level Rest Client on https://discuss.elastic.co/[our forum].