- Java REST Client (deprecated): other versions:
- Overview
- Java Low Level REST Client
- Java High Level REST Client
- Getting started
- Document APIs
- Search APIs
- Async Search APIs
- Miscellaneous APIs
- Index APIs
- Analyze API
- Create Index API
- Delete Index API
- Index Exists API
- Open Index API
- Close Index API
- Shrink Index API
- Split Index API
- Clone Index API
- Refresh API
- Flush API
- Flush Synced API
- Clear Cache API
- Force Merge API
- Rollover Index API
- Update mapping API
- Get Mappings API
- Get Field Mappings API
- Index Aliases API
- Delete Alias API
- Exists Alias API
- Get Alias API
- Update Indices Settings API
- Get Settings API
- Create or update index template API
- Validate Query API
- Get Templates API
- Templates Exist API
- Get Index API
- Freeze Index API
- Unfreeze Index API
- Delete Template API
- Reload Search Analyzers API
- Get Composable Index Templates API
- Create or update composable index template API
- Delete Composable Index Template API
- Optional arguments
- Simulate Index Template API
- Cluster APIs
- Ingest APIs
- Snapshot APIs
- Tasks APIs
- Script APIs
- Licensing APIs
- Machine Learning APIs
- Close anomaly detection jobs API
- Delete anomaly detection jobs API
- Delete anomaly detection jobs from calendar API
- Delete calendar events API
- Delete calendars API
- Delete data frame analytics jobs API
- Delete datafeeds API
- Delete expired data API
- Delete filters API
- Delete forecasts API
- Delete model snapshots API
- Delete trained models API
- Delete trained model alias API
- Estimate anomaly detection job model memory API
- Evaluate data frame analytics API
- Explain data frame analytics API
- Flush jobs API
- Forecast jobs API
- Get anomaly detection jobs API
- Get anomaly detection job stats API
- Get buckets API
- Get calendar events API
- Get calendars API
- Get categories API
- Get data frame analytics jobs API
- Get data frame analytics jobs stats API
- Get datafeeds API
- Get datafeed stats API
- Get filters API
- Get influencers API
- Get machine learning info API
- Get model snapshots API
- Get overall buckets API
- Get records API
- Get trained models API
- Get trained models stats API
- Open anomaly detection jobs API
- Post calendar events API
- Post data API
- Preview datafeeds API
- Create anomaly detection jobs API
- Add anomaly detection jobs to calendar API
- Create calendars API
- Create data frame analytics jobs API
- Create datafeeds API
- Create filters API
- Create trained models API
- Create or update trained model alias API
- Reset anomaly detection jobs API
- Revert model snapshots API
- Set upgrade mode API
- Start data frame analytics jobs API
- Start datafeeds API
- Stop data frame analytics jobs API
- Stop datafeeds API
- Update anomaly detection jobs API
- Update data frame analytics jobs API
- Update datafeeds API
- Update filters API
- Update model snapshots API
- Upgrade job snapshot API
- Migration APIs
- Rollup APIs
- Security APIs
- Create or update user API
- Get Users API
- Delete User API
- Enable User API
- Disable User API
- Change Password API
- Create or update role API
- Get Roles API
- Delete Role API
- Delete Privileges API
- Get Builtin Privileges API
- Get Application Privileges API
- Clear Roles Cache API
- Clear Privileges Cache API
- Clear Realm Cache API
- Clear API Key Cache API
- Clear Service Account Token Cache API
- Authenticate API
- Has Privileges API
- Get User Privileges API
- SSL Certificate API
- Create or update role mapping API
- Get Role Mappings API
- Delete Role Mapping API
- Create Token API
- Invalidate Token API
- Create or update privileges API
- Create API Key API
- Grant API key API
- Get API Key information API
- Invalidate API Key API
- Get Service Accounts API
- Create Service Account Token API
- Delete Service Account Token API
- Get Service Account Credentials API
- Text Structure APIs
- Watcher APIs
- Graph APIs
- CCR APIs
- Index Lifecycle Management APIs
- Snapshot Lifecycle Management APIs
- Create or update snapshot lifecycle policy API
- Delete Snapshot Lifecycle Policy API
- Get Snapshot Lifecycle Policy API
- Start Snapshot Lifecycle Management API
- Stop Snapshot Lifecycle Management API
- Snapshot Lifecycle Management Status API
- Execute Snapshot Lifecycle Policy API
- Execute Snapshot Lifecycle Retention API
- Searchable Snapshots APIs
- Transform APIs
- Enrich APIs
- Using Java Builders
- Migration Guide
- License
Changing the application’s code
editChanging the application’s code
editThe RestHighLevelClient
supports the same request and response objects
as the TransportClient
, but exposes slightly different methods to
send the requests.
More importantly, the high-level client:
-
does not support request builders. The legacy methods like
client.prepareIndex()
must be changed to use request constructors likenew IndexRequest()
to create requests objects. The requests are then executed using synchronous or asynchronous dedicated methods likeclient.index()
orclient.indexAsync()
.
How to migrate the way requests are built
editThe Java API provides two ways to build a request: by using the request’s constructor or by using
a request builder. Migrating from the TransportClient
to the high-level client can be
straightforward if application’s code uses the former, while changing usages of the latter can
require more work.
With request constructors
editWhen request constructors are used, like in the following example:
IndexRequest request = new IndexRequest("index").id("id"); request.source("{\"field\":\"value\"}", XContentType.JSON);
The migration is very simple. The execution using the TransportClient
:
IndexResponse response = transportClient.index(indexRequest).actionGet();
Can be easily replaced to use the RestHighLevelClient
:
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
With request builders
editThe Java API provides a request builder for every type of request. They are exposed by the
TransportClient
through the many prepare()
methods. Here are some examples:
IndexRequestBuilder indexRequestBuilder = transportClient.prepareIndex(); DeleteRequestBuilder deleteRequestBuilder = transportClient.prepareDelete(); SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch();
Create a |
|
Create a |
|
Create a |
Since the Java High Level REST Client does not support request builders, applications that use them must be changed to use requests constructors instead.
While you are incrementally migrating your application and you have both the transport client
and the high level client available you can always get the Request
object from the Builder
object
by calling Builder.request()
. We do not advise continuing to depend on the builders in the long run
but it should be possible to use them during the transition from the transport client to the high
level rest client.
How to migrate the way requests are executed
editThe TransportClient
allows to execute requests in both synchronous and asynchronous ways. This is also
possible using the high-level client.
Synchronous execution
editThe following example shows how a DeleteRequest
can be synchronously executed using the TransportClient
:
DeleteRequest request = new DeleteRequest("index", "doc", "id"); DeleteResponse response = transportClient.delete(request).actionGet();
Create the |
|
Execute the |
The same request synchronously executed using the high-level client is:
Asynchronous execution
editThe following example shows how a DeleteRequest
can be asynchronously executed using the TransportClient
:
DeleteRequest request = new DeleteRequest("index", "doc", "id"); transportClient.delete(request, new ActionListener<DeleteResponse>() { @Override public void onResponse(DeleteResponse deleteResponse) { } @Override public void onFailure(Exception e) { } });
Create the |
|
Execute the |
|
The |
|
The |
The same request asynchronously executed using the high-level client is:
DeleteRequest request = new DeleteRequest("index", "id"); client.deleteAsync(request, RequestOptions.DEFAULT, new ActionListener<DeleteResponse>() { @Override public void onResponse(DeleteResponse deleteResponse) { } @Override public void onFailure(Exception e) { } });
Create the |
|
Execute the |
|
The |
|
The |
Checking Cluster Health using the Low-Level REST Client
editAnother common need is to check the cluster’s health using the Cluster API. With
the TransportClient
it can be done this way:
ClusterHealthResponse response = client.admin().cluster().prepareHealth().get(); ClusterHealthStatus healthStatus = response.getStatus(); if (healthStatus != ClusterHealthStatus.GREEN) { }
Execute a |
|
Retrieve the cluster’s health status from the response |
|
Handle the situation where the cluster’s health is not green |
With the low-level client, the code can be changed to:
Request request = new Request("GET", "/_cluster/health"); request.addParameter("wait_for_status", "green"); Response response = client.getLowLevelClient().performRequest(request); ClusterHealthStatus healthStatus; try (InputStream is = response.getEntity().getContent()) { Map<String, Object> map = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); healthStatus = ClusterHealthStatus.fromStringString) map.get("status"; } if (healthStatus != ClusterHealthStatus.GREEN) { }
Set up the request to wait for the cluster’s health to become green if it isn’t already. |
|
Make the request and the get back a |
|
Retrieve an |
|
Parse the response’s content using Elasticsearch’s helper class |
|
Retrieve the value of the |
|
Handle the situation where the cluster’s health is not green |
Note that for convenience this example uses Elasticsearch’s helpers to parse the JSON response body, but any other JSON parser could have been use instead.
On this page