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, timezonefrom elasticsearch import Elasticsearch, helpers# create an elasticsearch client instance, provide http authentication informationes = 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 indexdocs = [{'_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 documentshelpers.bulk(es, docs)# Search documents, replace index with your index name, replace body with your query statementres = 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"])