Elasticsearch专题精讲—— REST APIs —— Document APIs —— Bulk API

REST APIs —— Document APIs —— Bulk API

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#docs-bulk

Performs multiple indexing or delete operations in a single API call. This reduces overhead and can greatly increase indexing speed.

在单个 API 调用中执行多个建立索引或删除操作。这降低了开销,并且可以极大地提高索引速度。

curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
        { "index" : { "_index" : "test", "_id" : "1" } }
        { "field1" : "value1" }
        { "delete" : { "_index" : "test", "_id" : "2" } }
        { "create" : { "_index" : "test", "_id" : "3" } }
        { "field1" : "value3" }
        { "update" : {"_id" : "1", "_index" : "test"} }
        { "doc" : {"field2" : "value2"} }
        '

1、Request(请求)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#docs-bulk-api-request

        POST /_bulk

        POST /_mass
        
        POST /< target>/_bulk
        
        POST /< target>/_mass

2、Prerequisites(先决条件)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#docs-bulk-api-prereqs

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

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

      • To use the create action, you must have the create_doc, create, index, or write index privilege. Data streams support only the create action.

    要使用 create 操作,您必须拥有 create_doc、create、index 或 write index 权限。数据流只支持 create 操作。

      • To use the index action, you must have the create, index, or write index privilege.

    若要使用 index 操作,必须具有创建、索引或写入索引特权。

      • To use the delete action, you must have the delete or write index privilege.

    若要使用 delete 操作,必须具有删除或写入索引特权。

      • To use the update action, you must have the index or write index privilege.

    若要使用更新操作,必须具有索引或写入索引特权。

      • To automatically create a data stream or index with a bulk API request, you must have the auto_configure, create_index, or manage index privilege.

    若要使用批量 API 请求自动创建数据流或索引,必须具有 auto _ configure、 create _ index 或者管理索引特权。

      • To make the result of a bulk operation visible to search using the refresh parameter, you must have the maintenance or manage index privilege.

    若要使批量操作的结果可见,以便使用刷新参数进行搜索,必须具有维护或管理索引特权。

Automatic data stream creation requires a matching index template with data stream enabled. See Set up a data stream.

自动数据流创建需要使用已启用数据流的匹配索引模板。请参见《Set up a data stream》(https://www.elastic.co/guide/en/elasticsearch/reference/8.8/set-up-a-data-stream.html)。

3、Description(描述)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#docs-bulk-api-desc

Provides a way to perform multiple index, create, delete, and update actions in a single request.

提供在单个请求中执行多个索引、创建、删除和更新操作的方法。

The actions are specified in the request body using a newline delimited JSON (NDJSON) structure:

这些操作在请求体中使用新行分隔的 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

The index and create actions expect a source on the next line, and have the same semantics as the op_type parameter in the standard index API: create fails if a document with the same ID already exists in the target, index adds or replaces a document as necessary.

索引和创建操作在下一行预期有一个源,并且与标准索引 API 中的 op_type 参数具有相同的语义:如果在目标中已存在具有相同 ID 的文档,则创建操作会失败;索引操作根据需要添加或替换文档。

Data streams support only the create action. To update or delete a document in a data stream, you must target the backing index containing the document. See Update or delete documents in a backing index.

数据流只支持创建操作。若要更新或删除数据流中的文档,必须以包含该文档的后备索引为目标。请参见更新或删除后备索引中的文档。

update expects that the partial doc, upsert, and script and its options are specified on the next line.

Update 希望在下一行中指定部分文档、 upsert 和脚本及其选项。

delete does not expect a source on the next line and has the same semantics as the standard delete API.

Delete 不期望下一行有源代码,并且具有与标准 delete API 相同的语义。

The final line of data must end with a newline character \n. Each newline character may be preceded by a carriage return \r. When sending NDJSON data to the _bulk endpoint, use a Content-Type header of application/json or application/x-ndjson.

数据的最后一行必须以换行符\n结尾。每个换行符可以由回车符\r前置。当向_bulk端点发送NDJSON数据时,请使用Content-Type头为application/json或application/x-ndjson。

Because this format uses literal \n's as delimiters, make sure that the JSON actions and sources are not pretty printed.

由于此格式使用文字 \n 作为分隔符,请确保 JSON 操作和资源不是精美的打印格式。

If you provide a in the request path, it is used for any actions that don’t explicitly specify an _index argument.

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

A note on the format: The idea here is to make processing of this as fast as possible. As some of the actions are redirected to other shards on other nodes, only action_meta_data is parsed on the receiving node side.

关于格式的说明:这里的想法是尽可能快速地处理。由于一些操作会重定向到其他节点上的其他分片,因此在接收节点端只解析 action_meta_data。

Client libraries using this protocol should try and strive to do something similar on the client side, and reduce buffering as much as possible.

使用此协议的客户端库应该尽力在客户端端做类似的事情,并尽量减少缓冲区。

There is no "correct" number of actions to perform in a single bulk request. Experiment with different settings to find the optimal size for your particular workload. Note that Elasticsearch limits the maximum size of a HTTP request to 100mb by default so clients must ensure that no request exceeds this size. It is not possible to index a single document which exceeds the size limit, so you must pre-process any such documents into smaller pieces before sending them to Elasticsearch. For instance, split documents into pages or chapters before indexing them, or store raw binary data in a system outside Elasticsearch and replacing the raw data with a link to the external system in the documents that you send to Elasticsearch.

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

4、Client support for bulk requests(客户端对批量请求的支持)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-clients

Some of the officially supported clients provide helpers to assist with bulk requests and reindexing:

部分官方支持的客户端提供辅助功能,以帮助执行批量请求和重新索引:

Go

  See esutil.BulkIndexer

Perl

  See Search::Elasticsearch::Client::5_0::Bulk and Search::Elasticsearch::Client::5_0::Scroll

Python

  See elasticsearch.helpers.*

JavaScript

  See client.helpers.*.

NET

  See BulkAllObservable

PHP

  See Bulk indexing

5、Submitting bulk requests with cURL(使用 cURL 提交批量请求)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-curl

If you’re providing text file input to curl, you must use the --data-binary flag instead of plain -d. The latter doesn’t preserve newlines. Example:

如果您向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}}]}
            

6、Optimistic concurrency control(乐观并发控制求)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-optimistic-concurrency-control

Each index and delete action within a bulk API call may include the if_seq_no and if_primary_term parameters in their respective action and meta data lines. The if_seq_no and if_primary_term parameters control how operations are executed, based on the last modification to existing documents. See Optimistic concurrency control for more details.

在批量 API 调用中的每个索引和删除操作都可以在各自的操作和元数据行中包含 if_seq_no 和 if_primary_term 参数。if_seq_no 和 if_primary_term 参数根据现有文档的最后修改来控制操作的执行。有关更多详细信息,请查看乐观并发控制(https://www.elastic.co/guide/en/elasticsearch/reference/8.8/optimistic-concurrency-control.html)。

7、Versioning(版本控制)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-versioning

Each bulk item can include the version value using the version field. It automatically follows the behavior of the index / delete operation based on the _version mapping. It also support the version_type (see versioning).

每个批量项都可以使用 version 字段包含版本值。它根据 _ version 映射自动跟踪 index/delete 操作的行为。它还支持 version _ type (参见版本控制https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html#index-versioning)。

8、Routing(路由)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-routing

Each bulk item can include the routing value using the routing field. It automatically follows the behavior of the index / delete operation based on the _routing mapping.

每个批量项都可以使用路由字段包括路由值。它会自动遵循基于 _routing 映射的索引 / 删除操作行为。

Data streams do not support custom routing unless they were created with the allow_custom_routing setting enabled in the template.

数据流不支持自定义路由,除非它们是使用模板中启用了 allow_custom_routing 设置创建的。

9、Wait for active shards(等待激活的分片)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-wait-for-active-shards

When making bulk calls, you can set the wait_for_active_shards parameter to require a minimum number of shard copies to be active before starting to process the bulk request. See here for further details and a usage example.

在进行批量调用时,可以设置 wait_for_active_shards 参数,要求在开始处理批量请求之前必须有一定数量的分片副本处于活动状态。更多细节和用法示例请参见此处(https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html#index-wait-for-active-shards)。

Data streams do not support custom routing unless they were created with the allow_custom_routing setting enabled in the template.

数据流不支持自定义路由,除非它们是使用模板中启用了 allow_custom_routing 设置创建的。

10、Refresh(刷新)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-refresh

Control when the changes made by this request are visible to search. See refresh.

控制此请求所做的更改何时对搜索可见。请参见 refresh(https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-refresh.html)。

Only the shards that receive the bulk request will be affected by refresh. Imagine a _bulk?refresh=wait_for request with three documents in it that happen to be routed to different shards in an index with five shards. The request will only wait for those three shards to refresh. The other two shards that make up the index do not participate in the _bulk request at all.

控件在此请求所做的更改可见时进行搜索。请参见刷新。

11、Security(安全)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-security

See URL-based access control.

请参见基于 URL 的访问控制(https://www.elastic.co/guide/en/elasticsearch/reference/8.8/api-conventions.html#api-url-access-control)。

12、Examples(例子)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#docs-bulk-api-example

curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
        { "index" : { "_index" : "test", "_id" : "1" } }
        { "field1" : "value1" }
        { "delete" : { "_index" : "test", "_id" : "2" } }
        { "create" : { "_index" : "test", "_id" : "3" } }
        { "field1" : "value3" }
        { "update" : {"_id" : "1", "_index" : "test"} }
        { "doc" : {"field2" : "value2"} }
        '
    

The API returns the following result:

API 返回以下结果:

        {
            "took": 30,
            "errors": false,
            "items": [
               {
                  "index": {
                     "_index": "test",
                     "_id": "1",
                     "_version": 1,
                     "result": "created",
                     "_shards": {
                        "total": 2,
                        "successful": 1,
                        "failed": 0
                     },
                     "status": 201,
                     "_seq_no" : 0,
                     "_primary_term": 1
                  }
               },
               {
                  "delete": {
                     "_index": "test",
                     "_id": "2",
                     "_version": 1,
                     "result": "not_found",
                     "_shards": {
                        "total": 2,
                        "successful": 1,
                        "failed": 0
                     },
                     "status": 404,
                     "_seq_no" : 1,
                     "_primary_term" : 2
                  }
               },
               {
                  "create": {
                     "_index": "test",
                     "_id": "3",
                     "_version": 1,
                     "result": "created",
                     "_shards": {
                        "total": 2,
                        "successful": 1,
                        "failed": 0
                     },
                     "status": 201,
                     "_seq_no" : 2,
                     "_primary_term" : 3
                  }
               },
               {
                  "update": {
                     "_index": "test",
                     "_id": "1",
                     "_version": 2,
                     "result": "updated",
                     "_shards": {
                         "total": 2,
                         "successful": 1,
                         "failed": 0
                     },
                     "status": 200,
                     "_seq_no" : 3,
                     "_primary_term" : 4
                  }
               }
            ]
         }
    

13、Bulk update example(批量更新示例)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-update

When using the update action, retry_on_conflict can be used as a field in the action itself (not in the extra payload line), to specify how many times an update should be retried in the case of a version conflict.

在使用更新操作时,可以将 retry_on_conflict 用作操作本身中的字段(而不是在额外的有效荷行中),以指定在版本冲突的情况下应重试更新多少次。

The update action payload supports the following options: doc (partial document), upsert, doc_as_upsert, script, params (for script), lang (for script), and _source. See update documentation for details on the options. Example with update actions:

更新操作载荷支持以下选项:doc(部分文档),upsert,doc_as_upsert,script,params(用于脚本),lang(用于脚本)和_source。有关选项的详细信息,请参阅更新文档。以下是带有更新操作的示例:

        curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
        { "update" : {"_id" : "1", "_index" : "index1", "retry_on_conflict" : 3} }
        { "doc" : {"field" : "value"} }
        { "update" : { "_id" : "0", "_index" : "index1", "retry_on_conflict" : 3} }
        { "script" : { "source": "ctx._source.counter += params.param1", "lang" : "painless", "params" : {"param1" : 1}}, "upsert" : {"counter" : 1}}
        { "update" : {"_id" : "2", "_index" : "index1", "retry_on_conflict" : 3} }
        { "doc" : {"field" : "value"}, "doc_as_upsert" : true }
        { "update" : {"_id" : "3", "_index" : "index1", "_source" : true} }
        { "doc" : {"field" : "value"} }
        { "update" : {"_id" : "4", "_index" : "index1"} }
        { "doc" : {"field" : "value"}, "_source": true}
        '        
     

14、Example with failed actions(失败操作的示例)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-failures-ex

The following bulk API request includes operations that update non-existent documents.

下面的批量 API 请求包括更新不存在的文档的操作。

        curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
        { "update": {"_id": "5", "_index": "index1"} }
        { "doc": {"my_field": "foo"} }
        { "update": {"_id": "6", "_index": "index1"} }
        { "doc": {"my_field": "foo"} }
        { "create": {"_id": "7", "_index": "index1"} }
        { "my_field": "foo" }
        '               
     

Because these operations cannot complete successfully, the API returns a response with an errors flag of true.

因为这些操作不能成功完成,所以 API 返回一个错误标志为 true 的响应。

The response also includes an error object for any failed operations. The error object contains additional information about the failure, such as the error type and reason.

响应还包括任何失败操作的错误对象。错误对象包含有关失败的附加信息,如错误类型和原因。

        {
            "took": 486,
            "errors": true,
            "items": [
              {
                "update": {
                  "_index": "index1",
                  "_id": "5",
                  "status": 404,
                  "error": {
                    "type": "document_missing_exception",
                    "reason": "[5]: document missing",
                    "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA",
                    "shard": "0",
                    "index": "index1"
                  }
                }
              },
              {
                "update": {
                  "_index": "index1",
                  "_id": "6",
                  "status": 404,
                  "error": {
                    "type": "document_missing_exception",
                    "reason": "[6]: document missing",
                    "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA",
                    "shard": "0",
                    "index": "index1"
                  }
                }
              },
              {
                "create": {
                  "_index": "index1",
                  "_id": "7",
                  "_version": 1,
                  "result": "created",
                  "_shards": {
                    "total": 2,
                    "successful": 1,
                    "failed": 0
                  },
                  "_seq_no": 0,
                  "_primary_term": 1,
                  "status": 201
                }
              }
            ]
          } 

To return only information about failed operations, use the filter_path query parameter with an argument of items.*.error.

若要仅返回有关失败操作的信息,请使用带项参数的 filter _ path 查询参数. * . error。

        curl -X POST "localhost:9200/_bulk?filter_path=items.*.error&pretty" -H 'Content-Type: application/json' -d'
        { "update": {"_id": "5", "_index": "index1"} }
        { "doc": {"my_field": "baz"} }
        { "update": {"_id": "6", "_index": "index1"} }
        { "doc": {"my_field": "baz"} }
        { "update": {"_id": "7", "_index": "index1"} }
        { "doc": {"my_field": "baz"} }
        '
     

The API returns the following result.

API 返回以下结果。

        {
            "items": [
              {
                "update": {
                  "error": {
                    "type": "document_missing_exception",
                    "reason": "[5]: document missing",
                    "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA",
                    "shard": "0",
                    "index": "index1"
                  }
                }
              },
              {
                "update": {
                  "error": {
                    "type": "document_missing_exception",
                    "reason": "[6]: document missing",
                    "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA",
                    "shard": "0",
                    "index": "index1"
                  }
                }
              }
            ]
          }

15、Example with dynamic templates parameter(具有动态模板参数的示例)

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-bulk.html#bulk-dynamic-templates

The below example creates a dynamic template, then performs a bulk request consisting of index/create requests with the dynamic_templates parameter.

下面的示例创建一个动态模板,然后执行一个大容量请求,该大容量请求由带有 Dynamic _ template 参数的 index/create 请求组成。

        curl -X PUT "localhost:9200/my-index/?pretty" -H 'Content-Type: application/json' -d'
        {
          "mappings": {
            "dynamic_templates": [
              {
                "geo_point": {
                     "mapping": {
                        "type" : "geo_point"
                     }
                }
              }
            ]
          }
        }'

        curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
        { "index" : { "_index" : "my_index", "_id" : "1", "dynamic_templates": {"work_location": "geo_point"}} }
        { "field" : "value1", "work_location": "41.12,-71.34", "raw_location": "41.12,-71.34"}
        { "create" : { "_index" : "my_index", "_id" : "2", "dynamic_templates": {"home_location": "geo_point"}} }
        { "field" : "value2", "home_location": "41.12,-71.34"}'
        

The bulk request creates two new fields work_location and home_location with type geo_point according to the dynamic_templates parameter; however, the raw_location field is created using default dynamic mapping rules, as a text field in that case since it is supplied as a string in the JSON document.

批量请求根据dynamic_templates参数创建了两个新字段work_location和home_location,类型为geo_point;但是,raw_location字段是使用默认的动态映射规则创建的,在这种情况下,它是一个文本字段,因为它在JSON文档中被提供为字符串。

posted @ 2023-06-09 14:26  左扬  阅读(130)  评论(0编辑  收藏  举报
levels of contents