All Products
Search
Document Center

Elasticsearch:Connect to an Alibaba Cloud Elasticsearch cluster

Last Updated:Jun 11, 2026

This topic provides sample code and important notes for connecting to an Alibaba Cloud Elasticsearch cluster using PHP, Python, Java, and Go clients.

Prerequisites

  • Create an Alibaba Cloud Elasticsearch cluster. For more information, see Create an Alibaba Cloud Elasticsearch cluster.

  • Install the Elasticsearch client for your desired programming language.

    Use a client version that matches your Elasticsearch version to avoid compatibility issues. For more information about the version compatibility between Elasticsearch and clients, see Compatibility.

    • Elasticsearch Go client: Elasticsearch Go Client.

      Note

      Before using Go to connect to an Alibaba Cloud Elasticsearch cluster, install a Go compilation environment. For more information, see The Go Programming Language. The examples in this topic use Go 1.19.1.

    • Elasticsearch Java client: Elasticsearch Java API Client.

      Note
      • Java client types include Transport Client, Low Level REST Client, High Level REST Client, and Java API Client. For sample code for each type, see Java API. This topic uses High Level REST Client V6.7 as an example.

      • The Java Transport Client communicates with an Elasticsearch cluster over TCP. Compatibility issues may occur when the client is used to communicate with Elasticsearch clusters of different versions. For this reason, the Transport Client is deprecated in later versions. If you use Transport Client V5.5 or V5.6 to connect to an Elasticsearch cluster of V5.5 or V5.6, a NoNodeAvailableException error may occur. Use Transport Client V5.3.3 or Java Low Level REST Client to connect to the Elasticsearch cluster to ensure version compatibility.

    • Elasticsearch PHP client: Elasticsearch PHP Client.

      Note

      The default connection pool provided by the Elasticsearch PHP client is not suitable for cloud environments. Alibaba Cloud Elasticsearch provides a load-balanced domain name service. Therefore, your PHP application must use SimpleConnectionPool as the connection pool. Otherwise, connection errors can occur when your Alibaba Cloud Elasticsearch cluster restarts. The application must also implement a reconnection mechanism. Even with SimpleConnectionPool, connection errors such as "No enabled connection" may still occur when your cluster restarts.

    • Elasticsearch Python client: Elasticsearch Python Client.

    • For more information about other Elasticsearch clients, see Elasticsearch Clients.

  • Enable the Auto Indexing feature for your Elasticsearch cluster. For more information, see Configure YML parameters.

  • Configure a whitelist for the Alibaba Cloud Elasticsearch cluster to ensure network connectivity.

    • If the server that runs your code and the Alibaba Cloud Elasticsearch cluster are in the same Virtual Private Cloud (VPC), connect using the cluster's internal endpoint. Before connecting, add the server's private IP address to the VPC's private IP address whitelist (default: 0.0.0.0/0).

    • If the server that runs your code is on the public network, connect by using the cluster's public endpoint. Enable the public endpoint and add the server's public IP address to the public IP address whitelist of the Alibaba Cloud Elasticsearch cluster. For more information, see Configure a public or private IP address whitelist for an Elasticsearch cluster.

      Important
      • If you connect from a Wi-Fi or broadband network, add your public IP address to the whitelist.

      • You can also set the whitelist to 0.0.0.0/0 to allow all IPv4 addresses to access the Elasticsearch cluster. This configuration exposes the cluster to the public network and increases security risks. Use this setting only if you understand and accept the associated risks.

      • If no whitelist is configured or the whitelist is configured incorrectly, a connection timeout error occurs.

      • To access Kibana nodes from a client, you must also configure a whitelist for Kibana. For more information, see Connect to a cluster by using Kibana.

Sample code

The following examples show how to connect to an Alibaba Cloud Elasticsearch cluster using common clients.

// This example uses Go 1.19.1.
package main

import (
  "log"
  "github.com/elastic/go-elasticsearch/v7"
)

func main() {
  cfg := elasticsearch.Config {
    Addresses: []string{
      "<YourEsHost>",
    },
    Username: "<UserName>",
    Password: "<YourPassword>",
  }

  es, err := elasticsearch.NewClient(cfg)
  if err != nil {
    log.Fatalf("Error creating the client: %s", err)
  }

  res, err := es.Info()
  if err != nil {
    log.Fatalf("Error getting response: %s", err)
  }

  defer res.Body.Close()
  log.Println(res)
}
// This example uses High Level REST Client V6.7.
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 RestClientTest67 {

    private static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

        // The default cache limit is 100 MB. This example changes the value to 30 MB.
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    public static void main(String[] args) {
        // Alibaba Cloud Elasticsearch clusters require basic authentication.
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
       // Use the username and password that you configured when you created the Alibaba Cloud Elasticsearch cluster. They are also the logon credentials for the Kibana console.
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<UserName>", "<YourPassword>"));

        // Use a builder to create a REST client and configure the HttpClientConfigCallback of the HTTP client.
       // To obtain the cluster endpoint, click the ID of your Elasticsearch cluster and go to the Basic Information page.
        RestClientBuilder builder = RestClient.builder(new HttpHost("<YourEsHost>", 9200, "http"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // A RestHighLevelClient instance is built using a REST low-level client builder.
        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        try {
            // Create a request.
            Map<String, Object> jsonMap = new HashMap<>();
           jsonMap.put("<YourEsField1>", "<YourEsFieldValue1>");
           jsonMap.put("<YourEsField2>", "<YourEsFieldValue2>");
           IndexRequest indexRequest = new IndexRequest("<YourEsIndex>", "<YourEsType>", "<YourEsId>").source(jsonMap);

            // Synchronously execute the request and use custom request options (COMMON_OPTIONS).
            IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);

            long version = indexResponse.getVersion();

            System.out.println("Index document successfully! " + version);

            highClient.close();

        } catch (IOException ioException) {
            // Handle exceptions.
        }
    }
}
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()->setHosts([
  [
    'host'   => '<YourEsHost>',
    'port'   => '9200',
    'scheme' => 'http',
    'user'   => '<UserName>',
    'pass'   => '<YourPassword>'
  ]
])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
  ->setRetries(10)->build();

$indexParams = [
  'index'  => '<YourEsIndex>',
  'type'   => '<YourEsType>',
  'id'     => '<YourEsId>',
  'body'   => ['<YourEsField>' => '<YourEsFieldValue>'],
  'client' => [
    'timeout'         => 10,
    'connect_timeout' => 10
  ]
];
$indexResponse = $client->index($indexParams);
print_r($indexResponse);

$searchParams = [
  'index'  => '<YourEsIndex>',
  'type'   => '<YourEsType>',
  'body'   => [
    'query' => [
      'match' => [
        '<YourEsField>' => '<YourEsFieldValue>'
      ]
    ]
  ],
  'client' => [
    'timeout'         => 10,
    'connect_timeout' => 10
  ]
];
$searchResponse = $client->search($searchParams);
print_r($searchResponse);
?>
from elasticsearch import Elasticsearch, RequestsHttpConnection
import certifi
es = Elasticsearch(
    ['<YourEsHost>'],
    http_auth=('<UserName>', '<YourPassword>'),
    port=9200,
    use_ssl=False
)
res = es.index(index="<YourEsIndex>", doc_type="<YourEsType>", id=<YourEsId>, body={"<YourEsField1>": "<YourEsFieldValue1>", "<YourEsField2>": "<YourEsFieldValue2>"})
res = es.get(index="<YourEsIndex>", doc_type="<YourEsType>", id=<YourEsId>)
print(res['_source'])

If your Elasticsearch cluster uses the HTTPS protocol, set the value of use_ssl to True and add verify_certs=True.

es = Elasticsearch(
['<YourEsHost>'],
http_auth=('<UserName>', '<YourPassword>'),
port=9200,
use_ssl=True,
verify_certs=True
)

When you use the sample code, replace the following placeholders with their actual values.

Parameter

Description

<YourEsHost>

The internal or public endpoint of the Alibaba Cloud Elasticsearch cluster. The endpoint is available on the Basic Information page of your cluster or application.

<UserName>

The username of the Alibaba Cloud Elasticsearch cluster is elastic.

<YourPassword>

The password for the Alibaba Cloud Elasticsearch cluster user.

If you forget the password, you can reset it. For an Alibaba Cloud Elasticsearch cluster, this option is on the Security page of the cluster details page. For more information, see Reset the access password for an Elasticsearch cluster.

<YourEsIndex>

The name of the index.

<YourEsType>

The document type.

Important

In Elasticsearch versions earlier than 7.0, the document type could be customized. In Elasticsearch 7.0 and later, the document type is _doc.

<YourEsId>

The document ID.

<YourEsField>

The field name.

<YourEsFieldValue>

The value for the specified field.