Elasticsearch

class elasticsearch.Elasticsearch

Elasticsearch 低级客户端。提供从 Python 到 Elasticsearch REST API 的直接映射。

客户端实例具有额外属性以访问不同命名空间的 API,如 async_searchindicessecurity 等:

client = Elasticsearch("http://localhost:9200")

# 获取文档 API
client.get(index="*", id="1")

# 获取索引 API
client.indices.get(index="*")

传输选项可以在客户端构造函数或使用 options() 方法设置:

# 在构造函数中设置 'api_key'
client = Elasticsearch(
    "http://localhost:9200",
    api_key="api_key",
)
client.search(...)

# 为每个请求设置 'api_key'
client.options(api_key="api_key").search(...)
__init__(hosts=None, *, cloud_id=None, api_key=None, basic_auth=None, bearer_auth=None, opaque_id=None, headers=<DEFAULT>, connections_per_node=<DEFAULT>, http_compress=<DEFAULT>, verify_certs=<DEFAULT>, ca_certs=<DEFAULT>, client_cert=<DEFAULT>, client_key=<DEFAULT>, ssl_assert_hostname=<DEFAULT>, ssl_assert_fingerprint=<DEFAULT>, ssl_version=<DEFAULT>, ssl_context=<DEFAULT>, ssl_show_warn=<DEFAULT>, transport_class=<class 'elastic_transport.Transport'>, request_timeout=<DEFAULT>, node_class=<DEFAULT>, node_pool_class=<DEFAULT>, randomize_nodes_in_pool=<DEFAULT>, node_selector_class=<DEFAULT>, dead_node_backoff_factor=<DEFAULT>, max_dead_node_backoff=<DEFAULT>, serializer=None, serializers=<DEFAULT>, default_mimetype='application/json', max_retries=<DEFAULT>, retry_on_status=<DEFAULT>, retry_on_timeout=<DEFAULT>, sniff_on_start=<DEFAULT>, sniff_before_requests=<DEFAULT>, sniff_on_node_failure=<DEFAULT>, sniff_timeout=<DEFAULT>, min_delay_between_sniffing=<DEFAULT>, sniffed_node_callback=None, meta_header=<DEFAULT>, http_auth=<DEFAULT>, _transport=None)
Parameters:
Return type:

None

bulk(*, operations=None, body=None, index=None, error_trace=None, filter_path=None, human=None, include_source_on_error=None, list_executed_pipelines=None, pipeline=None, pretty=None, refresh=None, require_alias=None, require_data_stream=None, routing=None, source=None, source_excludes=None, source_includes=None, timeout=None, wait_for_active_shards=None)

批量索引或删除文档。 在单个请求中执行多个 indexcreatedeleteupdate 操作。 这减少了开销并可以显著提高索引速度。

如果启用了 Elasticsearch 安全功能,您必须对目标数据流、索引或索引别名拥有以下索引权限:

  • 使用 create 操作需要 create_doccreateindexwrite 索引权限。数据流仅支持 create 操作。
  • 使用 index 操作需要 createindexwrite 索引权限。
  • 使用 delete 操作需要 deletewrite 索引权限。
  • 使用 update 操作需要 indexwrite 索引权限。
  • 要通过批量 API 请求自动创建数据流或索引,需要 auto_configurecreate_indexmanage 索引权限。
  • 要使用 refresh 参数使批量操作结果对搜索可见,需要 maintenancemanage 索引权限。

自动数据流创建需要启用数据流的匹配索引模板。

操作在请求体中使用换行分隔的 JSON (NDJSON) 结构指定:

action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n

indexcreate 操作期望在下一行有源数据,其语义与标准索引 API 中的 op_type 参数相同。 如果目标中已存在相同 ID 的文档,create 操作会失败。 index 操作根据需要添加或替换文档。

注意:数据流仅支持 create 操作。 要更新或删除数据流中的文档,必须定位包含该文档的后备索引。

update 操作期望在下一行指定部分文档、upsert 及脚本及其选项。

delete 操作不期望在下一行有源数据,其语义与标准删除 API 相同。

注意:数据的最后一行必须以换行符 (\n) 结尾。 每个换行符前可以有回车符 (\r)。 向 _bulk 端点发送 NDJSON 数据时,使用 Content-Type 头为 application/jsonapplication/x-ndjson。 由于此格式使用字面换行符 (\n) 作为分隔符,请确保 JSON 操作和源数据没有美化打印。

如果在请求路径中提供目标,则用于未明确指定 _index 参数的任何操作。

关于格式的说明:这里的目的是使处理尽可能快。 由于某些操作被重定向到其他节点上的分片,接收节点端仅解析 action_meta_data

使用此协议的客户端库应尝试在客户端执行类似操作,并尽可能减少缓冲。

单个批量请求中没有“正确”的操作数量。 尝试不同的设置以找到适合您特定工作负载的最佳大小。 请注意,Elasticsearch 默认将 HTTP 请求的最大大小限制为 100mb,因此客户端必须确保没有请求超过此大小。 无法索引超过大小限制的单个文档,因此必须在发送到 Elasticsearch 之前将此类文档预处理为较小的部分。 例如,在索引之前将文档拆分为页面或章节,或将原始二进制数据存储在 Elasticsearch 之外的系统中,并在发送到 Elasticsearch 的文档中用指向外部系统的链接替换原始数据。

客户端对批量请求的支持

一些官方支持的客户端提供助手来帮助批量请求和重新索引:

  • Go:查看 esutil.BulkIndexer
  • Perl:查看 Search::Elasticsearch::Client::5_0::BulkSearch::Elasticsearch::Client::5_0::Scroll
  • Python:查看 elasticsearch.helpers.*
  • JavaScript:查看 client.helpers.*
  • .NET:查看 BulkAllObservable
  • PHP:查看批量索引。

使用 cURL 提交批量请求

如果向 curl 提供文本文件输入,必须使用 --data-binary 标志而不是普通的 -d。 后者不保留换行符。例如:

$ cat requests
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }
$ curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@requests"; echo
{"took":7, "errors": false, "items":[{"index":{"_index":"test","_id":"1","_version":1,"result":"created","forced_refresh":false}}]}

乐观并发控制

批量 API 调用中的每个 indexdelete 操作可以在其各自的操作和元数据行中包含 if_seq_noif_primary_term 参数。 if_seq_noif_primary_term 参数根据对现有文档的最后修改控制操作的执行方式。详情请参阅乐观并发控制。

版本控制

每个批量项可以使用 version 字段包含版本值。 它根据 _version 映射自动遵循索引或删除操作的行为。 它还支持 version_type

路由

每个批量项可以使用 routing 字段包含路由值。 它根据 _routing 映射自动遵循索引或删除操作的行为。

注意:数据流不支持自定义路由,除非在模板中启用了 allow_custom_routing 设置创建。

等待活动分片

进行批量调用时,可以设置 wait_for_active_shards 参数以要求在开始处理批量请求之前有最小数量的分片副本处于活动状态。

刷新

控制此请求所做的更改何时对搜索可见。

注意:只有接收批量请求的分片会受到刷新的影响。 想象一个包含三个文档的 _bulk?refresh=wait_for 请求,这些文档恰好路由到具有五个分片的索引中的不同分片。 请求将仅等待这三个分片刷新。 构成索引的其他两个分片根本不参与 _bulk 请求。

您可能希望暂时禁用刷新间隔以提高大型批量请求的索引吞吐量。 有关使用索引设置 API 的分步说明,请参阅链接文档。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-bulk

Parameters:
  • operations (Sequence[Mapping[str, Any]] | None)

  • index (str | None) – 执行批量操作的数据流、索引或索引别名的名称。

  • include_source_on_error (bool | None) – 在解析错误的情况下是否在错误消息中包含文档源(True 或 false)。

  • list_executed_pipelines (bool | None) – 如果为 true,响应将包括为每个索引或创建运行的摄取管道。

  • pipeline (str | None) – 用于预处理传入文档的管道标识符。 如果索引指定了默认摄取管道,将此值设置为 _none 将为此请求关闭默认摄取管道。 如果配置了最终管道,无论此参数的值如何,它都将始终运行。

  • refresh (bool | str | Literal['false', 'true', 'wait_for'] | None) – 如果为 true,Elasticsearch 刷新受影响的分片以使此操作对搜索可见。 如果为 wait_for,等待刷新以使此操作对搜索可见。 如果为 false,不进行任何刷新操作。 有效值:truefalsewait_for

  • require_alias (bool | None) – 如果为 true,请求的操作必须针对索引别名。

  • require_data_stream (bool | None) – 如果为 true,请求的操作必须针对数据流(现有的或要创建的)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 指示是否返回 _source 字段(truefalse)或包含要返回的字段列表。

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段的逗号分隔列表。 也可以使用此参数从 _source_includes 查询参数指定的子集中排除字段。 如果 _source 参数为 false,则忽略此参数。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。 如果指定此参数,则仅返回这些源字段。 可以使用 _source_excludes 查询参数从此子集中排除字段。 如果 _source 参数为 false,则忽略此参数。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 每个操作等待以下操作的时间段:自动索引创建、动态映射更新和等待活动分片。 默认为 `1m`(一分钟),保证 Elasticsearch 在失败前至少等待超时时间。 实际等待时间可能更长,特别是在发生多次等待时。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 必须处于活动状态才能继续操作的分片副本数量。 设置为 all 或任何正整数,最大为索引中的总分片数(number_of_replicas+1)。 默认为 1,等待每个主分片处于活动状态。

  • body (Sequence[Mapping[str, Any]] | None)

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

clear_scroll(*, error_trace=None, filter_path=None, human=None, pretty=None, scroll_id=None, body=None)

清除滚动搜索。 清除滚动搜索的搜索上下文和结果。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-clear-scroll

Parameters:
Return type:

ObjectApiResponse[Any]

close()

关闭 Transport 和所有内部连接

Return type:

None

close_point_in_time(*, id=None, error_trace=None, filter_path=None, human=None, pretty=None, body=None)

关闭时间点。 时间点在用于搜索请求之前必须显式打开。 keep_alive 参数告诉 Elasticsearch 应保持多长时间。 当 keep_alive 周期过去时,时间点会自动关闭。 然而,保持时间点有成本;一旦不再需要用于搜索请求,应尽快关闭它们。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-open-point-in-time

Parameters:
Return type:

ObjectApiResponse[Any]

count(*, index=None, allow_no_indices=None, analyze_wildcard=None, analyzer=None, default_operator=None, df=None, error_trace=None, expand_wildcards=None, filter_path=None, human=None, ignore_throttled=None, ignore_unavailable=None, lenient=None, min_score=None, preference=None, pretty=None, q=None, query=None, routing=None, terminate_after=None, body=None)

统计搜索结果数量。 获取匹配查询条件的文档数量。

查询条件可以通过简单查询字符串参数提供,也可以在请求体中定义 Query DSL。 查询是可选的。当未提供查询时,API 使用 match_all 来统计所有文档。

计数 API 支持多目标语法。您可以跨多个数据流和索引执行单个计数 API 搜索。

该操作会广播到所有分片。 对于每个分片 ID 组,选择一个副本并在其上运行搜索。 这意味着副本可以提高计数的可扩展性。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-count

Parameters:
  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和别名的逗号分隔列表。 支持通配符(*)。要搜索所有数据流和索引, 请省略此参数或使用`*`或`_all`。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、 索引别名或`_all`值仅指向缺失或关闭的索引时,请求将返回错误。 即使请求针对其他打开的索引,此行为也适用。例如, 针对`foo*,bar*`的请求如果存在以`foo`开头的索引但没有以`bar`开头的索引, 则会返回错误。

  • analyze_wildcard (bool | None) – 如果为`true`,则分析通配符和前缀查询。 此参数仅在指定`q`查询字符串参数时可用。

  • analyzer (str | None) – 用于查询字符串的分析器。此参数 仅在指定`q`查询字符串参数时可用。

  • default_operator (str | Literal['and', 'or'] | None) – 查询字符串查询的默认运算符:AND`或 `OR。此参数仅在指定`q`查询字符串参数时可用。

  • df (str | None) – 当查询字符串中未给出字段前缀时用作默认值的字段。 此参数仅在指定`q`查询字符串参数时可用。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。 如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏的数据流。 支持逗号分隔的值,例如`open,hidden`。

  • ignore_throttled (bool | None) – 如果为`true`,冻结时忽略具体、扩展或别名的索引。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求针对缺失或关闭的索引时返回错误。

  • lenient (bool | None) – 如果为`true`,查询字符串中基于格式的查询失败 (例如向数字字段提供文本)将被忽略。此参数仅在指定`q`查询字符串参数时可用。

  • min_score (float | None) – 文档必须具有的最低`_score`值才能包含在结果中。

  • preference (str | None) – 应执行操作的节点或分片。默认情况下是随机的。

  • q (str | None) – 使用 Lucene 查询字符串语法的查询。此参数不能与请求体一起使用。

  • query (Mapping[str, Any] | None) – 使用 Query DSL 定义搜索查询。请求体查询 不能与`q`查询字符串参数一起使用。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • terminate_after (int | None) – 为每个分片收集的最大文档数。 如果查询达到此限制,Elasticsearch 会提前终止查询。 Elasticsearch 在排序前收集文档。重要提示:谨慎使用。 Elasticsearch 将此参数应用于处理请求的每个分片。 在可能的情况下,让 Elasticsearch 自动执行提前终止。 避免为针对跨多个数据层具有后备索引的数据流的请求指定此参数。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

create(*, index, id, document=None, body=None, error_trace=None, filter_path=None, human=None, include_source_on_error=None, pipeline=None, pretty=None, refresh=None, require_alias=None, require_data_stream=None, routing=None, timeout=None, version=None, version_type=None, wait_for_active_shards=None)

在索引中创建新文档。

您可以使用/<target>/_doc//<target>/_create/<_id> API索引新的JSON文档 使用_create可确保仅在文档不存在时才进行索引。 当索引中已存在相同ID的文档时,将返回409响应。 要更新现有文档,必须使用/<target>/_doc/ API。

如果启用了Elasticsearch安全功能,您必须对目标数据流、索引或索引别名拥有以下索引权限:

  • 要使用PUT /<target>/_create/<_id>POST /<target>/_create/<_id>请求格式添加文档,必须拥有create_doccreateindexwrite索引权限。
  • 要通过此API请求自动创建数据流或索引,必须拥有auto_configurecreate_indexmanage索引权限。

自动创建数据流需要启用数据流的匹配索引模板。

自动创建数据流和索引

如果请求的目标不存在且匹配带有data_stream定义的索引模板,索引操作将自动创建数据流。

如果目标不存在且不匹配数据流模板,操作将自动创建索引并应用任何匹配的索引模板。

注意:Elasticsearch包含多个内置索引模板。为避免与这些模板命名冲突,请参阅索引模式文档。

如果不存在映射,索引操作会创建动态映射。 默认情况下,新字段和对象会根据需要自动添加到映射中。

自动索引创建由action.auto_create_index设置控制。 如果为true,则可以自动创建任何索引。 您可以修改此设置以明确允许或阻止匹配指定模式的索引自动创建,或将其设置为false以完全关闭自动索引创建。 指定逗号分隔的模式列表,或在每个模式前添加+-前缀以指示是否应允许或阻止。 指定列表时,默认行为是不允许。

注意:action.auto_create_index设置仅影响索引的自动创建。 它不影响数据流的创建。

路由

默认情况下,分片放置(即路由)通过文档ID值的哈希值控制。 为了更明确地控制,可以使用routing参数在每个操作基础上直接指定路由器使用的哈希函数的输入值。

设置显式映射时,还可以使用_routing字段指示索引操作从文档本身提取路由值。 这会带来(非常小的)额外文档解析开销。 如果定义了_routing映射并设置为必需,则在未提供或提取路由值时索引操作将失败。

注意:数据流不支持自定义路由,除非在模板中启用了allow_custom_routing设置创建。

分布式

索引操作根据其路由定向到主分片,并在包含该分片的实际节点上执行。 主分片完成操作后,如果需要,更新将分发到适用的副本。

活动分片

为了提高系统写入的弹性,可以配置索引操作在继续之前等待一定数量的活动分片副本。 如果所需数量的活动分片副本不可用,则写入操作必须等待并重试,直到所需分片副本启动或超时。 默认情况下,写入操作仅等待主分片变为活动状态(即wait_for_active_shards1)。 可以通过动态设置index.write.wait_for_active_shards在索引设置中覆盖此默认值。 要为每个操作更改此行为,请使用wait_for_active_shards request参数。

有效值为all或任何正整数,最大为索引中每个分片的配置副本总数(即number_of_replicas+1)。 指定负值或大于分片副本数的数字将引发错误。

例如,假设您有一个由节点A、B和C组成的集群,并创建了一个副本数设置为3的索引(导致4个分片副本,比节点数多一个副本)。 如果尝试索引操作,默认情况下操作将仅确保每个分片的主副本可用。 这意味着即使B和C宕机且A托管主分片副本,索引操作仍将继续,仅使用数据的一个副本。 如果在请求中将wait_for_active_shards设置为3(且所有三个节点都正常运行),则索引操作将在继续之前需要3个活动分片副本。 此要求应得到满足,因为集群中有3个活动节点,每个节点都持有分片的副本。 但是,如果将wait_for_active_shards设置为all(或在此情况下相同的4),则索引操作不会继续,因为索引中每个分片的所有4个副本并未都处于活动状态。 除非在集群中启动新节点以托管分片的第四个副本,否则操作将超时。

重要的是要注意,此设置大大减少了写入操作未写入所需数量分片副本的可能性,但并不能完全消除这种可能性,因为此检查发生在写入操作开始之前。 写入操作进行后,仍可能在任意数量的分片副本上复制失败,但在主分片上仍成功。 API响应的_shards部分显示复制成功和失败的分片副本数量。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-create

Parameters:
  • index (str) – 目标数据流或索引的名称。如果目标不存在且匹配带有`data_stream`定义的索引模板的名称或通配符(*)模式,此请求将创建数据流。如果目标不存在且不匹配数据流模板,此请求将创建索引。

  • id (str) – 文档的唯一标识符。要自动生成文档ID,请使用`POST /<target>/_doc/`请求格式。

  • document (Mapping[str, Any] | None)

  • include_source_on_error (bool | None) – 在解析错误的情况下是否在错误消息中包含文档源,true或false。

  • pipeline (str | None) – 用于预处理传入文档的管道ID。如果索引指定了默认摄取管道,将此值设置为`_none`将为此请求关闭默认摄取管道。如果配置了最终管道,无论此参数的值如何,它都将始终运行。

  • refresh (bool | str | Literal['false', 'true', 'wait_for'] | None) – 如果为`true`,Elasticsearch刷新受影响的分片以使此操作对搜索可见。如果为`wait_for`,则等待刷新以使此操作对搜索可见。如果为`false`,则不进行任何刷新操作。

  • require_alias (bool | None) – 如果为`true`,目标必须是索引别名。

  • require_data_stream (bool | None) – 如果为`true`,请求的操作必须针对数据流(现有的或要创建的)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 请求等待以下操作的超时时间:自动索引创建、动态映射更新、等待活动分片。Elasticsearch在失败前至少等待指定的超时时间。实际等待时间可能更长,特别是在发生多次等待时。此参数在分配执行操作的主分片在操作运行时可能不可用的情况下非常有用。可能的原因包括主分片当前正在从网关恢复或正在进行重新定位。默认情况下,操作将等待主分片变为可用至少1分钟,然后失败并返回错误。实际等待时间可能更长,特别是在发生多次等待时。

  • version (int | None) – 用于并发控制的显式版本号。必须为非负长整型数字。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 在继续操作之前必须处于活动状态的分片副本数量。可以设置为`all`或任何正整数,最大为索引中的分片总数(number_of_replicas+1)。默认值`1`表示等待每个主分片变为活动状态。

  • body (Mapping[str, Any] | None)

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

delete(*, index, id, error_trace=None, filter_path=None, human=None, if_primary_term=None, if_seq_no=None, pretty=None, refresh=None, routing=None, timeout=None, version=None, version_type=None, wait_for_active_shards=None)

删除文档。

从指定索引中移除一个JSON文档。

注意:不能直接向数据流发送删除请求。 要删除数据流中的文档,必须定位到包含该文档的后备索引。

乐观并发控制

删除操作可以设置为条件性执行,仅当文档的最后修改具有if_seq_noif_primary_term参数指定的序列号和主项时才会执行。 如果检测到不匹配,操作将导致VersionConflictException并返回状态码409

版本控制

每个被索引的文档都有版本号。 删除文档时可以指定版本号,确保实际删除的是目标文档且其间未被修改。 对文档执行的每个写入操作(包括删除)都会使其版本号递增。 已删除文档的版本号在删除后会短暂保留,以便控制并发操作。 保留时长由index.gc_deletes索引设置决定。

路由

如果索引时使用了路由,删除文档时也需要指定路由值。

_routing映射设为required但未指定路由值,删除API会抛出RoutingMissingException并拒绝请求。

例如:

DELETE /my-index-000001/_doc/1?routing=shard-1

该请求会删除ID为1的文档,但需基于用户路由。 若未指定正确路由值,文档不会被删除。

分布式

删除操作会被哈希到特定分片ID, 然后重定向到该ID组内的主分片,并(根据需要)复制到该ID组内的分片副本。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete

Parameters:
  • index (str) – 目标索引名称。

  • id (str) – 文档的唯一标识符。

  • if_primary_term (int | None) – 仅当文档具有此主项时才执行操作。

  • if_seq_no (int | None) – 仅当文档具有此序列号时才执行操作。

  • refresh (bool | str | Literal['false', 'true', 'wait_for'] | None) – 若为`true`,Elasticsearch会刷新受影响分片使操作对搜索可见;若为`wait_for`,则等待刷新;若为`false`,则不进行刷新操作。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待活跃分片的时长。当执行删除操作时主分片可能不可用(例如正在恢复或迁移中),此参数可设置等待时间,默认最多等待1分钟。

  • version (int | None) – 用于并发控制的显式版本号,必须与文档当前版本匹配才能使请求成功。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 执行操作前必须活跃的最小分片副本数,可设为`all`或不超过索引总分片数(number_of_replicas+1)的正整数,默认值`1`表示等待每个主分片活跃。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

delete_by_query(*, index, allow_no_indices=None, analyze_wildcard=None, analyzer=None, conflicts=None, default_operator=None, df=None, error_trace=None, expand_wildcards=None, filter_path=None, from_=None, human=None, ignore_unavailable=None, lenient=None, max_docs=None, preference=None, pretty=None, q=None, query=None, refresh=None, request_cache=None, requests_per_second=None, routing=None, scroll=None, scroll_size=None, search_timeout=None, search_type=None, slice=None, slices=None, sort=None, stats=None, terminate_after=None, timeout=None, version=None, wait_for_active_shards=None, wait_for_completion=None, body=None)

Delete documents.

Deletes documents that match the specified query.

If the Elasticsearch security features are enabled, you must have the following index privileges for the target data stream, index, or alias:

  • read
  • delete or write

You can specify the query criteria in the request URI or the request body using the same syntax as the search API. When you submit a delete by query request, Elasticsearch gets a snapshot of the data stream or index when it begins processing the request and deletes matching documents using internal versioning. If a document changes between the time that the snapshot is taken and the delete operation is processed, it results in a version conflict and the delete operation fails.

NOTE: Documents with a version equal to 0 cannot be deleted using delete by query because internal versioning does not support 0 as a valid version number.

While processing a delete by query request, Elasticsearch performs multiple search requests sequentially to find all of the matching documents to delete. A bulk delete request is performed for each batch of matching documents. If a search or bulk request is rejected, the requests are retried up to 10 times, with exponential back off. If the maximum retry limit is reached, processing halts and all failed requests are returned in the response. Any delete requests that completed successfully still stick, they are not rolled back.

You can opt to count version conflicts instead of halting and returning by setting conflicts to proceed. Note that if you opt to count version conflicts the operation could attempt to delete more documents from the source than max_docs until it has successfully deleted max_docs documents, or it has gone through every document in the source query.

Throttling delete requests

To control the rate at which delete by query issues batches of delete operations, you can set requests_per_second to any positive decimal number. This pads each batch with a wait time to throttle the rate. Set requests_per_second to -1 to disable throttling.

Throttling uses a wait time between batches so that the internal scroll requests can be given a timeout that takes the request padding into account. The padding time is the difference between the batch size divided by the requests_per_second and the time spent writing. By default the batch size is 1000, so if requests_per_second is set to 500:

target_time = 1000 / 500 per second = 2 seconds
wait_time = target_time - write_time = 2 seconds - .5 seconds = 1.5 seconds

Since the batch is issued as a single _bulk request, large batch sizes cause Elasticsearch to create many requests and wait before starting the next set. This is "bursty" instead of "smooth".

Slicing

Delete by query supports sliced scroll to parallelize the delete process. This can improve efficiency and provide a convenient way to break the request down into smaller parts.

Setting slices to auto lets Elasticsearch choose the number of slices to use. This setting will use one slice per shard, up to a certain limit. If there are multiple source data streams or indices, it will choose the number of slices based on the index or backing index with the smallest number of shards. Adding slices to the delete by query operation creates sub-requests which means it has some quirks:

  • You can see these requests in the tasks APIs. These sub-requests are "child" tasks of the task for the request with slices.
  • Fetching the status of the task for the request with slices only contains the status of completed slices.
  • These sub-requests are individually addressable for things like cancellation and rethrottling.
  • Rethrottling the request with slices will rethrottle the unfinished sub-request proportionally.
  • Canceling the request with slices will cancel each sub-request.
  • Due to the nature of slices each sub-request won't get a perfectly even portion of the documents. All documents will be addressed, but some slices may be larger than others. Expect larger slices to have a more even distribution.
  • Parameters like requests_per_second and max_docs on a request with slices are distributed proportionally to each sub-request. Combine that with the earlier point about distribution being uneven and you should conclude that using max_docs with slices might not result in exactly max_docs documents being deleted.
  • Each sub-request gets a slightly different snapshot of the source data stream or index though these are all taken at approximately the same time.

If you're slicing manually or otherwise tuning automatic slicing, keep in mind that:

  • Query performance is most efficient when the number of slices is equal to the number of shards in the index or backing index. If that number is large (for example, 500), choose a lower number as too many slices hurts performance. Setting slices higher than the number of shards generally does not improve efficiency and adds overhead.
  • Delete performance scales linearly across available resources with the number of slices.

Whether query or delete performance dominates the runtime depends on the documents being reindexed and cluster resources.

Cancel a delete by query operation

Any delete by query can be canceled using the task cancel API. For example:

POST _tasks/r1A2WoRbTwKZ516z6NEs5A:36619/_cancel

The task ID can be found by using the get tasks API.

Cancellation should happen quickly but might take a few seconds. The get task status API will continue to list the delete by query task until this task checks that it has been cancelled and terminates itself.

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete-by-query

Parameters:
  • index (str | Sequence[str]) – A comma-separated list of data streams, indices, and aliases to search. It supports wildcards (*). To search all data streams or indices, omit this parameter or use * or _all.

  • allow_no_indices (bool | None) – If false, the request returns an error if any wildcard expression, index alias, or _all value targets only missing or closed indices. This behavior applies even if the request targets other open indices. For example, a request targeting foo*,bar* returns an error if an index starts with foo but no index starts with bar.

  • analyze_wildcard (bool | None) – If true, wildcard and prefix queries are analyzed. This parameter can be used only when the q query string parameter is specified.

  • analyzer (str | None) – Analyzer to use for the query string. This parameter can be used only when the q query string parameter is specified.

  • conflicts (str | Literal['abort', 'proceed'] | None) – What to do if delete by query hits version conflicts: abort or proceed.

  • default_operator (str | Literal['and', 'or'] | None) – The default operator for query string query: AND or OR. This parameter can be used only when the q query string parameter is specified.

  • df (str | None) – The field to use as default where no field prefix is given in the query string. This parameter can be used only when the q query string parameter is specified.

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – The type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. It supports comma-separated values, such as open,hidden.

  • from – Skips the specified number of documents.

  • ignore_unavailable (bool | None) – If false, the request returns an error if it targets a missing or closed index.

  • lenient (bool | None) – If true, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. This parameter can be used only when the q query string parameter is specified.

  • max_docs (int | None) – The maximum number of documents to delete.

  • preference (str | None) – The node or shard the operation should be performed on. It is random by default.

  • q (str | None) – A query in the Lucene query string syntax.

  • query (Mapping[str, Any] | None) – The documents to delete specified with Query DSL.

  • refresh (bool | None) – If true, Elasticsearch refreshes all shards involved in the delete by query after the request completes. This is different than the delete API’s refresh parameter, which causes just the shard that received the delete request to be refreshed. Unlike the delete API, it does not support wait_for.

  • request_cache (bool | None) – If true, the request cache is used for this request. Defaults to the index-level setting.

  • requests_per_second (float | None) – The throttle for this request in sub-requests per second.

  • routing (str | None) – A custom value used to route operations to a specific shard.

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – The period to retain the search context for scrolling.

  • scroll_size (int | None) – The size of the scroll request that powers the operation.

  • search_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – The explicit timeout for each search request. It defaults to no timeout.

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – The type of the search operation. Available options include query_then_fetch and dfs_query_then_fetch.

  • slice (Mapping[str, Any] | None) – Slice the request manually using the provided slice ID and total number of slices.

  • slices (int | str | Literal['auto'] | None) – The number of slices this task should be divided into.

  • sort (Sequence[str] | None) – A comma-separated list of <field>:<direction> pairs.

  • stats (Sequence[str] | None) – The specific tag of the request for logging and statistical purposes.

  • terminate_after (int | None) – The maximum number of documents to collect for each shard. If a query reaches this limit, Elasticsearch terminates the query early. Elasticsearch collects documents before sorting. Use with caution. Elasticsearch applies this parameter to each shard handling the request. When possible, let Elasticsearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indices across multiple data tiers.

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – The period each deletion request waits for active shards.

  • version (bool | None) – If true, returns the document version as part of a hit.

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (number_of_replicas+1). The timeout value controls how long each write request waits for unavailable shards to become available.

  • wait_for_completion (bool | None) – If true, the request blocks until the operation is complete. If false, Elasticsearch performs some preflight checks, launches the request, and returns a task you can use to cancel or get the status of the task. Elasticsearch creates a record of this task as a document at .tasks/task/${taskId}. When you are done with a task, you should delete the task document so Elasticsearch can reclaim the space.

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • from_ (int | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

delete_by_query_rethrottle(*, task_id, error_trace=None, filter_path=None, human=None, pretty=None, requests_per_second=None)

限制按查询删除操作的速率。

调整特定按查询删除操作的每秒请求数。 加速查询的重新限速会立即生效,而减速查询的重新限速会在当前批次完成后生效,以防止滚动超时。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete-by-query-rethrottle

Parameters:
  • task_id (str) – 任务ID。

  • requests_per_second (float | None) – 该请求的限速值,单位为每秒子请求数。 要禁用限速,请设置为`-1`。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

delete_script(*, id, error_trace=None, filter_path=None, human=None, master_timeout=None, pretty=None, timeout=None)

删除脚本或搜索模板。 删除存储的脚本或搜索模板。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete-script

Parameters:
  • id (str) – 存储脚本或搜索模板的标识符。

  • master_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待连接主节点的时间。 如果在超时前未收到响应,请求将失败 并返回错误。也可以设置为 -1 表示请求 永不超时。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待响应的时间。如果在超时前 未收到响应,请求将失败并返回错误。也可以 设置为 -1 表示请求永不超时。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

exists(*, index, id, error_trace=None, filter_path=None, human=None, preference=None, pretty=None, realtime=None, refresh=None, routing=None, source=None, source_excludes=None, source_includes=None, stored_fields=None, version=None, version_type=None)

检查文档。

验证文档是否存在。 例如,检查是否存在 `_id` 为 0 的文档:

HEAD my-index-000001/_doc/0

如果文档存在,API 返回状态码 `200 - OK`。 如果文档不存在,API 返回 `404 - Not Found`。

版本控制支持

可以使用 `version` 参数仅在文档当前版本等于指定版本时进行检查。

在内部,Elasticsearch 已将旧文档标记为删除并添加全新文档。 旧版本文档不会立即消失,尽管您无法访问它。 Elasticsearch 会在后台清理已删除文档,同时您继续索引更多数据。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get

Parameters:
  • index (str) – 数据流、索引和别名的逗号分隔列表。 支持通配符 (*)。

  • id (str) – 唯一文档标识符。

  • preference (str | None) – 应执行操作的节点或分片。 默认情况下,操作在分片副本之间随机执行。如果 设置为 _local,操作将尽可能在本地分配的分片上运行。 如果设置为自定义值,该值用于保证相同的分片将用于相同的自定义值。 这有助于在不同刷新状态下命中不同分片时避免”跳跃值”。 示例值可以是 Web 会话 ID 或用户名等。

  • realtime (bool | None) – 如果为 true,请求是实时的而非近实时。

  • refresh (bool | None) – 如果为 true,请求在检索文档前刷新相关分片。 设置为 true 应经过仔细考虑和验证,确保不会对系统造成重负载 (并减慢索引速度)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 指示是否返回 _source 字段 (truefalse) 或列出要返回的字段。

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段的逗号分隔列表。 也可以使用此参数排除 _source_includes 查询参数中指定的子集中的字段。 如果 _source 参数为 false,则忽略此参数。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。 如果指定此参数,则仅返回这些源字段。 可以使用 _source_excludes 查询参数从此子集中排除字段。 如果 _source 参数为 false,则忽略此参数。

  • stored_fields (str | Sequence[str] | None) – 作为命中结果一部分返回的存储字段的逗号分隔列表。 如果未指定字段,则响应中不包含存储字段。 如果指定此字段,_source 参数默认为 false

  • version (int | None) – 并发控制的显式版本号。 指定版本必须与文档当前版本匹配才能使请求成功。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

HeadApiResponse

exists_source(*, index, id, error_trace=None, filter_path=None, human=None, preference=None, pretty=None, realtime=None, refresh=None, routing=None, source=None, source_excludes=None, source_includes=None, version=None, version_type=None)

检查文档源。

检查文档源是否存在于索引中。 例如:

HEAD my-index-000001/_source/1

如果在映射中禁用了文档源,则无法获取文档源。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get

Parameters:
  • index (str) – 数据流、索引和别名的逗号分隔列表。 支持通配符 (*)。

  • id (str) – 文档的唯一标识符。

  • preference (str | None) – 应执行操作的节点或分片。 默认情况下,操作在分片副本之间随机执行。

  • realtime (bool | None) – 如果为 true,请求是实时的而非近实时。

  • refresh (bool | None) – 如果为 true,请求在检索文档前刷新相关分片。 设置为 true 应经过仔细考虑和验证,确保不会对系统造成重负载 (并减慢索引速度)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 指示是否返回 _source 字段 (truefalse) 或列出要返回的字段。

  • source_excludes (str | Sequence[str] | None) – 要在响应中排除的源字段的逗号分隔列表。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。

  • version (int | None) – 并发控制的版本号。 必须与文档当前版本匹配才能使请求成功。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

HeadApiResponse

explain(*, index, id, analyze_wildcard=None, analyzer=None, default_operator=None, df=None, error_trace=None, filter_path=None, human=None, lenient=None, preference=None, pretty=None, q=None, query=None, routing=None, source=None, source_excludes=None, source_includes=None, stored_fields=None, body=None)

解释文档匹配结果。 获取关于特定文档为何匹配或不匹配查询的信息。 它计算查询和特定文档的分数解释。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-explain

Parameters:
  • index (str) – 用于限制请求的索引名称。 只能向此参数提供单个索引名称。

  • id (str) – 文档标识符。

  • analyze_wildcard (bool | None) – 如果为 true,分析通配符和前缀查询。 此参数仅在指定 q 查询字符串参数时可用。

  • analyzer (str | None) – 用于查询字符串的分析器。 此参数仅在指定 q 查询字符串参数时可用。

  • default_operator (str | Literal['and', 'or'] | None) – 查询字符串查询的默认运算符:ANDOR。此参数仅在指定 q 查询字符串参数时可用。

  • df (str | None) – 当查询字符串中未给出字段前缀时用作默认的字段。 此参数仅在指定 q 查询字符串参数时可用。

  • lenient (bool | None) – 如果为 true,将忽略查询字符串中基于格式的查询失败 (例如向数字字段提供文本)。此参数仅在指定 q 查询字符串参数时可用。

  • preference (str | None) – 应执行操作的节点或分片。 默认为随机。

  • q (str | None) – Lucene 查询字符串语法中的查询。

  • query (Mapping[str, Any] | None) – 使用 Query DSL 定义搜索定义。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – Truefalse 表示是否返回 _source 字段或要返回的字段列表。

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段的逗号分隔列表。 也可以使用此参数排除 _source_includes 查询参数中指定的子集中的字段。 如果 _source 参数为 false,则忽略此参数。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。 如果指定此参数,则仅返回这些源字段。 可以使用 _source_excludes 查询参数从此子集中排除字段。 如果 _source 参数为 false,则忽略此参数。

  • stored_fields (str | Sequence[str] | None) – 要在响应中返回的存储字段的逗号分隔列表。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

field_caps(*, index=None, allow_no_indices=None, error_trace=None, expand_wildcards=None, fields=None, filter_path=None, filters=None, human=None, ignore_unavailable=None, include_empty_fields=None, include_unmapped=None, index_filter=None, pretty=None, runtime_mappings=None, types=None, body=None)

获取字段能力。

获取多个索引中字段的能力信息。

对于数据流,API 返回流支持索引中的字段能力。 它像其他字段一样返回运行时字段。 例如,类型为 keyword 的运行时字段与属于 `keyword` 族的任何其他字段一样返回。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-field-caps

Parameters:
  • index (str | Sequence[str] | None) – 用于限制请求的数据流、索引和别名的逗号分隔列表。 支持通配符 (*)。要针对所有数据流和索引,省略此参数或使用 * 或 _all。

  • allow_no_indices (bool | None) – 如果为 false,如果任何通配符表达式、索引别名或 _all 值 仅针对缺失或关闭的索引,请求将返回错误。 即使请求针对其他打开的索引,此行为也适用。 例如,针对 foo*,bar* 的请求如果存在以 foo 开头的索引但没有以 bar 开头的索引,则返回错误。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。 如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏的数据流。 支持逗号分隔的值,例如 open,hidden

  • fields (str | Sequence[str] | None) – 要检索能力的字段列表。支持通配符 (*) 表达式。

  • filters (str | None) – 应用于响应的过滤器逗号分隔列表。

  • ignore_unavailable (bool | None) – 如果为 true,缺失或关闭的索引不包括在响应中。

  • include_empty_fields (bool | None) – 如果为 false,空字段不包括在响应中。

  • include_unmapped (bool | None) – 如果为 true,未映射的字段包括在响应中。

  • index_filter (Mapping[str, Any] | None) – 如果提供的查询在每个分片上重写为 match_none,则过滤索引。 重要:过滤是基于最佳努力的,它使用索引统计和映射将查询重写为 match_none 而不是完全运行请求。例如,日期字段上的范围查询如果分片中的所有文档 (包括已删除文档) 都在提供范围之外,则可以重写为 match_none。 但是,并非所有查询都可以重写为 match_none,因此即使提供的过滤器不匹配任何文档, 此 API 也可能返回索引。

  • runtime_mappings (Mapping[str, Mapping[str, Any]] | None) – 在请求中定义临时运行时字段,类似于在搜索请求中的方式。 这些字段仅作为查询的一部分存在,并优先于索引映射中定义的相同名称字段。

  • types (Sequence[str] | None) – 要包含的字段类型的逗号分隔列表。 不匹配这些类型的任何字段将从结果中排除。 默认为空,表示返回所有字段类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

get(*, index, id, error_trace=None, filter_path=None, force_synthetic_source=None, human=None, preference=None, pretty=None, realtime=None, refresh=None, routing=None, source=None, source_exclude_vectors=None, source_excludes=None, source_includes=None, stored_fields=None, version=None, version_type=None)

通过ID获取文档。

从索引中获取文档及其源或存储字段。

默认情况下,此API是实时的,不受索引刷新率的影响(数据何时对搜索可见)。 在使用stored_fields参数请求存储字段且文档已更新但尚未刷新的情况下,API将需要解析和分析源以提取存储字段。 要关闭实时行为,请将realtime参数设置为false。

源过滤

默认情况下,除非您使用了stored_fields参数或_source字段已关闭,否则API会返回_source字段的内容。 您可以使用_source参数关闭_source检索:

GET my-index-000001/_doc/0?_source=false

如果只需要_source中的一个或两个字段,请使用_source_includes_source_excludes参数来包含或过滤特定字段。 这对于大型文档非常有用,部分检索可以节省网络开销。 这两个参数都接受逗号分隔的字段列表或通配符表达式。 例如:

GET my-index-000001/_doc/0?_source_includes=*.id&_source_excludes=entities

如果只想指定包含字段,可以使用更短的表示法:

GET my-index-000001/_doc/0?_source=*.id

路由

如果在索引期间使用了路由,检索文档时也需要指定路由值。 例如:

GET my-index-000001/_doc/2?routing=user1

此请求获取ID为2的文档,但它是基于用户路由的。 如果未指定正确的路由,则不会获取文档。

分布式

GET操作被哈希到特定的分片ID。 然后重定向到该分片ID内的一个副本并返回结果。 副本是该分片ID组内的主分片及其副本。 这意味着副本越多,GET操作的扩展性越好。

版本支持

您可以使用version参数仅在文档的当前版本等于指定版本时检索文档。

在内部,Elasticsearch已将旧文档标记为已删除并添加了一个全新的文档。 旧版本的文档不会立即消失,尽管您无法访问它。 随着您继续索引更多数据,Elasticsearch会在后台清理已删除的文档。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get

Parameters:
  • index (str) – 包含文档的索引名称。

  • id (str) – 唯一的文档标识符。

  • force_synthetic_source (bool | None) – 指示请求是否强制使用合成<code>_source</code>。 使用此参数测试映射是否支持合成<code>_source</code>并了解最坏情况下的性能。 启用此参数的获取操作将比在索引中本地启用合成源慢。

  • preference (str | None) – 应在其上执行操作的节点或分片。 默认情况下,操作在分片副本之间随机化。 如果设置为<code>_local</code>,操作将尽可能在本地分配的分片上运行。 如果设置为自定义值,该值用于保证相同的分片将用于相同的自定义值。 这有助于在不同刷新状态下命中不同分片时的”跳跃值”问题。 示例值可以是Web会话ID或用户名。

  • realtime (bool | None) – 如果为<code>true</code>,请求是实时的而不是近实时的。

  • refresh (bool | None) – 如果为<code>true</code>,请求在检索文档之前刷新相关分片。 将其设置为<code>true</code>应经过仔细考虑和验证,确保不会对系统造成重负载(并减慢索引速度)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 指示是否返回<code>_source</code>字段(<code>true</code>或<code>false</code>)或列出要返回的字段。

  • source_exclude_vectors (bool | None) – 是否应从_source中排除向量

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段的逗号分隔列表。 您还可以使用此参数从<code>_source_includes</code>查询参数指定的子集中排除字段。 如果<code>_source</code>参数为<code>false</code>,则忽略此参数。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。 如果指定了此参数,则仅返回这些源字段。 您可以使用<code>_source_excludes</code>查询参数从此子集中排除字段。 如果<code>_source</code>参数为<code>false</code>,则忽略此参数。

  • stored_fields (str | Sequence[str] | None) – 作为命中一部分返回的存储字段的逗号分隔列表。 如果未指定字段,则响应中不包含存储字段。 如果指定了此字段,则<code>_source</code>参数默认为<code>false</code>。 只有叶字段可以通过<code>stored_fields</code>选项检索。 无法返回对象字段;如果指定,请求将失败。

  • version (int | None) – 用于并发控制的版本号。 它必须与文档的当前版本匹配才能使请求成功。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

get_script(*, id, error_trace=None, filter_path=None, human=None, master_timeout=None, pretty=None)

获取脚本或搜索模板。 检索存储的脚本或搜索模板。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get-script

Parameters:
  • id (str) – 存储的脚本或搜索模板的标识符。

  • master_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待主节点的期限。 如果在超时到期之前主节点不可用,请求将失败并返回错误。 也可以设置为<code>-1</code>以指示请求不应超时。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

get_script_context(*, error_trace=None, filter_path=None, human=None, pretty=None)

获取脚本上下文。

获取支持的脚本上下文及其方法的列表。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get-script-context

Parameters:
Return type:

ObjectApiResponse[Any]

get_script_languages(*, error_trace=None, filter_path=None, human=None, pretty=None)

获取脚本语言。

获取可用的脚本类型、语言和上下文的列表。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get-script-languages

Parameters:
Return type:

ObjectApiResponse[Any]

get_source(*, index, id, error_trace=None, filter_path=None, human=None, preference=None, pretty=None, realtime=None, refresh=None, routing=None, source=None, source_excludes=None, source_includes=None, version=None, version_type=None)

获取文档的源。

获取文档的源。 例如:

GET my-index-000001/_source/1

您可以使用源过滤参数控制返回_source的哪些部分:

GET my-index-000001/_source/1/?_source_includes=*.id&_source_excludes=entities

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-get

Parameters:
  • index (str) – 包含文档的索引名称。

  • id (str) – 唯一的文档标识符。

  • preference (str | None) – 应在其上执行操作的节点或分片。 默认情况下,操作在分片副本之间随机化。

  • realtime (bool | None) – 如果为<code>true</code>,请求是实时的而不是近实时的。

  • refresh (bool | None) – 如果为<code>true</code>,请求在检索文档之前刷新相关分片。 将其设置为<code>true</code>应经过仔细考虑和验证,确保不会对系统造成重负载(并减慢索引速度)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 指示是否返回<code>_source</code>字段(<code>true</code>或<code>false</code>)或列出要返回的字段。

  • source_excludes (str | Sequence[str] | None) – 要在响应中排除的源字段的逗号分隔列表。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。

  • version (int | None) – 用于并发控制的版本号。 它必须与文档的当前版本匹配才能使请求成功。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

health_report(*, feature=None, error_trace=None, filter_path=None, human=None, pretty=None, size=None, timeout=None, verbose=None)

获取集群健康状态。 获取Elasticsearch集群健康状态的报告。 该报告包含构成Elasticsearch功能的指标列表。

每个指标的健康状态分为:绿色、未知、黄色或红色。 指标会提供解释和元数据,说明当前健康状态的原因。

集群状态由最差的指标状态决定。

当某个指标状态非绿色时,指标结果中可能会包含影响列表,详细说明受健康问题负面影响的功能。 每个影响都带有严重级别、受影响的系统区域以及对系统影响的简要描述。

部分健康指标可以确定健康问题的根本原因,并提供一系列可执行的步骤来改善系统健康状况。 根本原因和修复步骤封装在诊断信息中。 诊断信息包含详细说明根本原因分析的成因、简要描述修复步骤的操作、受影响资源列表(如适用)以及修复诊断问题的详细分步故障排除指南。

注意:健康指标会对非绿色健康状态执行根本原因分析。频繁调用时可能产生较高的计算开销。 当设置API自动轮询健康状态时,将verbose设为false可禁用开销较大的分析逻辑。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-health-report

Parameters:
  • feature (str | Sequence[str] | None) – 集群功能,由顶层健康报告API返回。

  • size (int | None) – 限制健康报告API返回的受影响资源数量。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 显式操作超时时间。

  • verbose (bool | None) – 选择获取更多系统健康信息。</p>

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

index(*, index, document=None, body=None, id=None, error_trace=None, filter_path=None, human=None, if_primary_term=None, if_seq_no=None, include_source_on_error=None, op_type=None, pipeline=None, pretty=None, refresh=None, require_alias=None, require_data_stream=None, routing=None, timeout=None, version=None, version_type=None, wait_for_active_shards=None)

在索引中创建或更新文档。

将JSON文档添加到指定的数据流或索引中使其可被搜索。 如果目标是索引且文档已存在,请求会更新文档并增加其版本号。

注意:不能使用此API发送针对数据流中现有文档的更新请求。

如果启用了Elasticsearch安全功能,必须对目标数据流、索引或索引别名拥有以下索引权限:

  • 使用PUT /<target>/_doc/<_id>请求格式添加或覆盖文档时,必须拥有createindexwrite索引权限。
  • 使用POST /<target>/_doc/请求格式添加文档时,必须拥有create_doccreateindexwrite索引权限。
  • 要通过此API请求自动创建数据流或索引,必须拥有auto_configurecreate_indexmanage索引权限。

自动创建数据流需要启用数据流的匹配索引模板。

注意:索引操作成功返回时,副本分片可能尚未全部启动。 默认情况下只需主分片可用。可通过设置wait_for_active_shards改变此默认行为。

自动创建数据流和索引

如果请求目标不存在且匹配带有data_stream定义的索引模板,索引操作会自动创建数据流。

如果目标不存在且不匹配数据流模板,操作会自动创建索引并应用任何匹配的索引模板。

注意:Elasticsearch包含多个内置索引模板。为避免命名冲突,请参考索引模式文档。

如果不存在映射,索引操作会创建动态映射。 默认情况下,新字段和对象会根据需要自动添加到映射中。

自动索引创建由action.auto_create_index设置控制。 若为true,可自动创建任何索引。 可修改此设置以显式允许/阻止匹配指定模式的索引自动创建,或设为false完全关闭自动创建。 指定逗号分隔的模式列表,或在每个模式前添加+-表示允许/阻止。 指定列表时,默认行为是禁止。

注意:action.auto_create_index设置仅影响索引的自动创建,不影响数据流的创建。

乐观并发控制

索引操作可设置为条件操作,仅当文档的最后修改具有if_seq_noif_primary_term参数指定的序列号和主项时才会执行。 若检测到不匹配,操作将导致VersionConflictException409状态码。

路由

默认情况下,分片位置(路由)由文档ID值的哈希控制。 如需更精确控制,可通过routing参数直接指定用于路由器的哈希函数输入值。

设置显式映射时,也可使用_routing字段指示索引操作从文档本身提取路由值。 这会带来(极小的)额外文档解析开销。 如果定义了_routing映射并设为必需,当未提供或提取到路由值时索引操作将失败。

注意:数据流不支持自定义路由,除非创建时在模板中启用了allow_custom_routing设置。

分布式

索引操作根据路由定向到主分片,并在包含该分片的实际节点上执行。 主分片完成操作后,如有需要,更新会分发到适用的副本。

活动分片

为提高系统写入弹性,可配置索引操作等待特定数量的活动分片副本后再继续。 如果所需活动分片副本不可用,写入操作必须等待并重试,直到副本启动或超时。 默认情况下,写入操作仅等待主分片活动(即wait_for_active_shards1)。 可通过动态设置index.write.wait_for_active_shards覆盖此默认值。 要为每个操作改变此行为,使用wait_for_active_shards request参数。

有效值为all或任何正整数,最大为索引中每个分片的配置副本总数(即number_of_replicas+1)。 指定负值或大于分片副本数的值会引发错误。

例如,假设有A、B、C三个节点的集群,创建索引时副本数设为3(产生4个分片副本,比节点数多1)。 执行索引操作时,默认仅确保每个分片的主副本可用。 这意味着即使B、C宕机且A托管主分片副本,索引操作仍会继续(仅有一份数据副本)。 如果在请求中将wait_for_active_shards设为3(且三个节点都正常),索引操作会等待3个活动分片副本。 此要求应被满足,因为集群中有3个活动节点各持有一个分片副本。 但如果设为all(或本例中的4),索引操作不会继续,因为并非所有4个分片副本都活动。 除非新节点加入集群托管第四个分片副本,否则操作将超时。

需注意此设置虽大幅降低写入操作未达到所需分片副本数的概率,但无法完全消除可能性,因为检查发生在写入操作开始前。 写入过程中,仍可能在任何数量的分片副本上复制失败但在主分片上成功。 API响应的_shards部分会显示复制成功和失败的分片副本数。

空操作(noop)更新

使用此API更新文档时,即使文档未更改也会创建新版本。 如需避免,应使用_update API并将detect_noop设为true。 此API不提供detect_noop选项,因为它不获取旧源且无法与新源比较。

没有明确规则规定何时不接受空操作更新。 这取决于诸多因素,如数据源发送空操作更新的频率,以及Elasticsearch在接收更新的分片上每秒运行的查询数。

版本控制

每个索引文档都有版本号。 默认使用内部版本控制,从1开始随每次更新(包括删除)递增。 也可选择将版本号设为外部值(例如在数据库中维护)。 要启用此功能,应将version_type设为external。 提供的值必须是大于等于0的数字长整型,且小于约9.2e+18

注意:版本控制完全实时,不受搜索操作近实时特性影响。 如未提供版本号,操作将在无版本检查的情况下运行。

使用外部版本类型时,系统检查传递给索引请求的版本号是否大于当前存储文档的版本。 若为真,则索引文档并使用新版本号。 如提供的值小于等于存储文档的版本号,将发生版本冲突导致索引操作失败。例如:

PUT my-index-000001/_doc/1?version=2&version_type=external
{
  "user": {
    "id": "elkbee"
  }
}

此例中操作会成功,因为提供的版本2高于当前文档版本1。
如果文档已更新且版本设为2或更高,索引命令将失败并导致冲突(409 HTTP状态码)。

一个良好副作用是:只要使用来自源数据库的版本号,就无需严格排序因源数据库变更而运行的异步索引操作。
即使简单的使用数据库数据更新Elasticsearch索引的情况,若使用外部版本控制也会简化,因为当索引操作乱序到达时只会使用最新版本。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-create

Parameters:
  • index (str) – 目标数据流或索引的名称。如果目标不存在且匹配带有<code>data_stream</code>定义的索引模板的名称或通配符(<code>*</code>)模式,此请求会创建数据流。 如果目标不存在且不匹配数据流模板,此请求会创建索引。可通过resolve index API检查现有目标。

  • document (Mapping[str, Any] | None)

  • id (str | None) – 文档的唯一标识符。要自动生成文档ID,使用<code>POST /<target>/_doc/</code>请求格式并省略此参数。

  • if_primary_term (int | None) – 仅当文档具有此主项时才执行操作。

  • if_seq_no (int | None) – 仅当文档具有此序列号时才执行操作。

  • include_source_on_error (bool | None) – 解析错误时是否在错误消息中包含文档源(true/false)。

  • op_type (str | Literal['create', 'index'] | None) – 设为<code>create</code>时仅当文档不存在时才索引(缺席时放入)。如果指定<code>_id</code>的文档已存在,索引操作将失败。 行为与使用<code><index>/_create</code>端点相同。如指定文档ID,此参数默认为<code>index</code>,否则默认为<code>create</code>。 如果请求目标是数据流,则需要<code>create</code>的<code>op_type</code>。

  • pipeline (str | None) – 用于预处理传入文档的管道ID。如果索引指定了默认摄取管道, 将此值设为<code>_none</code>可禁用此请求的默认摄取管道。如果配置了最终管道, 无论此参数值如何,它始终会运行。

  • refresh (bool | str | Literal['false', 'true', 'wait_for'] | None) – 如果<code>true</code>,Elasticsearch刷新受影响分片使此操作对搜索可见。 如果<code>wait_for</code>,则等待刷新使操作对搜索可见。如果<code>false</code>,不执行刷新操作。

  • require_alias (bool | None) – 如果<code>true</code>,目标必须是索引别名。

  • require_data_stream (bool | None) – 如果<code>true</code>,请求操作必须针对数据流(现有或待创建)。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 请求等待以下操作的时长:自动索引创建、动态映射更新、等待活动分片。 当分配执行操作的主分片在操作运行时可能不可用时,此参数非常有用。 可能原因包括主分片正在从网关恢复或正在迁移。默认情况下, 操作将等待主分片变为可用至少1分钟,然后失败并返回错误。实际等待时间可能更长, 特别是在发生多次等待时。

  • version (int | None) – 用于并发控制的显式版本号。必须是非负长整型数字。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 操作继续前必须活动的分片副本数。可设为<code>all</code>或任何正整数, 最大为索引中分片总数(<code>number_of_replicas+1</code>)。 默认值<code>1</code>表示等待每个主分片活动。

  • body (Mapping[str, Any] | None)

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

info(*, error_trace=None, filter_path=None, human=None, pretty=None)

获取集群信息。 获取基本的构建、版本和集群信息。 ::: 在Serverless环境中,此API仅保留用于向后兼容。某些响应字段(如版本号)应被忽略。

https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-info

Parameters:
Return type:

ObjectApiResponse[Any]

mget(*, index=None, docs=None, error_trace=None, filter_path=None, force_synthetic_source=None, human=None, ids=None, preference=None, pretty=None, realtime=None, refresh=None, routing=None, source=None, source_excludes=None, source_includes=None, stored_fields=None, body=None)

获取多个文档。

通过ID从一个或多个索引中获取多个JSON文档。 如果在请求URI中指定了索引,则只需在请求体中指定文档ID。 为确保快速响应,如果部分分片失败,此多获取(mget)API会返回部分结果。

过滤源字段

默认情况下,每个文档都会返回_source字段(如果已存储)。 使用_source_source_includesource_exclude属性来过滤特定文档返回的字段。 可以在请求URI中包含_source_source_includes_source_excludes查询参数,以指定在没有每个文档指令时使用的默认值。

获取存储字段

使用stored_fields属性指定要检索的存储字段集。 任何未存储的请求字段将被忽略。 可以在请求URI中包含stored_fields查询参数,以指定在没有每个文档指令时使用的默认值。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-mget

Parameters:
  • index (str | None) – 当指定`ids`时或`docs`数组中的文档未指定索引时,从中检索文档的索引名称。

  • docs (Sequence[Mapping[str, Any]] | None) – 要检索的文档。如果请求URI中未指定索引,则此参数必填。

  • force_synthetic_source (bool | None) – 是否强制使用合成_source? 用于测试映射是否支持合成_source并了解最坏情况下的性能。 启用此选项的获取操作会比在索引中本地启用合成源更慢。

  • ids (str | Sequence[str] | None) – 要检索的文档ID。当请求URI中指定了索引时允许使用。

  • preference (str | None) – 指定操作应在哪个节点或分片上执行。默认为随机。

  • realtime (bool | None) – 如果为`true`,请求是实时的而非近实时的。

  • refresh (bool | None) – 如果为`true`,请求在检索文档前会刷新相关分片。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • source (bool | str | Sequence[str] | None) – 是否返回`_source`字段(true或false),或要返回的字段列表。

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段逗号分隔列表。 也可以使用此参数从`_source_includes`查询参数指定的子集中排除字段。

  • source_includes (str | Sequence[str] | None) – 要包含在响应中的源字段逗号分隔列表。 如果指定此参数,则仅返回这些源字段。 可以使用`_source_excludes`查询参数从此子集中排除字段。 如果`_source`参数为`false`,则忽略此参数。

  • stored_fields (str | Sequence[str] | None) – 如果为`true`,则检索存储在索引中的文档字段而非文档`_source`。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

msearch(*, searches=None, body=None, index=None, allow_no_indices=None, ccs_minimize_roundtrips=None, error_trace=None, expand_wildcards=None, filter_path=None, human=None, ignore_throttled=None, ignore_unavailable=None, include_named_queries_score=None, max_concurrent_searches=None, max_concurrent_shard_requests=None, pre_filter_shard_size=None, pretty=None, rest_total_hits_as_int=None, routing=None, search_type=None, typed_keys=None)

执行多个搜索。

请求格式类似于批量API格式,并使用换行分隔的JSON(NDJSON)格式。 结构如下:

header\n
body\n
header\n
body\n

该结构专门优化以减少解析,如果特定搜索最终重定向到另一个节点。

重要:数据的最后一行必须以换行符\n结尾。 每个换行符前面可以有一个回车符\r。 当向此端点发送请求时,Content-Type标头应设置为application/x-ndjson

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-msearch

Parameters:
  • searches (Sequence[Mapping[str, Any]] | None)

  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和索引别名的逗号分隔列表。

  • allow_no_indices (bool | None) – 如果为false,则当任何通配符表达式、索引别名或_all值仅针对缺失或关闭的索引时,请求返回错误。 即使请求针对其他打开的索引,此行为也适用。例如,针对foo*,bar*的请求如果存在以foo开头的索引但没有以bar开头的索引,则返回错误。

  • ccs_minimize_roundtrips (bool | None) – 如果为true,则跨集群搜索请求中协调节点与远程集群之间的网络往返次数最小化。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符表达式可以匹配的索引类型。如果请求可以针对数据流,则此参数确定通配符表达式是否匹配隐藏的数据流。

  • ignore_throttled (bool | None) – 如果为true,则在冻结时忽略具体、扩展或别名的索引。

  • ignore_unavailable (bool | None) – 如果为true,则响应中不包含缺失或关闭的索引。

  • include_named_queries_score (bool | None) – 指示hit.matched_queries是否应呈现为包含与分数关联的匹配查询名称的映射(true)或包含匹配查询名称的数组(false)。 此功能在搜索响应中的每个命中上重新运行每个命名查询。通常,这会给请求增加少量开销。但是,在大量命中上使用计算成本高的命名查询可能会增加显著开销。

  • max_concurrent_searches (int | None) – 多搜索API可以执行的最大并发搜索数。默认为`max(1, (# of data nodes * min(search thread pool size, 10)))`。

  • max_concurrent_shard_requests (int | None) – 每个子搜索请求在每个节点上执行的并发分片请求的最大数量。

  • pre_filter_shard_size (int | None) – 定义一个阈值,如果搜索请求扩展到的分片数超过该阈值,则强制执行预过滤往返以基于查询重写预过滤搜索分片。 如果分片基于其重写方法无法匹配任何文档(例如,如果日期过滤器是必需的但分片边界与查询不相交),则此过滤往返可以显著限制分片数量。

  • rest_total_hits_as_int (bool | None) – 如果为true,则hits.total在响应中作为整数返回。默认为false,返回一个对象。

  • routing (str | None) – 用于将搜索操作路由到特定分片的自定义路由值。

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – 指示在评分返回文档时是否应使用全局术语和文档频率。

  • typed_keys (bool | None) – 指定聚合和建议器名称是否应在响应中以其各自类型为前缀。

  • body (Sequence[Mapping[str, Any]] | None)

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

msearch_template(*, search_templates=None, body=None, index=None, ccs_minimize_roundtrips=None, error_trace=None, filter_path=None, human=None, max_concurrent_searches=None, pretty=None, rest_total_hits_as_int=None, search_type=None, typed_keys=None)

运行多个模板化搜索。

通过单个请求运行多个模板化搜索。 如果向curl提供文本文件或文本输入,请使用--data-binary标志而非-d以保留换行符。 例如:

$ cat requests
{ "index": "my-index" }
{ "id": "my-search-template", "params": { "query_string": "hello world", "from": 0, "size": 10 }}
{ "index": "my-other-index" }
{ "id": "my-other-search-template", "params": { "query_type": "match_all" }}

$ curl -H "Content-Type: application/x-ndjson" -XGET localhost:9200/_msearch/template --data-binary "@requests"; echo

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-msearch-template

Parameters:
  • search_templates (Sequence[Mapping[str, Any]] | None)

  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和别名的逗号分隔列表。 支持通配符(*)。要搜索所有数据流和索引,请省略此参数或使用`*`。

  • ccs_minimize_roundtrips (bool | None) – 如果为`true`,跨集群搜索请求将最小化网络往返次数。

  • max_concurrent_searches (int | None) – API可以运行的最大并发搜索数。

  • rest_total_hits_as_int (bool | None) – 如果为`true`,响应将`hits.total`返回为整数。 如果为`false`,则返回为对象。

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – 搜索操作的类型。

  • typed_keys (bool | None) – 如果为`true`,响应会为聚合和建议器名称添加各自类型的前缀。

  • body (Sequence[Mapping[str, Any]] | None)

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

mtermvectors(*, index=None, docs=None, error_trace=None, field_statistics=None, fields=None, filter_path=None, human=None, ids=None, offsets=None, payloads=None, positions=None, preference=None, pretty=None, realtime=None, routing=None, term_statistics=None, version=None, version_type=None, body=None)

获取多个词条向量。

通过单个请求获取多个词条向量。 您可以通过索引和ID指定现有文档,或在请求体中提供人工文档。 您可以在请求体或请求URI中指定索引。 响应包含一个docs数组,其中包含所有获取的词条向量。 每个元素都具有termvectors API提供的结构。

人工文档

您还可以使用mtermvectors为请求体中提供的人工文档生成词条向量。 使用的映射由指定的_index决定。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-mtermvectors

Parameters:
  • index (str | None) – 包含文档的索引名称。

  • docs (Sequence[Mapping[str, Any]] | None) – 现有或人工文档的数组。

  • field_statistics (bool | None) – 如果为`true`,响应包含文档计数、 文档频率总和和总词条频率总和。

  • fields (str | Sequence[str] | None) – 要包含在统计中的字段的逗号分隔列表或通配符表达式。 除非在`completion_fields`或`fielddata_fields`参数中提供了特定字段列表, 否则它用作默认列表。

  • ids (Sequence[str] | None) – 如果文档在同一索引中,则通过其ID指定文档的简化语法。

  • offsets (bool | None) – 如果为`true`,响应包含词条偏移量。

  • payloads (bool | None) – 如果为`true`,响应包含词条负载。

  • positions (bool | None) – 如果为`true`,响应包含词条位置。

  • preference (str | None) – 应在其上执行操作的节点或分片。 默认为随机。

  • realtime (bool | None) – 如果为true,请求是实时的而非近实时的。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • term_statistics (bool | None) – 如果为true,响应包含词条频率和文档频率。

  • version (int | None) – 如果为`true`,返回作为命中一部分的文档版本。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

open_point_in_time(*, index, keep_alive, allow_partial_search_results=None, error_trace=None, expand_wildcards=None, filter_path=None, human=None, ignore_unavailable=None, index_filter=None, max_concurrent_shard_requests=None, preference=None, pretty=None, routing=None, body=None)

打开时间点。

默认情况下,搜索请求针对目标索引的最新可见数据运行,这称为时间点。 Elasticsearch pit(时间点)是数据状态的轻量级视图,反映其初始化时的状态。 在某些情况下,最好使用相同的时间点执行多个搜索请求。 例如,如果在search_after请求之间发生刷新, 那么这些请求的结果可能不一致,因为搜索之间发生的变化仅对更新的时间点可见。

时间点必须在搜索请求中使用前显式打开。

带有pit参数的后续搜索请求不得指定indexroutingpreference值, 因为这些参数是从时间点复制的。

与常规搜索一样,您可以使用fromsize分页浏览时间点搜索结果,最多可达前10,000个命中。 如果要检索更多命中,请将PIT与search_after一起使用。

重要提示:打开时间点请求和每个后续搜索请求可能返回不同的标识符; 始终使用最近接收到的ID进行下一个搜索请求。

当搜索请求中使用包含分片故障的PIT时,缺失的分片始终会在搜索响应中报告为NoShardAvailableActionException异常。 要消除这些异常,需要创建一个新的PIT,以便可以处理先前PIT中缺失的分片,假设它们在此期间变得可用。

保持时间点存活

传递给打开时间点请求和搜索请求的keep_alive参数延长了相应时间点的生存时间。 该值不需要足够长来处理所有数据——只需足够长以处理下一个请求。

通常,后台合并过程通过将较小的段合并在一起创建新的较大段来优化索引。 一旦不再需要较小的段,它们就会被删除。 但是,打开的时间点会阻止旧段被删除,因为它们仍在使用中。

提示:保持旧段存活意味着需要更多的磁盘空间和文件句柄。 确保您已配置节点具有足够的空闲文件句柄。

此外,如果段包含已删除或更新的文档,则时间点必须跟踪段中的每个文档在初始搜索请求时是否处于活动状态。 如果您在正在进行删除或更新的索引上有许多打开的时间点,请确保您的节点具有足够的堆空间。 请注意,时间点不会阻止其关联的索引被删除。 您可以使用节点统计API检查有多少时间点(即搜索上下文)是打开的。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-open-point-in-time

Parameters:
  • index (str | Sequence[str]) – 要打开时间点的索引名称的逗号分隔列表; 使用`_all`或空字符串对所有索引执行操作

  • keep_alive (str | Literal[-1] | ~typing.Literal[0]) – 延长时间点持续的时间长度。

  • allow_partial_search_results (bool | None) – 指示时间点在最初创建PIT时是否容忍不可用的分片或分片故障。 如果为`false`,当分片缺失或不可用时创建时间点请求将抛出异常。 如果为`true`,时间点将包含请求时可用的所有分片。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。 如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏的数据流。 它支持逗号分隔的值,例如`open,hidden`。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求针对缺失或关闭的索引时返回错误。

  • index_filter (Mapping[str, Any] | None) – 如果提供的查询在每个分片上重写为`match_none`,则过滤索引。

  • max_concurrent_shard_requests (int | None) – 每个子搜索请求在每个节点上执行的最大并发分片请求数。

  • preference (str | None) – 应在其上执行操作的节点或分片。 默认情况下是随机的。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

ping(*, error_trace=None, filter_path=None, human=None, pretty=None)

如果 info() API 返回成功响应则返回 True,否则返回 False。此 API 调用可能在传输层失败(由于连接错误或超时)或由于非 2XX HTTP 响应(由于认证或授权问题)。

若想了解请求失败原因,应使用 info() API。

https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

Parameters:
Return type:

bool

put_script(*, id, script=None, context=None, error_trace=None, filter_path=None, human=None, master_timeout=None, pretty=None, timeout=None, body=None)

创建或更新脚本或搜索模板。 创建或更新存储的脚本或搜索模板。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-put-script

Parameters:
  • id (str) – 存储的脚本或搜索模板的标识符。 它在集群中必须是唯一的。

  • script (Mapping[str, Any] | None) – 脚本或搜索模板、其参数及其语言。

  • context (str | None) – 脚本或搜索模板应运行的上下文。 为防止错误,API会立即在此上下文中编译脚本或模板。

  • master_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待连接到主节点的超时时间。 如果在超时到期前未收到响应,请求将失败并返回错误。 也可以设置为`-1`表示请求永不过期。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待响应的超时时间。 如果在超时到期前未收到响应,请求将失败并返回错误。 也可以设置为`-1`表示请求永不过期。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

rank_eval(*, requests=None, index=None, allow_no_indices=None, error_trace=None, expand_wildcards=None, filter_path=None, human=None, ignore_unavailable=None, metric=None, pretty=None, search_type=None, body=None)

评估排名搜索结果。

评估一组典型搜索查询的排名搜索结果质量。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-rank-eval

Parameters:
  • requests (Sequence[Mapping[str, Any]] | None) – 一组典型的搜索请求及其提供的评级。

  • index (str | Sequence[str] | None) – 用于限制请求的数据流、索引和索引别名的逗号分隔列表。 支持通配符(*)表达式。要针对集群中的所有数据流和索引, 请省略此参数或使用`_all`或`*`。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、索引别名或`_all`值 仅针对缺失或关闭的索引时,请求返回错误。 即使请求针对其他打开的索引,此行为也适用。 例如,针对`foo*,bar*`的请求如果存在以`foo`开头的索引但不存在以`bar`开头的索引, 则会返回错误。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 是否将通配符表达式扩展为打开、关闭或两者兼有的具体索引。

  • ignore_unavailable (bool | None) – 如果为`true`,缺失或关闭的索引不包含在响应中。

  • metric (Mapping[str, Any] | None) – 要计算的评估指标的定义。

  • search_type (str | None) – 搜索操作类型

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

reindex(*, dest=None, source=None, conflicts=None, error_trace=None, filter_path=None, human=None, max_docs=None, pretty=None, refresh=None, requests_per_second=None, require_alias=None, script=None, scroll=None, size=None, slices=None, timeout=None, wait_for_active_shards=None, wait_for_completion=None, body=None)

重新索引文档。

将文档从源索引复制到目标索引。 您可以将所有文档复制到目标索引,或仅重新索引文档的子集。 源可以是任何现有索引、别名或数据流。 目标必须与源不同。 例如,您不能将数据流重新索引到其自身。

重要提示:重新索引要求源中所有文档都启用_source字段。 在调用重新索引API前应预先配置好目标索引。 重新索引不会复制源的设置或关联模板。 例如映射、分片数和副本数等必须提前配置。

如果启用了Elasticsearch安全功能,您必须拥有以下安全权限:

  • 对源数据流、索引或别名的read索引权限
  • 对目标数据流、索引或索引别名的write索引权限
  • 要通过重新索引API请求自动创建数据流或索引,必须对目标数据流、索引或别名拥有auto_configurecreate_indexmanage索引权限
  • 如果从远程集群重新索引,source.remote.user必须拥有monitor集群权限和对源数据流、索引或别名的read索引权限

如果从远程集群重新索引,必须在reindex.remote.whitelist设置中显式允许远程主机。 自动数据流创建需要启用数据流的匹配索引模板。

dest元素可以像索引API一样配置以控制乐观并发控制。 省略version_type或设置为internal会导致Elasticsearch盲目地将文档转储到目标中,覆盖任何具有相同ID的文档。

version_type设置为external会导致Elasticsearch保留源中的version,创建缺失的文档,并更新目标中版本比源中旧的文档。

op_type设置为create会导致重新索引API仅在目标中创建缺失文档。 所有现有文档都会导致版本冲突。

重要提示:由于数据流是仅追加的,任何对目标数据流的重新索引请求都必须将op_type设为create。 重新索引只能向目标数据流添加新文档。 它不能更新目标数据流中的现有文档。

默认情况下,版本冲突会中止重新索引过程。 要在存在冲突时继续重新索引,请将conflicts请求体属性设置为proceed。 在这种情况下,响应将包含遇到的版本冲突计数。 请注意,其他错误类型的处理不受conflicts属性的影响。 此外,如果选择计数版本冲突,操作可能会尝试从源重新索引超过max_docs的文档,直到成功将max_docs文档索引到目标或遍历完源查询中的所有文档。

有关如何重新索引文档的示例,请参阅链接文档。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-reindex

Parameters:
  • dest (Mapping[str, Any] | None) – 要复制到的目标

  • source (Mapping[str, Any] | None) – 要复制自的源

  • conflicts (str | Literal['abort', 'proceed'] | None) – 指示在存在冲突时是否继续重新索引

  • max_docs (int | None) – 要重新索引的最大文档数。默认重新索引所有文档。如果值小于或等于`scroll_size`,则不会使用滚动来检索操作结果。如果`conflicts`设为`proceed`,重新索引操作可能会尝试从源重新索引超过`max_docs`的文档,直到成功将`max_docs`文档索引到目标或遍历完源查询中的所有文档

  • refresh (bool | None) – 如果为`true`,请求会刷新受影响的分片以使此操作对搜索可见

  • requests_per_second (float | None) – 此请求的节流值,单位为每秒子请求数。默认无节流

  • require_alias (bool | None) – 如果为`true`,目标必须是索引别名

  • script (Mapping[str, Any] | None) – 重新索引时用于更新文档源或元数据的脚本

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – 为滚动搜索维护索引一致视图的时间段

  • size (int | None)

  • slices (int | str | Literal['auto'] | None) – 此任务应划分的切片数。默认为一个切片,表示任务不分割为子任务。重新索引支持切片滚动以并行化重新索引过程。这种并行化可以提高效率,并提供将请求分解为较小部分的便捷方式。注意:从远程集群重新索引不支持手动或自动切片。如果设为`auto`,Elasticsearch会选择使用的切片数。此设置将为每个分片使用一个切片,最多达到某个限制。如果有多个源,它将基于分片数最少的索引或后备索引选择切片数

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 每次索引等待自动索引创建、动态映射更新和等待活动分片的时长。默认Elasticsearch在失败前至少等待一分钟。实际等待时间可能更长,特别是在多次等待发生时

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 操作前必须激活的分片副本数。可设为`all`或任何不超过索引总分片数(number_of_replicas+1)的正整数。默认值为一,表示等待每个主分片激活

  • wait_for_completion (bool | None) – 如果为`true`,请求会阻塞直到操作完成

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

reindex_rethrottle(*, task_id, error_trace=None, filter_path=None, human=None, pretty=None, requests_per_second=None)

节流重新索引操作。

更改特定重新索引操作的每秒请求数。 例如:

POST _reindex/r1A2WoRbTwKZ516z6NEs5A:36619/_rethrottle?requests_per_second=-1

加速查询的重新节流会立即生效。 减速查询的重新节流将在完成当前批次后生效。 此行为可防止滚动超时。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-reindex

Parameters:
  • task_id (str) – 任务标识符,可通过tasks API找到

  • requests_per_second (float | None) – 此请求的节流值,单位为每秒子请求数。可以是`-1`关闭节流,或如`1.7`或`12`等十进制数节流到该级别

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

render_search_template(*, id=None, error_trace=None, file=None, filter_path=None, human=None, params=None, pretty=None, source=None, body=None)

渲染搜索模板。

将搜索模板渲染为搜索请求体。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-render-search-template

Parameters:
  • id (str | None) – 要渲染的搜索模板ID。如果未指定`source`,则需要此参数或`id`请求体参数

  • file (str | None)

  • params (Mapping[str, Any] | None) – 用于替换模板中Mustache变量的键值对。键是变量名,值是变量值

  • source (str | Mapping[str, Any] | None) – 内联搜索模板。支持与搜索API请求体相同的参数。这些参数也支持Mustache变量。如果未指定`id`或`<templated-id>`,则需要此参数

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

scripts_painless_execute(*, context=None, context_setup=None, error_trace=None, filter_path=None, human=None, pretty=None, script=None, body=None)

运行脚本。

运行脚本并返回结果。 使用此API构建和测试脚本,例如为运行时字段定义脚本时。 此API依赖极少,在您没有集群文档写入权限时特别有用。

API使用多个上下文,这些上下文控制脚本运行方式、运行时可用的变量以及返回类型。

每个上下文都需要脚本,但附加参数取决于您为该脚本使用的上下文。

https://www.elastic.co/docs/reference/scripting-languages/painless/painless-api-examples

Parameters:
  • context (str | Literal['boolean_field', 'composite_field', 'date_field', 'double_field', 'filter', 'geo_point_field', 'ip_field', 'keyword_field', 'long_field', 'painless_test', 'score'] | None) – 脚本应运行的上下文。注意:字段上下文中的结果顺序不保证

  • context_setup (Mapping[str, Any] | None) – context`的附加参数。注意:除`painless_test`外所有上下文都需要此参数,如果未提供`context`值则默认为`painless_test

  • script (Mapping[str, Any] | None) – 要运行的Painless脚本

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

scroll(*, scroll_id=None, error_trace=None, filter_path=None, human=None, pretty=None, rest_total_hits_as_int=None, scroll=None, body=None)

运行滚动搜索。

重要提示:不再推荐使用滚动API进行深度分页。如果需要在对超过10,000个命中结果分页时保留索引状态,请使用带有时间点(PIT)的search_after参数。

滚动API从单个滚动搜索请求中获取大量结果。 要获取必要的滚动ID,提交包含scroll查询参数参数的搜索API请求。 scroll参数指示Elasticsearch应为请求保留搜索上下文的时长。 搜索响应在_scroll_id响应体参数中返回滚动ID。 然后您可以使用滚动ID与滚动API一起检索请求的下一批结果。 如果启用了Elasticsearch安全功能,对特定滚动ID结果的访问仅限于提交搜索的用户或API密钥。

您还可以使用滚动API指定新的滚动参数以延长或缩短搜索上下文的保留期。

重要提示:滚动搜索的结果反映初始搜索请求时的索引状态。后续索引或文档更改仅影响以后的搜索和滚动请求。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-scroll

Parameters:
  • scroll_id (str | None) – 搜索的滚动ID

  • rest_total_hits_as_int (bool | None) – 如果为true,API响应的hit.total属性作为整数返回。如果为false,作为对象返回

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – 为滚动保留搜索上下文的时长

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

search(*, index=None, aggregations=None, aggs=None, allow_no_indices=None, allow_partial_search_results=None, analyze_wildcard=None, analyzer=None, batched_reduce_size=None, ccs_minimize_roundtrips=None, collapse=None, default_operator=None, df=None, docvalue_fields=None, error_trace=None, expand_wildcards=None, explain=None, ext=None, fields=None, filter_path=None, force_synthetic_source=None, from_=None, highlight=None, human=None, ignore_throttled=None, ignore_unavailable=None, include_named_queries_score=None, indices_boost=None, knn=None, lenient=None, max_concurrent_shard_requests=None, min_score=None, pit=None, post_filter=None, pre_filter_shard_size=None, preference=None, pretty=None, profile=None, q=None, query=None, rank=None, request_cache=None, rescore=None, rest_total_hits_as_int=None, retriever=None, routing=None, runtime_mappings=None, script_fields=None, scroll=None, search_after=None, search_type=None, seq_no_primary_term=None, size=None, slice=None, sort=None, source=None, source_exclude_vectors=None, source_excludes=None, source_includes=None, stats=None, stored_fields=None, suggest=None, suggest_field=None, suggest_mode=None, suggest_size=None, suggest_text=None, terminate_after=None, timeout=None, track_scores=None, track_total_hits=None, typed_keys=None, version=None, body=None)

执行搜索操作。

获取与请求中定义的查询匹配的搜索结果。可以通过q查询字符串参数或请求体提供搜索查询。如果两者都指定,则仅使用查询参数。

如果启用了Elasticsearch安全功能,您必须对目标数据流、索引或别名具有读取索引权限。对于跨集群搜索,请参考关于配置CCS权限的文档。要搜索别名的点时间(PIT),您必须对该别名的数据流或索引具有read索引权限。

搜索切片

当分页浏览大量文档时,将搜索拆分为多个切片并使用slicepit属性独立处理会很有帮助。默认情况下,拆分首先在分片上执行,然后在每个分片本地执行。本地拆分基于Lucene文档ID将分片划分为连续范围。

例如,如果分片数量等于2且请求4个切片,则切片0和2分配给第一个分片,切片1和3分配给第二个分片。

重要提示:所有切片应使用相同的点时间ID。如果使用不同的PIT ID,切片可能会重叠并遗漏文档。这种情况可能发生,因为拆分标准基于Lucene文档ID,这些ID在索引变更时不稳定。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search

Parameters:
  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和别名的逗号分隔列表。支持通配符(*)。要搜索所有数据流和索引,省略此参数或使用`*`或`_all`。

  • aggregations (Mapping[str, Mapping[str, Any]] | None) – 定义作为搜索请求一部分运行的聚合。

  • aggs (Mapping[str, Mapping[str, Any]] | None) – 定义作为搜索请求一部分运行的聚合。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、索引别名或`_all`值仅指向缺失或关闭的索引时,请求返回错误。即使请求针对其他开放索引,此行为也适用。例如,针对`foo*,bar*`的请求如果存在以`foo`开头的索引但没有以`bar`开头的索引,则返回错误。

  • allow_partial_search_results (bool | None) – 如果为`true`且存在分片请求超时或分片失败,请求返回部分结果。如果为`false`,则返回错误且无部分结果。要覆盖默认行为,可以将`search.default_allow_partial_results`集群设置设为`false`。

  • analyze_wildcard (bool | None) – 如果为`true`,分析通配符和前缀查询。此参数仅在指定`q`查询字符串参数时可用。

  • analyzer (str | None) – 用于查询字符串的分析器。此参数仅在指定`q`查询字符串参数时可用。

  • batched_reduce_size (int | None) – 应在协调节点上一次减少的分片结果数量。如果请求中潜在的分片数量可能很大,应使用此值作为保护机制以减少每个搜索请求的内存开销。

  • ccs_minimize_roundtrips (bool | None) – 如果为`true`,在运行跨集群搜索(CCS)请求时,最小化协调节点与远程集群之间的网络往返。

  • collapse (Mapping[str, Any] | None) – 根据指定字段的值折叠搜索结果。

  • default_operator (str | Literal['and', 'or'] | None) – 查询字符串查询的默认运算符:AND`或`OR。此参数仅在指定`q`查询字符串参数时可用。

  • df (str | None) – 当查询字符串中未给出字段前缀时使用的默认字段。此参数仅在指定`q`查询字符串参数时可用。

  • docvalue_fields (Sequence[Mapping[str, Any]] | None) – 通配符(*)字段模式数组。请求返回响应`hits.fields`属性中匹配这些模式的字段的文档值。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏数据流。支持逗号分隔值,如`open,hidden`。

  • explain (bool | None) – 如果为`true`,请求返回关于命中分数计算的详细信息。

  • ext (Mapping[str, Any] | None) – Elasticsearch插件定义的搜索扩展配置。

  • fields (Sequence[Mapping[str, Any]] | None) – 通配符(*)字段模式数组。请求返回响应`hits.fields`属性中匹配这些模式的字段值。

  • force_synthetic_source (bool | None) – 此请求是否强制使用合成_source?用于测试映射是否支持合成_source并了解最坏情况性能。启用此功能的获取会比在索引中本地启用合成_source慢。

  • from – 起始文档偏移量,必须为非负数。默认情况下,使用`from`和`size`参数无法分页超过10,000个命中。要分页更多命中,请使用`search_after`参数。

  • highlight (Mapping[str, Any] | None) – 指定用于从搜索结果的一个或多个字段中检索高亮片段的高亮器。

  • ignore_throttled (bool | None) – 如果为`true`,冻结时将忽略具体、扩展或别名索引。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求针对缺失或关闭的索引时返回错误。

  • include_named_queries_score (bool | None) – 如果为`true`,响应包括来自任何命名查询的分数贡献。此功能在搜索响应中的每个命中上重新运行每个命名查询。通常,这会给请求增加少量开销。但是,在大量命中上使用计算成本高的命名查询可能会增加显著开销。

  • indices_boost (Sequence[Mapping[str, float]] | None) – 提升来自指定索引的文档的`_score`。提升值是分数相乘的因子。大于`1.0`的提升值增加分数。介于`0`和`1.0`之间的提升值降低分数。

  • knn (Mapping[str, Any] | Sequence[Mapping[str, Any]] | None) – 要运行的近似kNN搜索。

  • lenient (bool | None) – 如果为`true`,查询字符串中基于格式的查询失败(如向数字字段提供文本)将被忽略。此参数仅在指定`q`查询字符串参数时可用。

  • max_concurrent_shard_requests (int | None) – 搜索在每个节点上并发运行的分片请求数。应使用此值限制搜索对集群的影响,以限制并发分片请求数。

  • min_score (float | None) – 匹配文档的最低`_score`。`_score`较低的文档不包含在搜索结果和聚合收集的结果中。

  • pit (Mapping[str, Any] | None) – 将搜索限制到一个点时间(PIT)。如果提供PIT,则不能在请求路径中指定`<index>`。

  • post_filter (Mapping[str, Any] | None) – 使用`post_filter`参数过滤搜索结果。搜索命中在计算聚合后被过滤。后过滤器对聚合结果没有影响。

  • pre_filter_shard_size (int | None) – 如果搜索请求扩展到的分片数超过阈值,则强制执行基于查询重写的预过滤往返以预过滤搜索分片。如果分片基于其重写方法无法匹配任何文档(例如日期过滤器是必须匹配的但分片边界和查询不相交),此过滤往返可以显著限制分片数量。未指定时,如果满足以下任一条件则执行预过滤阶段:*请求目标超过128个分片。*请求目标一个或多个只读索引。*查询的主要排序目标是一个索引字段。

  • preference (str | None) – 用于搜索的节点和分片。默认情况下,Elasticsearch使用自适应副本选择从符合条件的节点和分片中选择,考虑分配感知。有效值为:*_only_local`仅在本地节点上的分片上运行搜索。*`_local`尽可能在本地节点上的分片上运行搜索,否则使用默认方法选择分片。*`_only_nodes:<node-id>,<node-id>`仅在指定节点ID上运行搜索。如果多个选定节点上存在合适分片,则使用这些节点上的分片使用默认方法。如果指定的节点都不可用,则使用默认方法从任何可用节点选择分片。*`_prefer_nodes:<node-id>,<node-id>`尽可能在指定节点ID上运行搜索。否则使用默认方法选择分片。*`_shards:<shard>,<shard>`仅在指定分片上运行搜索。可以与其他`preference`值组合。但`_shards`值必须在前。例如:`_shards:2,3|_local*`<custom-string>`(任何不以`_`开头的字符串)将具有相同`<custom-string>`的搜索路由到相同分片并按相同顺序。

  • profile (bool | None) – 设为`true`返回搜索请求中各个组件执行的详细时间信息。注意:这是调试工具,会显著增加搜索执行开销。

  • q (str | None) – Lucene查询字符串语法中的查询。查询参数搜索不支持完整的Elasticsearch Query DSL,但便于测试。重要提示:此参数覆盖请求体中的查询参数。如果两个参数都指定,则不会返回匹配请求体查询参数的文档。

  • query (Mapping[str, Any] | None) – 使用Query DSL的搜索定义。

  • rank (Mapping[str, Any] | None) – 要使用的互惠排名融合(RRF)。

  • request_cache (bool | None) – 如果为`true`,对`size`为`0`的请求启用搜索结果缓存。默认为索引级别设置。

  • rescore (Mapping[str, Any] | Sequence[Mapping[str, Any]] | None) – 可用于通过仅对`query`和`post_filter`阶段返回的顶部(例如100-500)文档重新排序来提高精度。

  • rest_total_hits_as_int (bool | None) – 指示`hits.total`在rest搜索响应中应呈现为整数还是对象。

  • retriever (Mapping[str, Any] | None) – 检索器是描述从搜索返回的顶部文档的规范。检索器替换搜索API中其他也返回顶部文档的元素,如`query`和`knn`。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • runtime_mappings (Mapping[str, Mapping[str, Any]] | None) – 搜索请求中的一个或多个运行时字段。这些字段优先于具有相同名称的映射字段。

  • script_fields (Mapping[str, Mapping[str, Any]] | None) – 为每个命中检索基于不同字段的脚本评估。

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – 用于滚动的搜索上下文保留时间。默认情况下,此值不能超过`1d`(24小时)。可以使用`search.max_keep_alive`集群级别设置更改此限制。

  • search_after (Sequence[None | bool | float | int | str] | None) – 用于使用上一页的一组排序值检索下一页命中。

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – 指示如何计算分布式词频以进行相关性评分。

  • seq_no_primary_term (bool | None) – 如果为`true`,请求返回每个命中最后修改的序列号和主项。

  • size (int | None) – 要返回的命中数,必须为非负数。默认情况下,使用`from`和`size`参数无法分页超过10,000个命中。要分页更多命中,请使用`search_after`属性。

  • slice (Mapping[str, Any] | None) – 将滚动搜索拆分为可以独立处理的多个切片。

  • sort (Sequence[str | Mapping[str, Any]] | str | Mapping[str, Any] | None) – 逗号分隔的<field>:<direction>对列表。

  • source (bool | Mapping[str, Any] | None) – 为匹配文档返回的源字段。这些字段在搜索响应的`hits._source`属性中返回。如果指定了`stored_fields`属性,则`_source`属性默认为`false`。否则默认为`true`。

  • source_exclude_vectors (bool | None) – 是否应从_source中排除向量

  • source_excludes (str | Sequence[str] | None) – 要从响应中排除的源字段的逗号分隔列表。也可以使用此参数排除`_source_includes`查询参数中指定的子集中的字段。如果`_source`参数为`false`,则忽略此参数。

  • source_includes (str | Sequence[str] | None) – 要在响应中包含的源字段的逗号分隔列表。如果指定此参数,则仅返回这些源字段。可以使用`_source_excludes`查询参数从此子集中排除字段。如果`_source`参数为`false`,则忽略此参数。

  • stats (Sequence[str] | None) – 与搜索关联的统计组。每个组为其关联的搜索维护统计聚合。可以使用索引统计API检索这些统计信息。

  • stored_fields (str | Sequence[str] | None) – 作为命中一部分返回的存储字段的逗号分隔列表。如果未指定字段,则响应中不包含存储字段。如果指定此字段,则`_source`属性默认为`false`。可以传递`_source: true`以在搜索响应中同时返回源字段和存储字段。

  • suggest (Mapping[str, Any] | None) – 定义基于提供文本提供相似外观术语的建议器。

  • suggest_field (str | None) – 用于建议的字段。

  • suggest_mode (str | Literal['always', 'missing', 'popular'] | None) – 建议模式。此参数仅在指定`suggest_field`和`suggest_text`查询字符串参数时可用。

  • suggest_size (int | None) – 要返回的建议数。此参数仅在指定`suggest_field`和`suggest_text`查询字符串参数时可用。

  • suggest_text (str | None) – 应返回建议的源文本。此参数仅在指定`suggest_field`和`suggest_text`查询字符串参数时可用。

  • terminate_after (int | None) – 为每个分片收集的最大文档数。如果查询达到此限制,Elasticsearch提前终止查询。Elasticsearch在排序前收集文档。重要提示:谨慎使用。Elasticsearch将此属性应用于处理请求的每个分片。可能时,让Elasticsearch自动执行提前终止。避免为针对跨多个数据层的备份索引的数据流的请求指定此属性。如果设为`0`(默认),查询不会提前终止。

  • timeout (str | None) – 等待每个分片响应的超时时间。如果在超时到期前未收到响应,则请求失败并返回错误。默认为无超时。

  • track_scores (bool | None) – 如果为`true`,计算并返回文档分数,即使分数不用于排序。

  • track_total_hits (bool | int | None) – 准确计数匹配查询的命中数。如果为`true`,以一些性能为代价返回准确的命中数。如果为`false`,响应不包括匹配查询的总命中数。

  • typed_keys (bool | None) – 如果为`true`,聚合和建议器名称在响应中以其各自类型为前缀。

  • version (bool | None) – 如果为`true`,请求返回文档版本作为命中的一部分。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • from_ (int | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

search_mvt(*, index, field, zoom, x, y, aggs=None, buffer=None, error_trace=None, exact_bounds=None, extent=None, fields=None, filter_path=None, grid_agg=None, grid_precision=None, grid_type=None, human=None, pretty=None, query=None, runtime_mappings=None, size=None, sort=None, track_total_hits=None, with_labels=None, body=None)

Search a vector tile.

Search a vector tile for geospatial values. Before using this API, you should be familiar with the Mapbox vector tile specification. The API returns results as a binary mapbox vector tile.

Internally, Elasticsearch translates a vector tile search API request into a search containing:

  • A geo_bounding_box query on the <field>. The query uses the <zoom>/<x>/<y> tile as a bounding box.
  • A geotile_grid or geohex_grid aggregation on the <field>. The grid_agg parameter determines the aggregation type. The aggregation uses the <zoom>/<x>/<y> tile as a bounding box.
  • Optionally, a geo_bounds aggregation on the <field>. The search only includes this aggregation if the exact_bounds parameter is true.
  • If the optional parameter with_labels is true, the internal search will include a dynamic runtime field that calls the getLabelPosition function of the geometry doc value. This enables the generation of new point features containing suggested geometry labels, so that, for example, multi-polygons will have only one label.

The API returns results as a binary Mapbox vector tile. Mapbox vector tiles are encoded as Google Protobufs (PBF). By default, the tile contains three layers:

  • A hits layer containing a feature for each <field> value matching the geo_bounding_box query.
  • An aggs layer containing a feature for each cell of the geotile_grid or geohex_grid. The layer only contains features for cells with matching data.
  • A meta layer containing:
    • A feature containing a bounding box. By default, this is the bounding box of the tile.
    • Value ranges for any sub-aggregations on the geotile_grid or geohex_grid.
    • Metadata for the search.

The API only returns features that can display at its zoom level. For example, if a polygon feature has no area at its zoom level, the API omits it. The API returns errors as UTF-8 encoded JSON.

IMPORTANT: You can specify several options for this API as either a query parameter or request body parameter. If you specify both parameters, the query parameter takes precedence.

Grid precision for geotile

For a grid_agg of geotile, you can use cells in the aggs layer as tiles for lower zoom levels. grid_precision represents the additional zoom levels available through these cells. The final precision is computed by as follows: <zoom> + grid_precision. For example, if <zoom> is 7 and grid_precision is 8, then the geotile_grid aggregation will use a precision of 15. The maximum final precision is 29. The grid_precision also determines the number of cells for the grid as follows: (2^grid_precision) x (2^grid_precision). For example, a value of 8 divides the tile into a grid of 256 x 256 cells. The aggs layer only contains features for cells with matching data.

Grid precision for geohex

For a grid_agg of geohex, Elasticsearch uses <zoom> and grid_precision to calculate a final precision as follows: <zoom> + grid_precision.

This precision determines the H3 resolution of the hexagonal cells produced by the geohex aggregation. The following table maps the H3 resolution for each precision. For example, if <zoom> is 3 and grid_precision is 3, the precision is 6. At a precision of 6, hexagonal cells have an H3 resolution of 2. If <zoom> is 3 and grid_precision is 4, the precision is 7. At a precision of 7, hexagonal cells have an H3 resolution of 3.

Precision Unique tile bins H3 resolution Unique hex bins Ratio
1 4 0 122 30.5
2 16 0 122 7.625
3 64 1 842 13.15625
4 256 1 842 3.2890625
5 1024 2 5882 5.744140625
6 4096 2 5882 1.436035156
7 16384 3 41162 2.512329102
8 65536 3 41162 0.6280822754
9 262144 4 288122 1.099098206
10 1048576 4 288122 0.2747745514
11 4194304 5 2016842 0.4808526039
12 16777216 6 14117882 0.8414913416
13 67108864 6 14117882 0.2103728354
14 268435456 7 98825162 0.3681524172
15 1073741824 8 691776122 0.644266719
16 4294967296 8 691776122 0.1610666797
17 17179869184 9 4842432842 0.2818666889
18 68719476736 10 33897029882 0.4932667053
19 274877906944 11 237279209162 0.8632167343
20 1099511627776 11 237279209162 0.2158041836
21 4398046511104 12 1660954464122 0.3776573213
22 17592186044416 13 11626681248842 0.6609003122
23 70368744177664 13 11626681248842 0.165225078
24 281474976710656 14 81386768741882 0.2891438866
25 1125899906842620 15 569707381193162 0.5060018015
26 4503599627370500 15 569707381193162 0.1265004504
27 18014398509482000 15 569707381193162 0.03162511259
28 72057594037927900 15 569707381193162 0.007906278149
29 288230376151712000 15 569707381193162 0.001976569537

Hexagonal cells don't align perfectly on a vector tile. Some cells may intersect more than one vector tile. To compute the H3 resolution for each precision, Elasticsearch compares the average density of hexagonal bins at each resolution with the average density of tile bins at each zoom level. Elasticsearch uses the H3 resolution that is closest to the corresponding geotile density.

Learn how to use the vector tile search API with practical examples in the Vector tile search examples guide.

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search-mvt

Parameters:
  • index (str | Sequence[str]) – Comma-separated list of data streams, indices, or aliases to search

  • field (str) – Field containing geospatial data to return

  • zoom (int) – Zoom level for the vector tile to search

  • x (int) – X coordinate for the vector tile to search

  • y (int) – Y coordinate for the vector tile to search

  • aggs (Mapping[str, Mapping[str, Any]] | None) – Sub-aggregations for the geotile_grid. It supports the following aggregation types: - avg - boxplot - cardinality - extended stats - max - median absolute deviation - min - percentile - percentile-rank - stats - sum - value count The aggregation names can’t start with _mvt_. The _mvt_ prefix is reserved for internal aggregations.

  • buffer (int | None) – The size, in pixels, of a clipping buffer outside the tile. This allows renderers to avoid outline artifacts from geometries that extend past the extent of the tile.

  • exact_bounds (bool | None) – If false, the meta layer’s feature is the bounding box of the tile. If true, the meta layer’s feature is a bounding box resulting from a geo_bounds aggregation. The aggregation runs on <field> values that intersect the <zoom>/<x>/<y> tile with wrap_longitude set to false. The resulting bounding box may be larger than the vector tile.

  • extent (int | None) – The size, in pixels, of a side of the tile. Vector tiles are square with equal sides.

  • fields (str | Sequence[str] | None) – The fields to return in the hits layer. It supports wildcards (*). This parameter does not support fields with array values. Fields with array values may return inconsistent results.

  • grid_agg (str | Literal['geohex', 'geotile'] | None) – The aggregation used to create a grid for the field.

  • grid_precision (int | None) – Additional zoom levels available through the aggs layer. For example, if <zoom> is 7 and grid_precision is 8, you can zoom in up to level 15. Accepts 0-8. If 0, results don’t include the aggs layer.

  • grid_type (str | Literal['centroid', 'grid', 'point'] | None) – Determines the geometry type for features in the aggs layer. In the aggs layer, each feature represents a geotile_grid cell. If grid, each feature is a polygon of the cells bounding box. If `point, each feature is a Point that is the centroid of the cell.

  • query (Mapping[str, Any] | None) – The query DSL used to filter documents for the search.

  • runtime_mappings (Mapping[str, Mapping[str, Any]] | None) – Defines one or more runtime fields in the search request. These fields take precedence over mapped fields with the same name.

  • size (int | None) – The maximum number of features to return in the hits layer. Accepts 0-10000. If 0, results don’t include the hits layer.

  • sort (Sequence[str | Mapping[str, Any]] | str | Mapping[str, Any] | None) – Sort the features in the hits layer. By default, the API calculates a bounding box for each feature. It sorts features based on this box’s diagonal length, from longest to shortest.

  • track_total_hits (bool | int | None) – The number of hits matching the query to count accurately. If true, the exact number of hits is returned at the cost of some performance. If false, the response does not include the total number of hits matching the query.

  • with_labels (bool | None) – If true, the hits and aggs layers will contain additional point features representing suggested label positions for the original features. * Point and MultiPoint features will have one of the points selected. * Polygon and MultiPolygon features will have a single point generated, either the centroid, if it is within the polygon, or another point within the polygon selected from the sorted triangle-tree. * LineString features will likewise provide a roughly central point selected from the triangle-tree. * The aggregation results will provide one central point for each aggregation bucket. All attributes from the original features will also be copied to the new label features. In addition, the new features will be distinguishable using the tag _mvt_label_position.

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

BinaryApiResponse

search_shards(*, index=None, allow_no_indices=None, error_trace=None, expand_wildcards=None, filter_path=None, human=None, ignore_unavailable=None, local=None, master_timeout=None, preference=None, pretty=None, routing=None)

获取搜索分片信息。

获取搜索请求将运行的索引和分片信息。 这些信息对于排查问题或规划路由和分片偏好优化非常有用。 当使用过滤别名时,过滤器会作为indices部分的一部分返回。

如果启用了Elasticsearch安全功能,您必须对目标数据流、索引或别名拥有view_index_metadatamanage索引权限。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search-shards

Parameters:
  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和别名的逗号分隔列表。 支持通配符(*)。要搜索所有数据流和索引, 请省略此参数或使用`*`或`_all`。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、 索引别名或`_all`值仅指向缺失或关闭的索引时,请求将返回错误。 即使请求同时指向其他打开的索引,此行为也适用。例如, 指向`foo*,bar*`的请求会在存在以`foo`开头的索引但不存在以`bar`开头的索引时返回错误。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。如果请求可以指向数据流, 此参数决定通配符表达式是否匹配隐藏的数据流。支持逗号分隔的值, 例如`open,hidden`。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求指向缺失或关闭的索引时, 请求将返回错误。

  • local (bool | None) – 如果为`true`,请求仅从本地节点获取信息。

  • master_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待连接主节点的时间。 如果在超时前主节点不可用,请求将失败并返回错误。 也可以设置为`-1`表示请求永不超时。

  • preference (str | None) – 应执行操作的节点或分片。 默认为随机选择。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]

search_template(*, index=None, allow_no_indices=None, ccs_minimize_roundtrips=None, error_trace=None, expand_wildcards=None, explain=None, filter_path=None, human=None, id=None, ignore_throttled=None, ignore_unavailable=None, params=None, preference=None, pretty=None, profile=None, rest_total_hits_as_int=None, routing=None, scroll=None, search_type=None, source=None, typed_keys=None, body=None)

使用搜索模板执行搜索。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search-template

Parameters:
  • index (str | Sequence[str] | None) – 要搜索的数据流、索引和别名列表,以逗号分隔。支持通配符(*)。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、索引别名或`_all`值仅指向缺失或关闭的索引时,请求将返回错误。即使请求同时指向其他打开的索引,此行为也适用。例如,针对`foo*,bar*`的请求会在存在以`foo`开头的索引但不存在以`bar`开头的索引时返回错误。

  • ccs_minimize_roundtrips (bool | None) – 如果为`true`,跨集群搜索请求将最小化网络往返次数。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可匹配的索引类型。如果请求可以针对数据流,此参数决定通配符表达式是否匹配隐藏的数据流。支持逗号分隔的值,如`open,hidden`。

  • explain (bool | None) – 如果为`true`,返回每条命中结果中关于分数计算的详细信息。如果同时指定此参数和`explain`查询参数,API仅使用查询参数。

  • id (str | None) – 要使用的搜索模板ID。如果未指定`source`,则此参数为必需。

  • ignore_throttled (bool | None) – 如果为`true`,被限流时响应中不包含指定的具体索引、扩展索引或别名索引。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求指向缺失或关闭的索引时将返回错误。

  • params (Mapping[str, Any] | None) – 用于替换模板中Mustache变量的键值对。键是变量名,值是变量值。

  • preference (str | None) – 执行操作的节点或分片。默认为随机选择。

  • profile (bool | None) – 如果为`true`,将对查询执行进行性能分析。

  • rest_total_hits_as_int (bool | None) – 如果为`true`,响应中的`hits.total`将呈现为整数;如果为`false`,则呈现为对象。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – 指定在滚动搜索中应保持索引一致视图的时间长度。

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – 搜索操作的类型。

  • source (str | Mapping[str, Any] | None) – 内联搜索模板。支持与搜索API请求体相同的参数,同时支持Mustache变量。如果未指定`id`,则此参数为必需。

  • typed_keys (bool | None) – 如果为`true`,响应中聚合和建议器名称将带有各自类型的前缀。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

terms_enum(*, index, field=None, case_insensitive=None, error_trace=None, filter_path=None, human=None, index_filter=None, pretty=None, search_after=None, size=None, string=None, timeout=None, body=None)

获取索引中的术语。

发现索引中匹配部分字符串的术语。 该API专为自动补全场景中的低延迟查找而设计。

提示 术语枚举API可能返回已删除文档中的术语。已删除文档最初仅被标记为删除状态。 只有当它们的段被合并时,文档才会被实际删除。在此之前,术语枚举API仍会返回这些文档中的术语。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-terms-enum

Parameters:
  • index (str) – 要搜索的数据流、索引和索引别名的逗号分隔列表。 支持通配符(*)表达式。若要搜索所有数据流或索引,可省略此参数或使用`*`或`_all`。

  • field (str | None) – 用于匹配索引术语开头的字符串。如果未提供,则考虑字段中的所有术语。

  • case_insensitive (bool | None) – 当为`true`时,提供的搜索字符串将与索引术语进行不区分大小写的匹配。

  • index_filter (Mapping[str, Any] | None) – 如果提供的查询重写为`match_none`,则过滤索引分片。

  • search_after (str | None) – 指定返回索引中该字符串之后的术语。 它允许一种分页形式,如果将一个请求的最后一个结果作为后续请求的`search_after`参数传递。

  • size (int | None) – 要返回的匹配术语数量。

  • string (str | None) – 用于匹配索引术语开头的字符串。如果未提供,则考虑字段中的所有术语。> 提示 > 前缀字符串 不能大于可能的最大关键字值,即Lucene的术语字节长度限制32766。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 收集结果的最大时间长度。如果超时,响应中的`complete`标志将设置为`false`, 结果可能是部分或空的。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

termvectors(*, index, id=None, doc=None, error_trace=None, field_statistics=None, fields=None, filter=None, filter_path=None, human=None, offsets=None, payloads=None, per_field_analyzer=None, positions=None, preference=None, pretty=None, realtime=None, routing=None, term_statistics=None, version=None, version_type=None, body=None)

获取词项向量信息。

获取特定文档字段中词项的信息和统计。

可以检索索引中存储文档的词项向量,或通过请求体传入的人工文档词项向量。 可通过fields参数或在请求体中添加字段来指定感兴趣的字段。 例如:

GET /my-index-000001/_termvectors/1?fields=message

字段可使用通配符指定,类似于多匹配查询。

词项向量默认是实时的,而非近实时。 可通过将realtime参数设为false来改变此行为。

可请求三种类型的值:词项信息词项统计字段统计。 默认返回所有字段的词项信息和字段统计,但不包含词项统计。

词项信息

  • 字段中的词项频率(始终返回)
  • 词项位置(positions: true
  • 起始和结束偏移量(offsets: true
  • 词项载荷(payloads: true),以base64编码字节形式

如果请求的信息未存储在索引中,将尽可能实时计算。 此外,词项向量可针对索引中不存在但由用户提供的文档进行计算。

警告 起始和结束偏移量假设使用UTF-16编码。若想使用这些偏移量获取生成该标记的原始文本,应确保截取的子字符串也使用UTF-16编码。

行为

词项和字段统计不精确。 已删除文档不被计入。 信息仅从请求文档所在分片获取。 因此词项和字段统计仅作为相对度量有用,绝对数值在此上下文中无意义。 默认情况下,请求人工文档词项向量时,会随机选择分片获取统计信息。 使用routing可定向到特定分片。 详细API使用示例请参阅链接文档。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-termvectors

Parameters:
  • index (str) – 包含文档的索引名称。

  • id (str | None) – 文档的唯一标识符。

  • doc (Mapping[str, Any] | None) – 人工文档(不在索引中的文档),用于获取其词项向量。

  • field_statistics (bool | None) – 若为`true`,响应包含:* 文档计数(包含该字段的文档数)。 * 文档频率总和(该字段所有词项的文档频率之和)。* 总词频总和(该字段每个词项的总词频之和)。

  • fields (str | Sequence[str] | None) – 包含在统计中的字段列表。除非在`completion_fields`或`fielddata_fields` 参数中提供特定字段列表,否则作为默认列表使用。

  • filter (Mapping[str, Any] | None) – 基于tf-idf分数过滤词项。可用于找出文档的特征向量, 其工作方式类似于More Like This Query的第二阶段。

  • offsets (bool | None) – 若为`true`,响应包含词项偏移量。

  • payloads (bool | None) – 若为`true`,响应包含词项载荷。

  • per_field_analyzer (Mapping[str, str] | None) – 覆盖默认的每字段分析器。适用于以任意方式生成词项向量, 特别是使用人工文档时。为已存储词项向量的字段提供分析器时,将重新生成词项向量。

  • positions (bool | None) – 若为`true`,响应包含词项位置。

  • preference (str | None) – 执行操作的节点或分片,默认为随机。

  • realtime (bool | None) – 若为true,请求是实时的而非近实时的。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • term_statistics (bool | None) – 若为`true`,响应包含:* 总词频(词项在所有文档中出现次数)。 * 文档频率(包含当前词项的文档数)。默认不返回这些值,因词项统计会严重影响性能。

  • version (int | None) – 若为`true`,返回文档版本作为命中结果的一部分。

  • version_type (str | Literal['external', 'external_gte', 'force', 'internal'] | None) – 版本类型。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

update(*, index, id, detect_noop=None, doc=None, doc_as_upsert=None, error_trace=None, filter_path=None, human=None, if_primary_term=None, if_seq_no=None, include_source_on_error=None, lang=None, pretty=None, refresh=None, require_alias=None, retry_on_conflict=None, routing=None, script=None, scripted_upsert=None, source=None, source_excludes=None, source_includes=None, timeout=None, upsert=None, wait_for_active_shards=None, body=None)

更新文档。

通过运行脚本或传递部分文档来更新文档。

如果启用了Elasticsearch安全功能,您必须对目标索引或索引别名拥有indexwrite索引权限。

脚本可以更新、删除或跳过修改文档。 该API还支持传递部分文档,这些内容会被合并到现有文档中。 要完全替换现有文档,请使用索引API。 此操作:

  • 从索引中获取文档(与分片共置)。
  • 运行指定的脚本。
  • 索引结果。

文档仍需重新索引,但使用此API可以减少网络往返次数,并降低GET操作与索引操作之间出现版本冲突的可能性。

必须启用_source字段才能使用此API。 除了_source,您还可以通过ctx映射访问以下变量:_index_type_id_version_routing_now(当前时间戳)。 有关部分更新、upsert和脚本化更新等用法示例,请参阅外部文档。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update

Parameters:
  • index (str) – 目标索引名称。默认情况下,如果索引不存在会自动创建。

  • id (str) – 要更新文档的唯一标识符。

  • detect_noop (bool | None) – 如果为`true`,当文档没有变化时,响应中的`result`会设置为`noop`(无操作)。

  • doc (Mapping[str, Any] | None) – 对现有文档的部分更新。如果同时指定了`doc`和`script`,则忽略`doc`。

  • doc_as_upsert (bool | None) – 如果为`true`,使用’doc’的内容作为’upsert’的值。 注意:不支持将ingest管道与`doc_as_upsert`一起使用。

  • if_primary_term (int | None) – 仅当文档具有此主术语时才执行操作。

  • if_seq_no (int | None) – 仅当文档具有此序列号时才执行操作。

  • include_source_on_error (bool | None) – 在解析错误时是否在错误消息中包含文档源(true或false)。

  • lang (str | None) – 脚本语言。

  • refresh (bool | str | Literal['false', 'true', 'wait_for'] | None) – 如果为’true’,Elasticsearch会刷新受影响的分片以使此操作对搜索可见。如果为’wait_for’,则等待刷新以使此操作对搜索可见。如果为’false’,则不进行任何刷新操作。

  • require_alias (bool | None) – 如果为`true`,目标必须是索引别名。

  • retry_on_conflict (int | None) – 发生冲突时操作应重试的次数。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • script (Mapping[str, Any] | None) – 用于更新文档的脚本。

  • scripted_upsert (bool | None) – 如果为`true`,无论文档是否存在都运行脚本。

  • source (bool | Mapping[str, Any] | None) – 如果为`false`,关闭源检索。您也可以指定要检索的字段的逗号分隔列表。

  • source_excludes (str | Sequence[str] | None) – 要排除的源字段。

  • source_includes (str | Sequence[str] | None) – 要检索的源字段。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 等待以下操作的超时时间:动态映射更新和等待活动分片。Elasticsearch在失败前至少等待超时时间。实际等待时间可能更长,特别是在发生多次等待时。

  • upsert (Mapping[str, Any] | None) – 如果文档尚不存在,则将’upsert’的内容作为新文档插入。如果文档存在,则运行’script’。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 在执行操作之前必须处于活动状态的每个分片的副本数。设置为’all’或任何正整数,最大为索引中的总分片数(`number_of_replicas`+1)。默认值`1`表示等待每个主分片变为活动状态。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

update_by_query(*, index, allow_no_indices=None, analyze_wildcard=None, analyzer=None, conflicts=None, default_operator=None, df=None, error_trace=None, expand_wildcards=None, filter_path=None, from_=None, human=None, ignore_unavailable=None, lenient=None, max_docs=None, pipeline=None, preference=None, pretty=None, q=None, query=None, refresh=None, request_cache=None, requests_per_second=None, routing=None, script=None, scroll=None, scroll_size=None, search_timeout=None, search_type=None, slice=None, slices=None, sort=None, stats=None, terminate_after=None, timeout=None, version=None, version_type=None, wait_for_active_shards=None, wait_for_completion=None, body=None)

更新文档。 更新符合指定查询条件的文档。 如果未指定查询条件,则对数据流或索引中的每个文档执行更新操作但不修改源数据,这适用于获取映射变更。

如果启用了Elasticsearch安全功能,您必须对目标数据流、索引或别名拥有以下索引权限:

  • read
  • indexwrite

您可以使用与搜索API相同的语法,在请求URI或请求体中指定查询条件。

当您提交按查询更新请求时,Elasticsearch在开始处理请求时会获取数据流或索引的快照,并使用内部版本控制更新匹配的文档。 当版本匹配时,文档会被更新且版本号递增。 如果在快照拍摄时间和更新操作处理时间之间文档发生变化,会导致版本冲突并使操作失败。 您可以通过设置conflictsproceed来选择统计版本冲突而非停止并返回。 请注意,如果选择统计版本冲突,该操作可能会尝试从源中更新比max_docs更多的文档,直到成功更新max_docs个文档或遍历完源查询中的所有文档。

注意:版本号为0的文档无法通过按查询更新进行更新,因为内部版本控制不支持0作为有效版本号。

在处理按查询更新请求时,Elasticsearch会顺序执行多个搜索请求以查找所有匹配文档。 对每批匹配文档执行批量更新请求。 任何查询或更新失败都会导致按查询更新请求失败,并在响应中显示失败信息。 任何已成功完成的更新请求仍会保留,不会被回滚。

刷新分片

指定refresh参数会在请求完成后刷新所有分片。 这与更新API的refresh参数不同,后者仅刷新接收请求的分片。与更新API不同,它不支持wait_for

异步执行按查询更新

如果请求包含wait_for_completion=false,Elasticsearch会执行一些预检检查,启动请求,并返回一个可用于取消或获取任务状态的任务。 Elasticsearch会在.tasks/task/${taskId}处将此任务记录为一个文档。

等待活跃分片

wait_for_active_shards控制在进行请求之前必须有多少分片副本处于活跃状态。详情请参阅wait_for_active_shardstimeout控制每个写入请求等待不可用分片变为可用的时间。两者的工作方式与批量API中完全相同。按查询更新使用滚动搜索,因此您还可以指定scroll参数来控制搜索上下文保持活动的时间,例如?scroll=10m。默认为5分钟。

节流更新请求

要控制按查询更新发出批量更新操作的速率,您可以将requests_per_second设置为任何正十进制数。 这会为每批添加等待时间以节流速率。 将requests_per_second设置为-1可关闭节流。

节流使用批次之间的等待时间,以便内部滚动请求可以获得考虑请求填充的超时时间。 填充时间是批次大小除以requests_per_second与写入时间之差。 默认批次大小为1000,因此如果requests_per_second设置为500

target_time = 1000 / 500 per second = 2 seconds
wait_time = target_time - write_time = 2 seconds - .5 seconds = 1.5 seconds

由于批次作为单个_bulk请求发出,大批次大小会导致Elasticsearch创建许多请求并在开始下一组之前等待。 这是“突发式”而非“平滑式”。

切片

按查询更新支持切片滚动以并行化更新过程。 这可以提高效率,并提供将请求分解为较小部分的便捷方式。

slices设置为auto会为大多数数据流和索引选择合理的数量。 此设置将为每个分片使用一个切片,最多达到某个限制。 如果有多个源数据流或索引,它将基于具有最少分片数的索引或后备索引选择切片数量。

_update_by_query添加slices只是自动化了创建子请求的手动过程,这意味着它有一些特点:

  • 您可以在任务API中看到这些请求。这些子请求是具有切片的请求任务的“子”任务。
  • 获取带有slices的请求任务状态仅包含已完成切片的状态。
  • 这些子请求可以单独寻址以进行取消和重新节流等操作。
  • 重新节流带有slices的请求将按比例重新节流未完成的子请求。
  • 取消带有切片的请求将取消每个子请求。
  • 由于切片的性质,每个子请求不会获得完全均匀的文档部分。所有文档都会被处理,但某些切片可能比其他切片大。预计较大的切片会有更均匀的分布。
  • requests_per_secondmax_docs这样的参数在带有切片的请求中会按比例分配给每个子请求。结合上述关于分布不均匀的观点,您应该得出结论,将max_docsslices一起使用可能不会精确更新max_docs个文档。
  • 每个子请求获取的源数据流或索引快照略有不同,尽管这些快照都是在大致相同的时间拍摄的。

如果您手动切片或以其他方式调整自动切片,请记住:

  • 当切片数量等于索引或后备索引的分片数量时,查询性能最有效。如果该数字很大(例如500),请选择较小的数字,因为过多的切片会损害性能。将切片数量设置为高于分片数量通常不会提高效率,反而会增加开销。
  • 更新性能随切片数量在可用资源上线性扩展。

查询或更新性能主导运行时取决于正在重新索引的文档和集群资源。 有关如何使用_update_by_query API更新文档的示例,请参阅链接文档:

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update-by-query

Parameters:
  • index (str | Sequence[str]) – 要搜索的数据流、索引和别名的逗号分隔列表。支持通配符(*)。要搜索所有数据流或索引,请省略此参数或使用`*`或`_all`。

  • allow_no_indices (bool | None) – 如果为`false`,当任何通配符表达式、索引别名或`_all`值仅针对缺失或关闭的索引时,请求将返回错误。即使请求针对其他打开的索引,此行为也适用。例如,针对`foo*,bar*`的请求如果存在以`foo`开头的索引但没有以`bar`开头的索引,将返回错误。

  • analyze_wildcard (bool | None) – 如果为`true`,则分析通配符和前缀查询。此参数仅在指定`q`查询字符串参数时可用。

  • analyzer (str | None) – 用于查询字符串的分析器。此参数仅在指定`q`查询字符串参数时可用。

  • conflicts (str | Literal['abort', 'proceed'] | None) – 当按查询更新遇到版本冲突时的首选行为:abort`或`proceed

  • default_operator (str | Literal['and', 'or'] | None) – 查询字符串查询的默认运算符:AND`或`OR。此参数仅在指定`q`查询字符串参数时可用。

  • df (str | None) – 在查询字符串中未给出字段前缀时用作默认值的字段。此参数仅在指定`q`查询字符串参数时可用。

  • expand_wildcards (Sequence[str | Literal['all', 'closed', 'hidden', 'none', 'open']] | str | ~typing.Literal['all', 'closed', 'hidden', 'none', 'open'] | None) – 通配符模式可以匹配的索引类型。如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏的数据流。支持逗号分隔的值,例如`open,hidden`。

  • from – 跳过指定数量的文档。

  • ignore_unavailable (bool | None) – 如果为`false`,当请求针对缺失或关闭的索引时,请求将返回错误。

  • lenient (bool | None) – 如果为`true`,查询字符串中基于格式的查询失败(例如向数字字段提供文本)将被忽略。此参数仅在指定`q`查询字符串参数时可用。

  • max_docs (int | None) – 要更新的最大文档数。

  • pipeline (str | None) – 用于预处理传入文档的管道ID。如果索引指定了默认的摄取管道,则将值设置为`_none`会禁用此请求的默认摄取管道。如果配置了最终管道,它将始终运行,无论此参数的值如何。

  • preference (str | None) – 应执行操作的节点或分片。默认为随机。

  • q (str | None) – Lucene查询字符串语法中的查询。

  • query (Mapping[str, Any] | None) – 使用Query DSL更新的文档。

  • refresh (bool | None) – 如果为`true`,Elasticsearch会在请求完成后刷新受影响的分片,使操作对搜索可见。这与更新API的`refresh`参数不同,后者仅刷新接收请求的分片。

  • request_cache (bool | None) – 如果为`true`,则为此请求使用请求缓存。默认为索引级别设置。

  • requests_per_second (float | None) – 此请求的节流,单位为每秒子请求数。

  • routing (str | None) – 用于将操作路由到特定分片的自定义值。

  • script (Mapping[str, Any] | None) – 更新时用于更新文档源或元数据的脚本。

  • scroll (str | Literal[-1] | ~typing.Literal[0] | None) – 为滚动保留搜索上下文的时间段。

  • scroll_size (int | None) – 为操作提供动力的滚动请求的大小。

  • search_timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 每个搜索请求的显式超时。默认情况下没有超时。

  • search_type (str | Literal['dfs_query_then_fetch', 'query_then_fetch'] | None) – 搜索操作的类型。可用选项包括`query_then_fetch`和`dfs_query_then_fetch`。

  • slice (Mapping[str, Any] | None) – 使用提供的切片ID和切片总数手动切片请求。

  • slices (int | str | Literal['auto'] | None) – 此任务应划分的切片数量。

  • sort (Sequence[str] | None) – 逗号分隔的<field>:<direction>对列表。

  • stats (Sequence[str] | None) – 用于日志记录和统计目的的请求特定`tag`。

  • terminate_after (int | None) – 为每个分片收集的最大文档数。如果查询达到此限制,Elasticsearch会提前终止查询。Elasticsearch在排序前收集文档。重要提示:谨慎使用。Elasticsearch将此参数应用于处理请求的每个分片。在可能的情况下,让Elasticsearch自动执行提前终止。避免为针对跨多个数据层的后备索引的数据流的请求指定此参数。

  • timeout (str | Literal[-1] | ~typing.Literal[0] | None) – 每个更新请求等待以下操作的时间段:动态映射更新、等待活跃分片。默认为一分钟。这保证Elasticsearch在失败前至少等待超时时间。实际等待时间可能更长,特别是在发生多次等待时。

  • version (bool | None) – 如果为`true`,则返回作为命中一部分的文档版本。

  • version_type (bool | None) – 文档是否应在命中时增加版本号(内部)或不增加(重新索引)。

  • wait_for_active_shards (int | str | Literal['all', 'index-setting'] | None) – 在进行操作之前必须处于活跃状态的分片副本数量。设置为`all`或任何正整数,最多为索引中的总分片数(number_of_replicas+1)。`timeout`参数控制每个写入请求等待不可用分片变为可用的时间。两者的工作方式与批量API中完全相同。

  • wait_for_completion (bool | None) – 如果为`true`,请求会阻塞直到操作完成。如果为`false`,Elasticsearch执行一些预检检查,启动请求,并返回一个可用于取消或获取任务状态的任务ID。Elasticsearch会在`.tasks/task/${taskId}`处将此任务记录为一个文档。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • from_ (int | None)

  • human (bool | None)

  • pretty (bool | None)

  • body (Dict[str, Any] | None)

Return type:

ObjectApiResponse[Any]

update_by_query_rethrottle(*, task_id, error_trace=None, filter_path=None, human=None, pretty=None, requests_per_second=None)

节流一个按查询更新的操作。

调整特定按查询更新操作的每秒请求数。 加速查询的重新节流会立即生效,而减速查询的重新节流会在当前批次完成后生效,以防止滚动超时。

https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update-by-query-rethrottle

Parameters:
  • task_id (str) – 任务ID。

  • requests_per_second (float | None) – 该请求的节流值,单位为每秒子请求数。 要关闭节流,请设置为`-1`。

  • error_trace (bool | None)

  • filter_path (str | Sequence[str] | None)

  • human (bool | None)

  • pretty (bool | None)

Return type:

ObjectApiResponse[Any]