- 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
- Put 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
- Put 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
- Cluster APIs
- Ingest APIs
- Snapshot APIs
- Tasks APIs
- Script APIs
- Licensing APIs
- Machine Learning APIs
- Put anomaly detection job API
- Get anomaly detection jobs API
- Delete anomaly detection job API
- Open anomaly detection job API
- Close anomaly detection job API
- Update anomaly detection job API
- Flush Job API
- Put datafeed API
- Update datafeed API
- Get datafeed API
- Delete datafeed API
- Preview Datafeed API
- Start datafeed API
- Stop Datafeed API
- Get datafeed stats API
- Get anomaly detection job stats API
- Forecast Job API
- Delete Forecast API
- Get buckets API
- Get overall buckets API
- Get records API
- Post Data API
- Get influencers API
- Get categories API
- Get calendars API
- Put calendar API
- Get calendar events API
- Post Calendar Event API
- Delete calendar event API
- Put anomaly detection jobs in calendar API
- Delete anomaly detection jobs from calendar API
- Delete calendar API
- Estimate anomaly detection job model memory API
- Get data frame analytics jobs API
- Get data frame analytics jobs stats API
- Put data frame analytics jobs API
- Delete data frame analytics jobs API
- Start data frame analytics jobs API
- Stop data frame analytics jobs API
- Evaluate data frame analytics API
- Explain data frame analytics API
- Get trained models API
- Put trained model API
- Get trained models stats API
- Delete trained model API
- Put Filter API
- Get filters API
- Update filter API
- Delete Filter API
- Get model snapshots API
- Delete Model Snapshot API
- Revert Model Snapshot API
- Update model snapshot API
- ML get info API
- Delete Expired Data API
- Set Upgrade Mode API
- Migration APIs
- Rollup APIs
- Security APIs
- Put User API
- Get Users API
- Delete User API
- Enable User API
- Disable User API
- Change Password API
- Put Role API
- Get Roles API
- Delete Role API
- Delete Privileges API
- Get Builtin Privileges API
- Get Privileges API
- Clear Roles Cache API
- Clear Realm Cache API
- Authenticate API
- Has Privileges API
- Get User Privileges API
- SSL Certificate API
- Put Role Mapping API
- Get Role Mappings API
- Delete Role Mapping API
- Create Token API
- Invalidate Token API
- Put Privileges API
- Create API Key API
- Get API Key information API
- Invalidate API Key API
- Watcher APIs
- Graph APIs
- CCR APIs
- Index Lifecycle Management APIs
- Snapshot Lifecycle Management APIs
- Put 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
- Transform APIs
- Enrich APIs
- Using Java Builders
- Migration Guide
- License
Performing requests
editPerforming requests
editOnce the RestClient
has been created, requests can be sent by calling either
performRequest
or performRequestAsync
. performRequest
is synchronous and
will block the calling thread and return the Response
when the request is
successful or throw an exception if it fails. performRequestAsync
is
asynchronous and accepts a ResponseListener
argument that it calls with a
Response
when the request is successful or with an Exception
if it fails.
This is synchronous:
And this is asynchronous:
Request request = new Request( "GET", "/"); Cancellable cancellable = restClient.performRequestAsync(request, new ResponseListener() { @Override public void onSuccess(Response response) { } @Override public void onFailure(Exception exception) { } });
The HTTP method ( |
|
The endpoint on the server |
|
Handle the response |
|
Handle the failure |
You can add request parameters to the request object:
request.addParameter("pretty", "true");
You can set the body of the request to any HttpEntity
:
request.setEntity(new NStringEntity( "{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
The ContentType
specified for the HttpEntity
is important
because it will be used to set the Content-Type
header so that Elasticsearch
can properly parse the content.
You can also set it to a String
which will default to
a ContentType
of application/json
.
request.setJsonEntity("{\"json\":\"text\"}");
RequestOptions
editThe RequestOptions
class holds parts of the request that should be shared
between many requests in the same application. You can make a singleton
instance and share it between all requests:
private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); builder.addHeader("Authorization", "Bearer " + TOKEN); builder.setHttpAsyncResponseConsumerFactory( new HttpAsyncResponseConsumerFactory .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); }
addHeader
is for headers that are required for authorization or to work with
a proxy in front of Elasticsearch. There is no need to set the Content-Type
header because the client will automatically set that from the HttpEntity
attached to the request.
You can set the NodeSelector
which controls which nodes will receive
requests. NodeSelector.NOT_MASTER_ONLY
is a good choice.
You can also customize the response consumer used to buffer the asynchronous responses. The default consumer will buffer up to 100MB of response on the JVM heap. If the response is larger then the request will fail. You could, for example, lower the maximum size which might be useful if you are running in a heap constrained environment like the example above.
Once you’ve created the singleton you can use it when making requests:
request.setOptions(COMMON_OPTIONS);
You can also customize these options on a per request basis. For example, this adds an extra header:
RequestOptions.Builder options = COMMON_OPTIONS.toBuilder(); options.addHeader("cats", "knock things off of other things"); request.setOptions(options);
Multiple parallel asynchronous actions
editThe client is quite happy to execute many actions in parallel. The following
example indexes many documents in parallel. In a real world scenario you’d
probably want to use the _bulk
API instead, but the example is illustrative.
final CountDownLatch latch = new CountDownLatch(documents.length); for (int i = 0; i < documents.length; i++) { Request request = new Request("PUT", "/posts/doc/" + i); //let's assume that the documents are stored in an HttpEntity array request.setEntity(documents[i]); restClient.performRequestAsync( request, new ResponseListener() { @Override public void onSuccess(Response response) { latch.countDown(); } @Override public void onFailure(Exception exception) { latch.countDown(); } } ); } latch.await();
Cancelling asynchronous requests
editThe performRequestAsync
method returns a Cancellable
that exposes a single
public method called cancel
. Such method can be called to cancel the on-going
request. Cancelling a request will result in aborting the http request through
the underlying http client. On the server side, this does not automatically
translate to the execution of that request being cancelled, which needs to be
specifically implemented in the API itself.
The use of the Cancellable
instance is optional and you can safely ignore this
if you don’t need it. A typical usecase for this would be using this together with
frameworks like Rx Java or the Kotlin’s suspendCancellableCoRoutine
. Cancelling
no longer needed requests is a good way to avoid putting unnecessary
load on Elasticsearch.