Java High Level REST Client 7.x lets you call Elasticsearch APIs from Java applications. This guide walks you through setting up the client and running index and delete operations against an Alibaba Cloud Elasticsearch cluster.
Prerequisites
Before you begin, ensure that you have:
-
An Alibaba Cloud Elasticsearch cluster running version 7.x. For setup instructions, see Create an Alibaba Cloud Elasticsearch cluster
-
Auto Indexing enabled on the cluster. Without it, index operations fail. See Configure the YML file
-
Network access configured between your client and the cluster (see Network access below)
-
JDK 1.8 or later installed
-
A Java Maven project with the POM dependencies added to
pom.xml
Java High Level REST Client is forward compatible. For example, client version 7.10 works with clusters running version 7.10 or later. To access the latest client features, use a client version that matches your cluster version.
Network access
Choose the access method based on where your Java application runs.
Public network access (Internet)
If your application runs outside the cluster's virtual private cloud (VPC):
-
Enable Public Network Access on the cluster.
-
Add the public IP address of your application server to the cluster's public IP address whitelist. See Configure a public or private IP address whitelist for an Elasticsearch cluster.
-
Connect using the cluster's public endpoint on port 9200.
If your client is on a home or office network, add the Internet egress IP address to the whitelist — not the client's private IP address. To allow all IPv4 addresses, add 0.0.0.0/0, but be aware this exposes the cluster to the public Internet.
VPC access (internal)
If your application runs in the same VPC as the cluster:
-
Connect using the cluster's private endpoint on port 9200.
-
The private IP address whitelist defaults to
0.0.0.0/0, so no additional whitelist configuration is required unless your security policy requires it.
If no whitelist is configured or the configuration is incorrect, connections time out with the error Timeout connecting. To access Kibana from a client, configure a separate IP address whitelist for Kibana. See Configure a public or private IP address whitelist for Kibana.
POM (Project Object Model) dependencies
Add the following dependencies to your pom.xml. Replace 7.x with the specific version that matches your cluster, for example 7.10.2.
Maven
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.x</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.20.0</version>
</dependency>
Apache Log4j has a known remote code execution (RCE) vulnerability. See Vulnerability notice | RCE vulnerability in Apache Log4j 2 for details and mitigation steps.
Authentication
The client uses basic access authentication. Pass the username and password you set when creating the cluster — these are the same credentials used to log in to the Kibana console.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("<username>", "<password>")
);
| Placeholder | Description |
|---|---|
<username> |
The username set when creating the Elasticsearch cluster |
<password> |
The password set when creating the Elasticsearch cluster |
Index and delete a document
The following example creates a RestHighLevelClient, indexes a document using the Index API, and deletes it using the Delete API.
The example also limits the async response buffer to 30 MiB (down from the 100 MiB default) — useful in environments with constrained JVM memory.
Download the complete sample code.
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class RestClientTest74 {
private static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// Limit the async response buffer to 30 MiB (default is 100 MiB).
builder.setHttpAsyncResponseConsumerFactory(
new HttpAsyncResponseConsumerFactory
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
public static void main(String[] args) {
// Configure basic access authentication.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("<username>", "<password>")
);
// Build the client. Use the public endpoint for Internet access,
// or the private endpoint for VPC access.
RestClientBuilder builder = RestClient
.builder(new HttpHost("<cluster-endpoint>", 9200, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestHighLevelClient client = new RestHighLevelClient(builder);
try {
// --- Index a document ---
Map<String, Object> document = new HashMap<>();
document.put("<field_01>", "<value_01>");
document.put("<field_02>", "<value_02>");
// For Elasticsearch 7.x clusters, the type must be _doc.
IndexRequest indexRequest = new IndexRequest("<index_name>", "_doc", "<doc_id>")
.source(document);
IndexResponse indexResponse = client.index(indexRequest, COMMON_OPTIONS);
System.out.println("Indexed document. Version: " + indexResponse.getVersion());
// --- Delete the document ---
DeleteRequest deleteRequest = new DeleteRequest("<index_name>", "_doc", "<doc_id>");
DeleteResponse deleteResponse = client.delete(deleteRequest, COMMON_OPTIONS);
System.out.println("Deleted document: " + deleteResponse.toString());
} catch (IOException e) {
// Handle connection or I/O errors.
} finally {
try {
client.close();
} catch (IOException e) {
// Handle close errors.
}
}
}
}
Replace the placeholders with your actual values:
| Placeholder | Description | Example |
|---|---|---|
<username> |
Cluster username | elastic |
<password> |
Cluster password | — |
<cluster-endpoint> |
Public or private endpoint, from the cluster's Basic Information page | es-xxx.elasticsearch.aliyuncs.com |
<index_name> |
Name of the index to create | my-index |
<doc_id> |
Document ID | 1 |
<field_01>, <field_02> |
Field names in the document | title, content |
<value_01>, <value_02> |
Corresponding field values | Hello, World |
High-concurrency configuration
In high-concurrency scenarios, increase the maximum number of client connections to avoid request queuing:
httpClientBuilder.setMaxConnTotal(500);
httpClientBuilder.setMaxConnPerRoute(300);
Full client initialization with connection pool settings:
String host = "<cluster-endpoint>";
int port = 9200;
String username = "<username>";
String password = "<password>";
final int maxConnTotal = 500;
final int maxConnPerRoute = 300;
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost(host, port, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setMaxConnTotal(maxConnTotal);
httpClientBuilder.setMaxConnPerRoute(maxConnPerRoute);
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
})
);
What's next
-
Java High Level REST Client official documentation — full API reference for all supported operations