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 and Create a serverless application.
-
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.
NoteBefore 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.
NoteThe 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 and Configure a public access whitelist for a serverless application.
Important-
If you connect from a Wi-Fi or broadband network, add your public IP address to the whitelist. We recommend that you visit cip.cc in a browser to check your public IP address.
-
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 timeouterror 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 and Configure a public access whitelist for a serverless application.
-
-
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
)
This section provides sample code for connecting to a serverless application using common clients.
-
Elasticsearch Serverless supports only index-related APIs. Operations on other APIs are not permitted.
-
The Python API for Elasticsearch Serverless is compatible with the index-level operations of the Python client for the community edition of Elasticsearch 7.10. For more information, see Elasticsearch API.
// The following sample code shows how to use BulkRequest for batch writing and SearchRequest.
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.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class RestClientTest710 {
public static void main(String[] args) {
// Alibaba Cloud Elasticsearch Serverless applications require basic authentication.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// Use the username and password that you configured when you created the Alibaba Cloud Elasticsearch serverless application. These 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 application endpoint, click the ID of your Elasticsearch serverless application 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 {
// Batch write
// Create a BulkRequest object and use the timeout() method to set the request timeout period to 10s.
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
// Create a request.
Map<String, Object> jsonMap = new HashMap<>();
// field_01 and field_02 are field names, and value_01 and value_02 are their values.
jsonMap.put("{field_01}", "{value_01}");
jsonMap.put("{field_02}", "{value_02}");
IndexRequest indexRequest = new IndexRequest("{index_name}").id("{doc_id}").source(jsonMap);
bulkRequest.add(indexRequest);
Map<String, Object> jsonMap2 = new HashMap<>();
jsonMap2.put("{field_01}", "{value_01}");
jsonMap2.put("{field_02}", "{value_02}");
IndexRequest indexRequest2 = new IndexRequest("{index_name}").id("{doc_id}").source(jsonMap2);
bulkRequest.add(indexRequest2);
BulkResponse bulkResponse = highClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());
// Query all documents.
// Specify the index to search.
SearchRequest searchRequest = new SearchRequest("{index_name}");
// Build a query object.
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// Create a query that matches all documents.
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// Set the query object as the source of SearchRequest.
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = highClient.search(searchRequest, RequestOptions.DEFAULT);
// Obtain the SearchHit[] searchHits array of the search results from SearchResponse.
SearchHit[] searchHits = searchResponse.getHits().getHits();
// Traverse the searchHits array to process each search hit. In this example, the getSourceAsString() method is used to print the source data of the document as a string.
for (SearchHit hit : searchHits) {
System.out.println(hit.getSourceAsString());
}
// Query a single document.
GetRequest getRequest = new GetRequest("{index_name}", "{doc_id}");
GetResponse getResponse = highClient.get(getRequest, RequestOptions.DEFAULT);
// Print the content of the document.
System.out.println(getResponse.getSourceAsString());
// The full response is returned, just as it would be from a command-line request.
System.out.println(getResponse);
highClient.close();
} catch (IOException ioException) {
// Handle exceptions.
}
}
}# coding="utf-8"
from elasticsearch import Elasticsearch
import time
import string
import random
def stru_doc(index_name,doc_type="_doc",count=100):
doc = []
for i in range(count):
_id = ''.join([random.choice(letters) for _ in range(17)])
i_doc = [{"create": {"_index": index_name, "_id": _id, "_type": doc_type}},
{"field1": "This is a test document for creating an index. It contains various text to simulate real-world data for search and analysis.",
"filed2": "By default, Cloud Assistant Agent is installed on ECS instances created from public images after December 1, 2017. If your instance was purchased before this date, you need to manually install the agent to use its features. The installation methods vary based on the operating system.",
"field3": "If you choose the default installation path, the client is installed in C:\\ProgramData\\aliyun\\assist\\ on a Windows instance.",
"filed4":"This topic provides a quick overview of the billing items, methods, components, and pricing for Elastic Compute Service (ECS).",
"filed5":"Note: The basic billing methods for ECS resources are subscription and pay-as-you-go. You can combine these with other cost-effective billing options to reduce costs. For more information, see Billing overview.",
"filed6":"The cat is out of the bag! We are proud to have been involved in the sale of the Ai.com domain. We look forward to seeing what they will do with it! On February 16, the AI chatbot ChatGPT became a global sensation. OpenAI, its developer, spent a fortune to redirect the premium domain AI.com to ChatGPT. As we all know, Microsoft is the major backer of OpenAI, and products like Bing are already testing ChatGPT. Microsoft also announced an expansion of its partnership with OpenAI, with the latter receiving a 'multi-year, multi-billion dollar' investment.",
"@timestamp": int(time.time())}]
doc += i_doc
return doc
def bulk_request():
"""
Continuously write data without creating an index.
:return:
"""
index_name = "ali_push_doc_%s" % time.strftime('%H%M%S')
body = {
"settings": {"number_of_replicas": 0,
"number_of_shards": 1}
}
doc_type = "_doc"
try:
create_index = es.indices.create(index=index_name, body=body)
print(create_index)
except Exception as index:
print(time.strftime('%H:%M:%s') + str(index))
time.sleep(20)
bulk_body = stru_doc(index_name)
try:
bulk_request = es.bulk(body=bulk_body, timeout='10s')
# print(time.strftime('%H:%M:%S') + 'push_test' + str(bulk_request))
except Exception as u:
print(u)
with open('push_doc_exception.txt', 'w') as f:
f.write(time.strftime('%H:%M:%S') + url + '\n' + str(u) + '\n' + str(bulk_body) + '\n')
es.indices.refresh()
doc_account = es.count(index=index_name)
print("indexcount:",doc_account)
if doc_account["count"] == 100:
for times in range(100):
try:
query_body = {
"query": {
"match_all": {}
}
}
search_request = es.search(query_body, index_name)
print(search_request)
except Exception as e:
with open('asyn_error.txt', 'a') as f:
f.write(time.strftime('%H:%M:%S') + str(e) + '\n' + str(e) + '\n')
else:
with open('asyn_error.txt', 'a') as f:
f.write(time.strftime('%H:%M:%S') + str(doc_account) + '\n')
if __name__ == '__main__':
url = <YourEsHost>
es = Elasticsearch(url, http_auth=(<UserName>, <YourPassword>))
letters = string.ascii_lowercase + string.digits
bulk_request()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, or the public endpoint of the serverless application. The endpoint is available on the Basic Information page of your cluster or application. |
|
<UserName> |
The username of the Alibaba Cloud Elasticsearch cluster is |
|
<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, and for a serverless application, it is in the Basic Information section of the application 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 |
|
<YourEsId> |
The document ID. |
|
<YourEsField> |
The field name. |
|
<YourEsFieldValue> |
The value for the specified field. |