This topic describes how to use the PHP, Python, and Java clients of Elasticsearch to connect to Alibaba Cloud Elasticsearch. Sample code and usage guidelines for these clients are provided.

PHP client

Warning
  • The default connection pool provided by the PHP client is not suitable for connecting to Elasticsearch instances on the cloud. Alibaba Cloud Elasticsearch handles requests sent from clients based on load balancing. Therefore, the PHP client must use the SimpleConnectionPool method to create a connection pool. Otherwise, when the Alibaba Cloud Elasticsearch is restarted, a connection error occurs. This may adversely affect your workloads.
  • However, even if the connection pool is created by using the SimpleConnectionPool method, a connection error may occur when the Elasticsearch instance is restarted. For example, the "No enabled connection" error may occur. To resolve this issue, make sure that the PHP client supports auto reconnection.
To test the connectivity to your Elasticsearch instance, connect the PHP client to your instance through port 9200. The sample code is as follows. For more information, see elasticsearch-php.
<? php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;

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

$indexParams = [
  'index'  => 'my_index',
  'type'   => 'my_type',
  'id'     => '1',
  'body'   => ['testField' => 'abc'],
  'client' => [
    'timeout'         => 10,
    'connect_timeout' => 10
  ]
];
$indexResponse = $client->index($indexParams);
print_r($indexResponse);

$searchParams = [
  'index'  => 'my_index',
  'type'   => 'my_type',
  'body'   => [
    'query' => [
      'match' => [
        'testField' => 'abc'
      ]
    ]
  ],
  'client' => [
    'timeout'         => 10,
    'connect_timeout' => 10
  ]
];
$searchResponse = $client->search($searchParams);
print_r($searchResponse);
? >
Table 1. Variables
Variable Description
<USER NAME> Replace it with the username of your Alibaba Cloud Elasticsearch instance.
<PASSWORD> Replace it with the password of your Alibaba Cloud Elasticsearch instance.
<Host> Replace it with the public or internal network endpoint displayed on the View the basic information of a cluster page of your Alibaba Cloud Elasticsearch instance.

Python client

To test the connectivity to your Elasticsearch instance, connect the Python client to your instance through port 9200. The sample code is as follows. For more information, see elasticsearch-py.

from elasticsearch import Elasticsearch, RequestsHttpConnection
import certifi
es = Elasticsearch(
    ['<HOST>'],
    http_auth=('username', 'password'),
    port=9200,
    use_ssl=False
)
res = es.index(index="my_index", doc_type="my_type", id=1, body={"title": "One", "tags": ["ruby"]})
print(res['created'])
res = es.get(index="my_index", doc_type="my_type", id=1)
print(res['_source'])

Java client

Notice
  • The official Elasticsearch team no longer maintains the Transport client. We recommend that you do not use the Transport client to connect to Alibaba Cloud Elasticsearch. A NoNodeAvailableException error occurs when you use Transport client 5.5.3 to access Alibaba Cloud Elasticsearch. We recommend that you use the TransportClient V5.3.3 or Java low-level REST client to connect to Elasticsearch.
  • The Java REST client demo in this topic is compatible with Alibaba Cloud Elasticsearch V5.5.3. It is not compatible with Alibaba Cloud Elasticsearch V6.3.2. If the version of your Elasticsearch instance is V6.3.2, reference the official documentation Java REST client 6.3.2.
  • The version of the Java REST client must be the same as that of your Elasticsearch instance.

Before you use the Java REST client to connect to your Elasticsearch instance, perform the following tasks:

To test the connectivity to your Elasticsearch instance, connect the Java REST client to your instance through port 9200. The sample code is as follows.
import org.apache.http.HttpEntity;
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.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import java.io.IOException;
import java.util.Collections;
public class RestClientTest {
    public  static void main(String[]args){
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("<USER NAME>", "<PASSWORD>"));
        RestClient restClient = RestClient.builder(new HttpHost("<HOST>", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
        try {
            //index a document
            HttpEntity entity = new NStringEntity("{\n\"user\" : \"kimchy\"\n}", ContentType.APPLICATION_JSON);
            Response indexResponse = restClient.performRequest(
                    "PUT",
                    "/index/type/123",
                    Collections. <String, String>emptyMap(),
                    entity);
            //search a document
            Response response = restClient.performRequest("GET", "/index/type/123",
                    Collections.singletonMap("pretty", "true"));
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Table 2. Variables
Variable Description
<USER NAME> Replace it with the username of your Alibaba Cloud Elasticsearch instance.
<PASSWORD> Replace it with the password of your Alibaba Cloud Elasticsearch instance.
<HOST> Replace it with the public or internal network endpoint displayed on the Basic Information page of your Alibaba Cloud Elasticsearch instance.

For more information about sample code for clients in other languages, see HTTP/REST clients and security.

Go

Reference the following sample code if you use a Go client to connect to your Elasticsearch instance through port 9200.

Note Before you use a Go client to connect to Elasticsearch, perform the following tasks:
  • Install Go. For more information, see Official documentation. In the following sample code, Go 1.13.4 is used.
  • Create an Alibaba Cloud Elasticsearch instance. In this topic, the version of the Elasticsearch instance is V5.5.3.
package main

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

const (
    url      = "http://es-cn-xxxxxx.public.elasticsearch.aliyuncs.com:9200"     //<1>
    username = "elastic"        //<2>
    password = "password"       //<3>
)

func main() {
    var sniff = false    //<4>  
    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("index_test").Do(context.Background())   //<5>
    if err ! = nil {
        log.Println(err)
    }
    log.Println(exists)
}
Table 3. Variables
Variable Description
<1>: url Replace it with the endpoint of your Elasticsearch instance. You can find the endpoint information on the Basic Information page of your instance.
<2>: username Replace it with the username of your Elasticsearch instance. The default username is elastic.
<3>: password Replace it with the password of your Elasticsearch instance. The password is specified when you create the instance.
<4>: sniff Set the value to false to prevent sniffing on connections. If this feature is enabled, connection failures occur.
<5>: exists, err This parameter creates index index_test on your Elasticsearch instance, and returns log data that contains the connection information. Replace the index name with the actual name of your index.

If you are connected to your Elasticsearch instance, the following result is returned:

2019/11/29 10:07:37 true