一、前提条件
·已创建 serverless 空间及索引, 获取内网访问地址、用户名密码、索引名等信息。
·推荐安装 7.10.1 以上版本的 elasticsearch py 依赖库,可以安装最新版本,如下所示:
pip3 install elasticsearch
二、代码 demo
以下实例代码,功能为通过 Python SDK 写入 Elasticsearch Serverless 服务,并进行简单查询。
from datetime import datetime, timezonefrom elasticsearch import Elasticsearch, helpers# 创建一个Elasticsearch客户端实例,提供HTTP认证信息es = Elasticsearch( hosts=[ { 'host': 'space-12345678.ap-shanghai.qcloudes.com', # 替换为你的空间内网访问地址 'port': 80, # 替换为你的空间内网访问地址的端口号 'scheme': 'http', # 这里指定 scheme } ], http_auth=('elastic', 'xxxxxxxxxxx'), # 替换为你的空间用户名和密码)# 定义要索引的文档docs = [ { '_index': 'my_index', # '_id': i, '_source': { 'author': 'user', 'text': 'Hi! Elasticsearch Serverless!', '@timestamp': datetime.now(timezone.utc), } } for i in range(10) # 创建10个文档]# 使用bulk API索引文档helpers.bulk(es, docs)# 搜索文档, index替换为你的索引名称, body替换为你的查询语句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"])