Elasticsearch Service Python SDK

通过 Python SDK 将数据投递到 Elasticsearch Serverless 服务中的相关操作。

相关产品
Elasticsearch Service 产品页,含版本规格、价格与购买入口。

一、前提条件

·已创建 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"])

赞 (0)
上一篇 4天前
下一篇 4天前