This topic describes how to use a PHP, Python, Java, or Go client to access an Alibaba Cloud Elasticsearch cluster. This topic also provides sample code and usage notes of each type of client.

Preparations

  • Install a JDK. The JDK version must be 1.8 or later.

    For more information, see Install a JDK.

  • Create an Alibaba Cloud Elasticsearch cluster.
    For more information, see Create an Alibaba Cloud Elasticsearch cluster.
    Note To ensure compatibility, we recommend that you create an Alibaba Cloud Elasticsearch cluster of the same version as the client. For more information about the compatibility between Elasticsearch and clients, see Compatibility.
  • Enable the Auto Indexing feature for the cluster.

    For more information, see Configure the YML file.

  • Configure a whitelist for the cluster to ensure normal communication among networks.
    • If the server that runs code is located in an Internet environment, you can access the cluster by using its public endpoint. Before you access the cluster, you must enable the Public Network Access feature for the cluster and add the public IP address of the server to the public IP address whitelist of the cluster. For more information, see Configure a public or private IP address whitelist for an Elasticsearch cluster.
      Notice
      • If you are using a public network, add the IP address of the jump server that controls outbound traffic of the public network to the whitelist.
      • You can also add 0.0.0.0/0 to the whitelist to allow requests from all IPv4 addresses. If you make this configuration, all public IP addresses can be used to access the cluster. This poses security risks. We recommend that you evaluate the risks before you make this configuration.
    • If the server that runs code is located in the same virtual private cloud (VPC) as the cluster, you can access the cluster by using its internal endpoint. Before you access the cluster, make sure that the private IP address of the server is added to the private IP address whitelist of the cluster. By default, 0.0.0.0/0 is added to the whitelist.

PHP client

Warning
  • The default connection pool provided by the PHP client of open source Elasticsearch is not suitable for accessing services on the cloud. Alibaba Cloud Elasticsearch handles requests sent from clients based on load balancing. Therefore, a PHP client must use SimpleConnectionPool as the connection pool. If SimpleConnectionPool is not used as the connection pool, a connection error occurs when your Alibaba Cloud Elasticsearch cluster is restarted.
  • A PHP client must be configured to reconnect to an Elasticsearch cluster after the client is disconnected. If the PHP client cannot reconnect to the cluster, an error may occur (for example, the "No enabled connection" error message is reported) during a restart of the cluster even if SimpleConnectionPool is used as the connection pool.
To test the connectivity to the Alibaba Cloud Elasticsearch cluster, connect a PHP client to the cluster over port 9200. Sample code:
<?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);
?>

When you use the preceding code, you must replace the parameters listed in the following table with your actual values.

Parameter Description
<YourEsHost> The internal or public endpoint of your Alibaba Cloud Elasticsearch cluster. You can obtain the endpoint from the Basic Information page of your cluster. For more information, see View the basic information of a cluster.
<UserName> The username that is used to access your Alibaba Cloud Elasticsearch cluster. The default username is elastic.
<YourPassword> The password that is used to access your Alibaba Cloud Elasticsearch cluster. The password is specified when you create the cluster. If you forget the password, you can reset it. For more information about the procedure and precautions for resetting the password, see Reset the access password for an Elasticsearch cluster.
<YourEsIndex> The name of the index in your Alibaba Cloud Elasticsearch cluster.
<YourEsType> The type of documents in the index.
Notice In versions earlier than Elasticsearch V7.0, you can customize a type for your documents. In Elasticsearch V7.0 and later, the type of documents can only be _doc.
<YourEsId> The ID of a document in the index.
<YourEsField> The name of a field in the document.
<YourEsFieldValue> The value of the field.

For more information about the PHP client for Elasticsearch, see Elasticsearch-PHP.

Python client

To test the connectivity to the Elasticsearch cluster, connect a Python client to the cluster over port 9200. Sample code:

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'])

When you use the preceding code, you must replace the parameters listed in the following table with your actual values.

Parameter Description
<YourEsHost> The internal or public endpoint of your Alibaba Cloud Elasticsearch cluster. You can obtain the endpoint from the Basic Information page of your cluster. For more information, see View the basic information of a cluster.
<UserName> The username that is used to access your Alibaba Cloud Elasticsearch cluster. The default username is elastic.
<YourPassword> The password that is used to access your Alibaba Cloud Elasticsearch cluster. The password is specified when you create the cluster. If you forget the password, you can reset it. For more information about the procedure and precautions for resetting the password, see Reset the access password for an Elasticsearch cluster.
<YourEsIndex> The name of the index in your Alibaba Cloud Elasticsearch cluster.
<YourEsType> The type of documents in the index.
Notice In versions earlier than Elasticsearch V7.0, you can customize a type for your documents. In Elasticsearch V7.0 and later, the type of documents can only be _doc.
<YourEsId> The ID of a document in the index.
<YourEsField1> The name of Field 1 in the document.
<YourEsFieldValue1> The value of Field 1.
<YourEsField2> The name of Field 2 in the document.
<YourEsFieldValue2> The value of Field 2.

For more information about the Python client for Elasticsearch, see Elasticsearch Python Client.

Java client

Java clients include Transport Client, Low Level REST Client, and High Level REST Client. For more information about the sample code for each type of client, see Java API.
Notice Java Transport Client communicates with Elasticsearch over TCP. If the client communicates with Elasticsearch of a version that does not match its version, incompatibility issues may occur. In later versions of open source Elasticsearch, Transport Client is deprecated. If you use Transport Client 5.5 to access an Elasticsearch V5.5 cluster or use Transport Client 5.6 to access an Elasticsearch V5.6 cluster, the system displays the "NoNodeAvailableException" error message. To ensure version compatibility, we recommend that you use Transport Client 5.3.3 or Java Low Level REST Client to access an Elasticsearch cluster. If you use Transport Client 5.3.3, set client.transport.sniff to false.

Go client

Before you use a Go client to access an Elasticsearch cluster, you must install a compilation environment for Go. For more information, see The Go Programming Language. In the following sample code, a Go 1.13.4 client is used to connect to the Elasticsearch cluster over port 9200.

package main

import (
    "context"
    "gopkg.in/olivere/elastic.v5"
    "gopkg.in/olivere/elastic.v5/config"
    "log"
)

const (
    url      = "<YourEsHost>"     
    username = "<UserName>"        
    password = "<YourPassword>"       
)

func main() {
    var sniff = false     
    cfg := &config.Config{
        URL:      url,
        Username: username,
        Password: password,
    }

    cfg.Sniff = &sniff          
    var client, err = elastic.NewClientFromConfig(cfg)
    if err != nil {
        log.Println(err)
        return
    }

    exists, err := client.IndexExists("<YourEsIndex>").Do(context.Background())   // Create an index in the Elasticsearch cluster. A log is returned based on the connection status. 
    if err != nil {
        log.Println(err)
    }
    log.Println(exists)
}

When you use the preceding code, you must replace the parameters listed in the following table with your actual values.

Parameter Description
<YourEsHost> The internal or public endpoint of your Alibaba Cloud Elasticsearch cluster. You can obtain the endpoint from the Basic Information page of your cluster. For more information, see View the basic information of a cluster.
<UserName> The username that is used to access your Alibaba Cloud Elasticsearch cluster. The default username is elastic.
<YourPassword> The password that is used to access your Alibaba Cloud Elasticsearch cluster. The password is specified when you create the cluster. If you forget the password, you can reset it. For more information about the procedure and precautions for resetting the password, see Reset the access password for an Elasticsearch cluster.
<YourEsIndex> The name of the index in your Alibaba Cloud Elasticsearch cluster.
Notice You must set the sniff parameter to false to prevent sniffing on connections. If you set this parameter to true, connection failures occur.

If the client is connected to the cluster, the following result is returned:

2019/11/29 10:07:37 true

References

Other clients for Elasticsearch: Elasticsearch Clients