
在使用 python 与 elasticsearch 交互时,elasticsearch-py 库提供了同步和异步两种客户端。对于构建高性能、非阻塞的 web 应用(如基于 fastapi、aiohttp 等框架的应用),使用 asyncelasticsearch 客户端进行异步操作是必不可少的。然而,当需要执行大量文档的索引、更新或删除操作时,逐个发送请求效率低下。elasticsearch 提供了 bulk api 来批量处理文档,这显著减少了网络往返次数,从而大幅提升了处理速度。
elasticsearch-py 库中的 elasticsearch.helpers.bulk 函数是实现批量操作的常用工具。但需要注意的是,这个函数是为同步客户端 Elasticsearch 设计的,它不接受 AsyncElasticsearch 实例作为其客户端参数。尝试将 AsyncElasticsearch 客户端传递给 helpers.bulk 将会导致类型错误或无法预期的行为。
为了在异步环境中实现批量操作,我们需要使用专门为 AsyncElasticsearch 设计的异步辅助函数。
elasticsearch-py 库为异步客户端提供了一套独立的辅助函数,其中就包括 elasticsearch.helpers.async_bulk。这个函数与同步版本的 helpers.bulk 功能相似,但它能够与 AsyncElasticsearch 客户端无缝协作,并在异步事件循环中执行批量操作。
async_bulk 函数的核心优势在于:
下面我们将通过一个具体的示例来演示如何使用 async_bulk 函数执行异步批量索引操作。
首先,确保您的环境中安装了 elasticsearch 库:
pip install elasticsearch
import asyncio
from elasticsearch import AsyncElasticsearch
from elasticsearch.helpers import async_bulk
async def perform_async_bulk_operations():
"""
演示如何使用 AsyncElasticsearch 和 async_bulk 执行异步批量操作。
"""
# 1. 初始化 AsyncElasticsearch 客户端
# 请根据您的实际 Elasticsearch 服务地址和认证信息进行配置。
# 例如:hosts=["http://localhost:9200"]
# 如果使用 Elastic Cloud,可以配置 cloud_id 和 api_key。
client = AsyncElasticsearch(
hosts=["http://localhost:9200"],
# api_key=("your_api_key_id", "your_api_key_secret"),
# cloud_id="your_cloud_id"
)
try:
# 确保客户端能够连接到 Elasticsearch
print("尝试连接到 Elasticsearch...")
info = await client.info()
print(f"成功连接到 Elasticsearch: 版本 {info['version']['number']}")
# 2. 准备批量操作数据
# 每个字典代表一个操作。
# 必须包含 "_index" 字段,指定目标索引。
# "_id" 字段是可选的,如果未提供,Elasticsearch 会自动生成。
# "_op_type" 字段可选,默认为 'index'。其他值可以是 'create', 'update', 'delete'。
documents_to_index = [
{
"_index": "my_async_tutorial_index",
"_id": f"doc_{i}",
"title": f"Async Document Title {i}",
"content": f"This is the detailed content for async document {i}.",
"timestamp": asyncio.run(client.info())['tagline'] # Just for fun, add a dynamic field
}
for i in range(1, 101) # 创建100个文档
]
# 3. 执行异步批量操作
# async_bulk 函数返回一个元组:(成功操作数量, 失败操作列表)
print(f"\n开始执行异步批量索引 {len(documents_to_index)} 个文档...")
success_count, failed_actions = await async_bulk(
client=client,
actions=documents_to_index,
chunk_size=50, # 每次发送50个文档到 Elasticsearch
raise_on_error=True, # 如果有任何单个文档操作失败,则抛出异常
# raise_on_exception=True # 如果在批量操作过程中发生任何异常(如网络问题),则抛出异常
)
print(f"\n异步批量操作结果:")
print(f"成功索引/更新了 {success_count} 个文档。")
if failed_actions:
print(f"以下 {len(failed_actions)} 个文档操作失败:")
for item in failed_actions:
print(f" - 失败项: {item}")
else:
print("所有文档均已成功处理。")
# 4. 验证部分数据(可选)
print("\n验证部分已索引的文档...")
for i in [1, 50, 100]:
doc_id = f"doc_{i}"
try:
response = await client.get(index="my_async_tutorial_index", id=doc_id)
print(f" 成功获取文档 {doc_id}: Title='{response['_source']['title']}'")
except Exception as e:
print(f" 获取文档 {doc_id} 失败: {e}")
# 5. 清理:删除索引(可选)
print("\n正在清理:删除索引 'my_async_tutorial_index'...")
try:
await client.indices.delete(index="my_async_tutorial_index", ignore=[404])
print("索引 'my_async_tutorial_index' 已删除。")
except Exception as e:
print(f"删除索引失败: {e}")
except Exception as e:
print(f"执行异步批量操作时发生错误: {e}")
finally:
# 6. 关闭客户端连接
print("\n关闭 Elasticsearch 客户端连接...")
await client.close()
print("Elasticsearch 客户端已关闭。")
if __name__ == "__main__":
# 运行异步函数
asyncio.run(perform_async_bulk_operations())客户端初始化:client = AsyncElasticsearch(...) 创建一个异步 Elasticsearch 客户端实例。请务必根据您的 Elasticsearch 环境配置 hosts、api_key 或 cloud_id。
数据准备 (actions 参数):async_bulk 的 actions 参数需要一个可迭代对象,其中每个元素都是一个字典,代表一个要执行的批量操作。
示例:不同操作类型的 actions 结构
# 索引或更新文档
{"_index": "my_index", "_id": "1", "field": "value"}
# 仅当不存在时创建文档
{"_index": "my_index", "_id": "2", "_op_type": "create", "field": "value"}
# 更新文档(局部更新)
{"_index": "my_index", "_id": "3", "_op_type": "update", "doc": {"field_to_update": "new_value"}}
# 删除文档
{"_index": "my_index", "_id": "4", "_op_type": "delete"}async_bulk 参数:
结果处理:async_bulk 返回一个元组 (success_count, failed_actions)。
资源管理: 在程序结束时,务必调用 await client.close() 来关闭 AsyncElasticsearch 客户端的连接池,释放资源。这通常在 finally 块中完成,以确保无论是否发生异常都能执行。
通过使用 elasticsearch.helpers.async_bulk,您可以高效、可靠地在 Python 异步应用程序中执行大规模的 Elasticsearch 批量操作。理解其工作原理和参数配置,可以帮助您构建出性能卓越且健壮的数据处理管道。记住,对于异步客户端 AsyncElasticsearch,始终使用其配套的异步辅助函数,以确保代码的兼容性和正确性。
以上就是AsyncElasticsearch 异步批量操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号