The content of this page has been automatically translated by AI. If you encounter any problems while reading, you can view the corresponding content in Chinese.

Python SDK

Last updated: 2024-12-30 16:21:09
This article introduces how to use the Python SDK to send data to the Elasticsearch Serverless service.

Prerequisites

The Serverless space and index have been created. Obtain the Intranet Access Address, Username, Password, Index Name, and other information.
It is recommended to install the elasticsearch py library version 7.10.1 or above. The latest version can be installed as shown below:
pip3 install elasticsearch

Code demo

The following example code features writing to the Elasticsearch Serverless service through the Python SDK and performing a simple query.
from datetime import datetime, timezone
from elasticsearch import Elasticsearch, helpers

# create an elasticsearch client instance, provide http authentication information
es = Elasticsearch(
hosts=[
{
'host': 'space-12345678.ap-shanghai.qcloudes.com', # replace it with your intranet access address
'port': 80, # replace it with the port number of your intranet access address
'scheme': 'http', # specify the scheme here
}
],
http_auth=('elastic', 'xxxxxxxxxxx'), # replace it with your username and password
)

# Define the document to index
docs = [
{
'_index': 'my_index',
# '_id': i,
'_source': {
'author': 'user',
'text': 'Hi! Elasticsearch Serverless!',
'@timestamp': datetime.now(timezone.utc),
}
}
for i in range(10) # Create 10 documents
]

# Use bulk API to index documents
helpers.bulk(es, docs)

# Search documents, replace index with your index name, replace body with your query statement
res = es.search(index="my_index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
print("%(@timestamp)s %(author)s: %(text)s" % hit["_source"])