Connect to a cluster from an application
Connect to an Alibaba Cloud Elasticsearch cluster using Java, Python, or Go.
Before you begin
Obtain the cluster endpoint
You can connect to your Elasticsearch cluster by using an internal endpoint over a VPC private network or a public endpoint.
-
Internal endpoint: Provides a low-latency, high-stability connection to your Elasticsearch cluster. This endpoint is enabled by default upon cluster creation.
-
Public endpoint: Allows you to connect to your Elasticsearch cluster over the internet. You must enable this endpoint manually.
Enable public access
-
Log on to the Elasticsearch console and navigate to the Basic Information page of your instance.
-
In the navigation pane, choose Configuration and Management > Security Settings and enable public access. Public access is enabled once the cluster status changes from Initializing to Valid.
After you enable public access, the public endpoint is in the format
es-cn-<instance_ID>.public.elasticsearch.aliyuncs.com. The public IP whitelist is empty by default and must be configured.ImportantUsing a public endpoint can compromise the security of your Elasticsearch cluster. If you use a public endpoint, be sure to configure an IP whitelist and disable public access when you are done.
Configure an IP whitelist
To secure your cluster, you must add the IP address of the device you want to use for access to the VPC private network or public IP whitelist of the Elasticsearch cluster. Only devices with IP addresses in the whitelist can access the cluster.
-
Obtain the IP address of the device you want to use for access.
The following table explains how to obtain the IP address for different scenarios.
Scenario
IP address
Method
Connect to an Elasticsearch cluster from a local device
The public IP address of your local device.
If your local device is on a local area network (LAN), such as a home or corporate network, you must add the public IP address of the LAN's gateway to the cluster's public IP whitelist.
Run the
curl ipinfo.io/ipcommand to find the public IP of your local device.Connect to an Elasticsearch cluster from an ECS instance in a different VPC
The public IP of the ECS instance.
Log on to the ECS console to view it in the instance list.
Connect to an Elasticsearch cluster from an ECS instance in the same VPC
The private IP of the ECS instance.
Log on to the ECS console to view it in the instance list.
-
Add this IP address to a whitelist group.
-
Log on to the Elasticsearch console. On the Basic Information page of your instance, choose Configuration and Management > Security Settings in the navigation pane. Click Modify to configure the VPC private network or public IP whitelist.
-
Click Configure to the right of the default group. In the dialog box that appears, add IP addresses to the VPC private network or public IP whitelist. You can add up to 300 IP addresses or CIDR blocks to a cluster. Separate multiple entries with a comma (,) and do not add spaces around it.
-
You can also click Add IP address whitelist Group to create a custom group.
-
Whitelist groups are for IP address management only and do not affect access permissions. All IP addresses across all groups have the same permissions.
Configuration type
Format and example
Important notes
IPv4 address format
-
Single IP:
192.168.0.1 -
CIDR block:
192.168.0.0/24
-
Deny all access:
127.0.0.1 -
Allow all access:
0.0.0.0/0ImportantThis poses a high security risk. We strongly recommend that you do not configure
0.0.0.0/0.Some cluster versions (such as 7.16 and 8.5) and regions do not support
0.0.0.0/0. Refer to the console UI or error messages for details.
IPv6 address format
(Supported only for v2 deployment architecture clusters in the China (Hangzhou) region)
-
Single IP:
2401:XXXX:1000:24::5 -
CIDR block:
2401:XXXX:1000::/48
-
Deny all access:
::1 -
Allow all access:
::/0ImportantThis poses a high security risk. We strongly recommend that you do not configure
::/0.Some cluster versions do not support
::/0. Refer to the console UI or configuration prompts for details.
-
-
Click OK.
-
Protocols and certificates
-
Ensure your client's language version (Java, Python, or Go) matches the ES cluster's underlying runtime.
-
Public HTTPS: Uses a CA-issued certificate. No special client configuration needed — connect directly via
https://. -
Private HTTPS: Uses a self-signed certificate. Skip certificate verification in your client as shown below.
Connect to the cluster
Java
-
Install Java Development Kit (JDK) 1.8 or later.
-
Configure Maven dependencies.
ImportantSet
versionto match your cluster version (8.17.0 in this example). Mismatchedversionvalues cause dependency resolution failures.<dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.17.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency> -
Configure YML parameters to enable automatic index creation:
action.auto_create_index: true. The following example creates an index named hr_test.
Basic connection example
Applies to public HTTPS or private HTTP connections:
package org.example;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.cat.IndicesResponse;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
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.client.*;
import java.io.IOException;
public class RestClientTest {
public static void main(String[] args) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("{UserName}", "{YourPassword}"));
// Use "https" for public HTTPS access or "http" for private HTTP access.
RestClient restClient = RestClient.builder(new HttpHost("{YourEsHost}", 9200, "https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);
try {
CreateIndexResponse indexRequest = elasticsearchClient.indices().create(createIndexBuilder -> createIndexBuilder
.index("hr_test")
.aliases("foo", aliasBuilder -> aliasBuilder.isWriteIndex(true))
);
System.out.println("Index document successfully! " + indexRequest.acknowledged());
transport.close();
restClient.close();
} catch (IOException ioException) {
// Handle exceptions.
}
}
}
Private HTTPS connection example
For private HTTPS, skip certificate verification:
package org.example;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.*;
import javax.net.ssl.SSLContext;
public class RestClientTestPrivateHttps {
public static void main(String[] args) throws Exception {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("{UserName}", "{YourPassword}"));
// Create an SSLContext that trusts all certificates.
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, (chain, authType) -> true) // Trust all certificates.
.build();
RestClient restClient = RestClient.builder(new HttpHost("{YourEsHost}", 9200, "https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)
.setSSLContext(sslContext) // Set the SSLContext.
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); // Skip hostname verification.
}
}).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);
// Perform operations.
System.out.println(elasticsearchClient.info());
transport.close();
restClient.close();
}
}
Python
These examples use ES 8.17.0. Replace with your cluster version.
Basic connection example
Applies to public HTTPS or private HTTP connections:
pip install elasticsearch==8.17.0from elasticsearch import Elasticsearch
es = Elasticsearch(
hosts=['https://<YourEsHost>:9200'], # Use 'https://' for public HTTPS access or 'http://' for private HTTP access.
basic_auth=('<UserName>', '<YourPassword>'),
)
print(es.info())
Private HTTPS connection example
from elasticsearch import Elasticsearch
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Disable SSL warnings (optional).
es = Elasticsearch(
hosts=['https://<YourEsHost>:9200'],
basic_auth=('<UserName>', '<YourPassword>'),
verify_certs=False, # Skip certificate verification.
ssl_show_warn=False, # Disable SSL warnings.
)
print(es.info())
Go
These examples use the Elasticsearch Go Client for ES 8.x clusters.
Basic connection example
Applies to public HTTPS or private HTTP connections:
go get github.com/elastic/go-elasticsearch/v8
package main
import (
"github.com/elastic/go-elasticsearch/v8""log"
)
func main() {
cfg := elasticsearch.Config{
Addresses: []string{"https://<YourEsHost>:9200"}, // Use "https://" for public HTTPS access or "http://" for private HTTP access.
Username: "<UserName>",
Password: "<YourPassword>",
}
es, _ := elasticsearch.NewClient(cfg)
res, _ := es.Info()
defer res.Body.Close()
log.Println(res)
}
Private HTTPS connection example
package main
import (
"crypto/tls""net/http""github.com/elastic/go-elasticsearch/v8""log"
)
func main() {
cfg := elasticsearch.Config{
Addresses: []string{"https://<YourEsHost>:9200"},
Username: "<UserName>",
Password: "<YourPassword>",
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // Skip certificate verification.
},
}
es, _ := elasticsearch.NewClient(cfg)
res, _ := es.Info()
defer res.Body.Close()
log.Println(res)
}
Parameters
|
Parameter |
Description |
|
UserName |
The default username is Avoid this account in production. Create custom roles with fine-grained permissions using Manage user permissions by using Elasticsearch X-Pack roles. |
|
YourPassword |
The password for the specified |
|
https |
The access protocol. HTTP is enabled by default. For security, enable HTTPS manually. In the Elasticsearch console, go to the Basic Information page of your instance, then choose Configuration and Management > Security Settings to enable HTTPS. Important
|
|
YourEsHost |
The cluster endpoint (VPC or public) from Prerequisites:
|
|
9200 |
The cluster access port. Default: 9200 for both VPC and public access. |
FAQ
If the cluster status is healthy but the client cannot connect, troubleshoot using the following methods.
Routing table diagnostics
If an ES connection fails within the same VPC, check the routing table. Installing Docker modifies routing information, which may cause routes to the ES network segment to be missing or to point to an incorrect gateway. Run the following command on the ECS instance to view the routing table:
route -n
Check whether a route to the ES network segment exists in the output. If the route is missing or the gateway is incorrect, fix the routing configuration and retry the connection. Also check whether a corporate firewall is blocking traffic to the ES network segment.
Domain and port verification
Use the curl command to verify that the domain and port are correctly specified:
curl -u {UserName}:{YourPassword} https://{YourEsHost}:9200
A "Could not resolve host" response indicates a domain name typo. Common errors include missing characters in the domain name or omitting the port number.
Client timeout parameter configuration
The Java client does not set connection timeout or socket timeout by default. On unstable networks, connections may block indefinitely. Use setRequestConfigCallback to configure timeout parameters:
RestClient restClient = RestClient.builder(new HttpHost("{YourEsHost}", 9200, "https"))
.setRequestConfigCallback(builder -> builder
.setConnectTimeout(10000)
.setSocketTimeout(30000))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.build();
ConnectTimeout controls how long to wait for a connection to be established — set to 10000 milliseconds (10 seconds). SocketTimeout controls how long to wait for data to be read — set to 30000 milliseconds (30 seconds). Adjust these values based on your network environment.
How to test network latency from an ECS instance to an Elasticsearch cluster and notes on public network access
An ECS instance outside the VPC of your cluster can call Elasticsearch over the public endpoint, and public access is a supported connection method. Before you use it, make sure that public access is enabled for the cluster and that the public IP address of the ECS instance is in the public access whitelist. Both are described at the beginning of this topic.
A public connection traverses more hops and a longer network path than a connection that uses an internal endpoint over a VPC private network, so its network latency is noticeably higher and it is more sensitive to link jitter. For production environments, connect over an internal endpoint over a VPC private network. Reserve public access for testing, temporary troubleshooting, or cases where a private network path cannot be established.
To measure the network quality between the ECS instance and the cluster, run either of the following checks on the ECS instance.
-
Use ping to verify basic connectivity and observe the round-trip time (RTT):
ping {YourEsHost}Check the average RTT and the packet loss rate in the output. A high average RTT or any packet loss indicates poor link quality. Some network environments and security policies block ICMP, so an unreachable ping result does not necessarily mean that the Elasticsearch service is unavailable. In that case, confirm port connectivity with the curl command in the "Domain and port verification" entry of this FAQ.
-
Use MTR for hop-by-hop network path tracing to locate the bottleneck. MTR is a general-purpose network diagnostic tool that you install on the ECS instance yourself:
mtr -r -c 100 {YourEsHost}Review the packet loss rate and the latency of each hop. If the packet loss rate or the latency keeps rising from a specific hop onward, the bottleneck is at that hop or later in the path. This tells you whether the problem is on the ECS side, in the intermediate public network, or on the access side.
If the measured latency is high and your workload is latency-sensitive, switch to an internal endpoint over a VPC private network in the same region and the same VPC. Then tune the connection and read timeouts as described in the "Client timeout parameter configuration" entry of this FAQ.
Troubleshoot frequent "No alive nodes found" errors that persist after scaling up the cluster
A No alive nodes found error means that the client cannot find any available node in the node list that it maintains. It is usually caused by unstable network connectivity, request timeouts, or abnormal routing between the client and the cluster, rather than by insufficient cluster resources. That is why scaling up the cluster often does not resolve the error. Investigate the network connection first.
-
Identify the network path that the client uses to reach the cluster. Determine whether the client connects over an internal endpoint over a VPC private network or over a public endpoint. Then check for cross-region access, cross-VPC access, or a long public network path, all of which make node probing more likely to fail because of network jitter.
For a public network connection or an inter-region connection, measure the link quality as described in the "How to test network latency from an ECS instance to an Elasticsearch cluster and notes on public network access" entry of this FAQ. Then switch to an internal endpoint over a VPC private network in the same region and the same VPC.
-
Examine the context of the client log. Instead of reading only the
No alive nodes foundline, check the errors logged around it for a connect timeout, a socket timeout, an SSL/TLS handshake failure, or a certificate verification failure. Those accompanying errors determine your next action: adjust the timeout parameters, or correct the protocol and certificate configuration described in the "Protocols and certificates" section of this topic. -
Combine the checks that this FAQ already provides. Follow the "Routing table diagnostics" entry to verify that a route to the ES network segment exists and points to the correct gateway. Installing Docker, for example, modifies routing information. Also verify that no firewall blocks traffic to the ES network segment.
Then follow the "Client timeout parameter configuration" entry to set an explicit connect timeout and socket timeout in the client. Explicit timeouts prevent a request from blocking for a long time on an unstable network and causing the node to be treated as unavailable.
If none of these network-layer checks reveals a problem, use the cluster monitoring data to confirm whether a resource bottleneck actually exists. Do not treat scaling up the cluster as the first remedy.