查询
Python Elasticsearch 客户端提供了几种向 Elasticsearch 发送查询的方法。本文档详细解释了如何使用客户端构建和执行查询。本文档不涉及 DSL 模块。
Elasticsearch API 按命名空间分组。
- 有全局命名空间,包含 Search API (
GET _search
) 或 Index API (PUT /<target>/_doc/<_id>
和相关端点) 等 API。 - 然后是所有其他命名空间,例如
- Indices,包含 Create index API (
PUT /my-index
) 等 API, - ES|QL,包含 Run an ES|QL query API (
POST /_async
) 等 API, - 等等。
- Indices,包含 Create index API (
因此,当您知道需要哪个命名空间和函数时,即可调用该函数。假设 client
是一个 Elasticsearch 实例,下面是您调用上述示例的方法
- 全局命名空间:
client.search(...)
和client.index(...)
- 其他命名空间
- Indices:
client.indices.create(...)
- ES|QL:
client.esql.query(...)
- Indices:
如何确定命名空间?
- Elasticsearch API 文档可以提供帮助,尽管其使用的标签并非完全对应命名空间。
- 您还可以通过以下方式使用客户端文档:
- 浏览 Elasticsearch API 参考页面,或
- 使用 Read the Docs 搜索来查找您的端点,该搜索由 Elasticsearch 提供支持!
- 最后,对于 Elasticsearch 8.x,Elasticsearch 指南中的大多数示例也提供了 Python 版本。(对于 Elasticsearch 9.x,这项工作仍在进行中。)在下面的示例中,
client.ingest.put_pipeline(...)
是调用“创建或更新管道”API 的函数。
现在您知道要调用哪些函数了,下一步是参数。为避免歧义,Python Elasticsearch 客户端强制使用关键字参数。举例来说,我们看看 “创建索引”API。只有一个必需参数 index
,因此最简形式如下所示:
from elasticsearch import Elasticsearch
client = Elasticsearch("http://localhost:9200", api_key="...")
client.indices.create(index="my-index")
您还可以使用其他参数,包括第一级的正文参数,例如:
resp = client.indices.create(
index="logs",
aliases={"logs-alias": {}},
mappings={"name": {"type": "text"}},
)
print(resp)
在这种情况下,客户端将向 Elasticsearch 发送以下 JSON 正文:
PUT /logs
{
"aliases": {"logs-alias": {}},
"mappings": {"name": {"type": "text"}}
}
与其他客户端一样,Python Elasticsearch 客户端是根据 Elasticsearch 规范生成的。虽然我们努力保持其更新,但它并非(还不是!)完美,有时会缺少正文参数。在这种情况下,您可以直接指定正文,如下所示:
resp = client.indices.create(
index="logs",
body={
"aliases": {"logs-alias": {}},
"mappings": {"name": {"type": "text"}},
"missing_parameter": "foo",
}
)
print(resp)
如果缺少某个 API,您需要使用低级别的 perform_request
函数:
resp = client.perform_request(
"PUT",
"/logs"
index="logs",
headers={"content-type": "application/json", "accept": "application/json"},
body={
"aliases": {"logs-alias": {}},
"mappings": {"name": {"type": "text"}},
"missing_parameter": "foo",
}
)
print(resp)
此函数的一个好处是允许您使用任意标头,例如用于模拟用户的 es-security-runas-user
标头。
您可以使用 .options()
API 指定请求超时或重试等选项,详细信息请参阅配置页面。