- 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
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.SKIP_DEDICATED_MASTERS
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.