本文档为您介绍使用Elasticsearch的PHP、Python和Java客户端访问阿里云Elasticsearch的方法,并提供了示例代码和注意事项供您参考。

PHP语言

警告
  • Elasticsearch的PHP客户端提供的默认连接池并不适合云上环境。阿里云Elasticsearch提供了负载均衡的域名服务,因此PHP客户端访问程序必须使用SimpleConnectionPool作为连接池,否则在触发阿里云Elasticsearch重启操作时会出现访问连接异常影响您的业务。
  • 在PHP客户端访问程序已使用SimpleConnectionPool作为连接池后,不排除在触发Elasticsearch重启操作时还会出现访问连接异常问题(例如提示No enabled connection),因此PHP客户端访问程序必须要有访问连接失败重连机制。
通过PHP客户端访问阿里云Elasticsearch的9200端口进行测试,示例代码如下,详细信息请参见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);
?>
  • <USER NAME>:替换为访问阿里云Elasticsearch实例的用户名。
  • <PASSWORD>:替换为访问阿里云Elasticsearch实例的密码。
  • <HOST>:替换为阿里云Elasticsearch实例基本信息页面中的内网或外网地址。

Python语言

通过Python访问阿里云Elasticsearch的9200端口进行测试,示例代码如下,详细信息请参见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语言

注意
  • Elasticsearch官方已经不再维护TransportClient,不建议通过TransportClient来访问Elasticsearch,使用TransportClient 5.5.3版本在建立连接时会提示NoNodeAvailableException的问题。建议您使用Java Low Level REST Client来访问Elasticsearch。
  • 本文提供的Java REST Client示例主要适用于阿里云Elasticsearch 5.5.3版本,不兼容阿里云Elasticsearch 6.3.2版本。如果您的Elasticsearch实例是6.3.2版本,可参考Elasticsearch Java REST Client 6.3.2官方文档。
  • Java REST Client版本需要与Elasticsearch实例版本保持一致。
准备工作
通过Java REST Client访问阿里云Elasticsearch的9200端口进行测试,示例代码如下。
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();
        }
    }
}
  • <USER NAME>:替换为访问阿里云Elasticsearch实例的用户名。
  • <PASSWORD>:替换为访问阿里云Elasticsearch实例的密码。
  • <HOST>:替换为阿里云Elasticsearch实例基本信息页面中的内网或外网地址。

更多语言示例请参见HTTP/REST Clients and Security