使用 asyncio 与 Elasticsearch DSL
elasticsearch-dsl 包支持使用 asyncio 进行异步/等待。为了确保您拥有所有必要的依赖项,请安装 [async] 扩展
$ python -m pip install elasticsearch-dsl[async]
连接
使用 async_connections 模块来管理您的异步连接。
from elasticsearch_dsl import async_connections async_connections.create_connection(hosts=['localhost'], timeout=20)
connections 模块中提供的所有选项都可以在 async_connections 中使用。
如何避免退出时出现“未关闭的客户端会话/连接器”警告
这些警告来自 aiohttp 包,该包在 AsyncElasticsearch 客户端内部使用。当应用程序退出时,它们经常出现,这是因为在垃圾回收时 HTTP 连接处于打开状态。为了避免这些警告,请确保您关闭了连接。
es = async_connections.get_connection() await es.close()
搜索 DSL
使用 AsyncSearch 类执行异步搜索。
from elasticsearch_dsl import AsyncSearch s = AsyncSearch().query("match", title="python") async for hit in s: print(hit.title)
您可以显式调用 execute() 方法来获取 Response 对象,而不是将 AsyncSearch 对象用作异步迭代器。
s = AsyncSearch().query("match", title="python") response = await s.execute() for hit in response: print(hit.title)
还提供了一个 AsyncMultiSearch。
from elasticsearch_dsl import AsyncMultiSearch ms = AsyncMultiSearch(index='blogs') ms = ms.add(AsyncSearch().filter('term', tags='python')) ms = ms.add(AsyncSearch().filter('term', tags='elasticsearch')) responses = await ms.execute() for response in responses: print("Results for query %r." % response.search.query) for hit in response: print(hit.title)
异步文档、索引等
Document、Index、IndexTemplate、Mapping、UpdateByQuery 和 FacetedSearch 类都有异步版本,它们使用相同的名称,并在前面加上 Async 前缀。这些类公开了与同步版本相同的接口,但任何执行 I/O 的方法都定义为协程。
不执行 I/O 的辅助类没有异步版本。相同的类可以在同步和异步应用程序中使用。
在异步应用程序中使用 自定义分析器 时,请使用 async_simulate() 方法在其上调用 Analyze API。
有关每个特定方法的详细信息,请参阅 API 文档 部分。