Skip to content

Commit 583601b

Browse files
authored
[DOCS] Add examples for update by query (#3597)
1 parent aecc157 commit 583601b

11 files changed

+338
-110
lines changed

output/openapi/elasticsearch-openapi.json

Lines changed: 35 additions & 26 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

output/openapi/elasticsearch-serverless-openapi.json

Lines changed: 34 additions & 25 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

output/schema/schema.json

Lines changed: 57 additions & 34 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

specification/_doc_ids/table.csv

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ docs-multi-termvectors,https://www.elastic.co/guide/en/elasticsearch/reference/{
151151
docs-reindex,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/docs-reindex.html
152152
docs-termvectors,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/docs-termvectors.html
153153
docs-update-by-query,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/docs-update-by-query.html
154+
docs-update-by-query-rethrottle,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/docs-update-by-query.html#docs-update-by-query-rethrottle
154155
docs-update,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/docs-update.html
155156
document-input-parameters,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/query-dsl-mlt-query.html#_document_input_parameters
156157
docvalue-fields,https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/search-fields.html#docvalue-fields

specification/_global/update_by_query/UpdateByQueryRequest.ts

Lines changed: 128 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,93 @@ import { Duration } from '@_types/Time'
3838
* Update documents.
3939
* Updates documents that match the specified query.
4040
* If no query is specified, performs an update on every document in the data stream or index without modifying the source, which is useful for picking up mapping changes.
41+
*
42+
* If the Elasticsearch security features are enabled, you must have the following index privileges for the target data stream, index, or alias:
43+
*
44+
* * `read`
45+
* * `index` or `write`
46+
*
47+
* You can specify the query criteria in the request URI or the request body using the same syntax as the search API.
48+
*
49+
* When you submit an update by query request, Elasticsearch gets a snapshot of the data stream or index when it begins processing the request and updates matching documents using internal versioning.
50+
* When the versions match, the document is updated and the version number is incremented.
51+
* If a document changes between the time that the snapshot is taken and the update operation is processed, it results in a version conflict and the operation fails.
52+
* You can opt to count version conflicts instead of halting and returning by setting `conflicts` to `proceed`.
53+
* Note that if you opt to count version conflicts, the operation could attempt to update more documents from the source than `max_docs` until it has successfully updated `max_docs` documents or it has gone through every document in the source query.
54+
*
55+
* NOTE: Documents with a version equal to 0 cannot be updated using update by query because internal versioning does not support 0 as a valid version number.
56+
*
57+
* While processing an update by query request, Elasticsearch performs multiple search requests sequentially to find all of the matching documents.
58+
* A bulk update request is performed for each batch of matching documents.
59+
* Any query or update failures cause the update by query request to fail and the failures are shown in the response.
60+
* Any update requests that completed successfully still stick, they are not rolled back.
61+
*
62+
* **Throttling update requests**
63+
*
64+
* To control the rate at which update by query issues batches of update operations, you can set `requests_per_second` to any positive decimal number.
65+
* This pads each batch with a wait time to throttle the rate.
66+
* Set `requests_per_second` to `-1` to turn off throttling.
67+
*
68+
* 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.
69+
* The padding time is the difference between the batch size divided by the `requests_per_second` and the time spent writing.
70+
* By default the batch size is 1000, so if `requests_per_second` is set to `500`:
71+
*
72+
* ```
73+
* target_time = 1000 / 500 per second = 2 seconds
74+
* wait_time = target_time - write_time = 2 seconds - .5 seconds = 1.5 seconds
75+
* ```
76+
*
77+
* 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.
78+
* This is "bursty" instead of "smooth".
79+
*
80+
* **Slicing**
81+
*
82+
* Update by query supports sliced scroll to parallelize the update process.
83+
* This can improve efficiency and provide a convenient way to break the request down into smaller parts.
84+
*
85+
* Setting `slices` to `auto` chooses a reasonable number for most data streams and indices.
86+
* This setting will use one slice per shard, up to a certain limit.
87+
* 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.
88+
*
89+
* Adding `slices` to `_update_by_query` just automates the manual process of creating sub-requests, which means it has some quirks:
90+
*
91+
* * You can see these requests in the tasks APIs. These sub-requests are "child" tasks of the task for the request with slices.
92+
* * Fetching the status of the task for the request with `slices` only contains the status of completed slices.
93+
* * These sub-requests are individually addressable for things like cancellation and rethrottling.
94+
* * Rethrottling the request with `slices` will rethrottle the unfinished sub-request proportionally.
95+
* * Canceling the request with slices will cancel each sub-request.
96+
* * 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.
97+
* * Parameters like `requests_per_second` and `max_docs` on a request with slices are distributed proportionally to each sub-request. Combine that with the point above about distribution being uneven and you should conclude that using `max_docs` with `slices` might not result in exactly `max_docs` documents being updated.
98+
* * 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.
99+
*
100+
* If you're slicing manually or otherwise tuning automatic slicing, keep in mind that:
101+
*
102+
* * 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.
103+
* * Update performance scales linearly across available resources with the number of slices.
104+
*
105+
* Whether query or update performance dominates the runtime depends on the documents being reindexed and cluster resources.
106+
*
107+
* **Update the document source**
108+
*
109+
* Update by query supports scripts to update the document source.
110+
* As with the update API, you can set `ctx.op` to change the operation that is performed.
111+
*
112+
* Set `ctx.op = "noop"` if your script decides that it doesn't have to make any changes.
113+
* The update by query operation skips updating the document and increments the `noop` counter.
114+
*
115+
* Set `ctx.op = "delete"` if your script decides that the document should be deleted.
116+
* The update by query operation deletes the document and increments the `deleted` counter.
117+
*
118+
* Update by query supports only `index`, `noop`, and `delete`.
119+
* Setting `ctx.op` to anything else is an error.
120+
* Setting any other field in `ctx` is an error.
121+
* This API enables you to only modify the source of matching documents; you cannot move them.
41122
* @rest_spec_name update_by_query
42123
* @availability stack since=2.4.0 stability=stable
43124
* @availability serverless stability=stable visibility=public
125+
* @index_privileges read,write
44126
* @doc_tag document
127+
* @doc_id docs-update-by-query
45128
*/
46129
export interface Request extends RequestBase {
47130
urls: [
@@ -52,8 +135,8 @@ export interface Request extends RequestBase {
52135
]
53136
path_parts: {
54137
/**
55-
* Comma-separated list of data streams, indices, and aliases to search.
56-
* Supports wildcards (`*`).
138+
* A comma-separated list of data streams, indices, and aliases to search.
139+
* It supports wildcards (`*`).
57140
* To search all data streams or indices, omit this parameter or use `*` or `_all`.
58141
*/
59142
index: Indices
@@ -67,32 +150,36 @@ export interface Request extends RequestBase {
67150
*/
68151
allow_no_indices?: boolean
69152
/**
70-
* Analyzer to use for the query string.
153+
* The analyzer to use for the query string.
154+
* This parameter can be used only when the `q` query string parameter is specified.
71155
*/
72156
analyzer?: string
73157
/**
74158
* If `true`, wildcard and prefix queries are analyzed.
159+
* This parameter can be used only when the `q` query string parameter is specified.
75160
* @server_default false
76161
*/
77162
analyze_wildcard?: boolean
78163
/**
79-
* What to do if update by query hits version conflicts: `abort` or `proceed`.
164+
* The preferred behavior when update by query hits version conflicts: `abort` or `proceed`.
80165
* @server_default abort
81166
*/
82167
conflicts?: Conflicts
83168
/**
84169
* The default operator for query string query: `AND` or `OR`.
170+
* This parameter can be used only when the `q` query string parameter is specified.
85171
* @server_default OR
86172
*/
87173
default_operator?: Operator
88174
/**
89-
* Field to use as default where no field prefix is given in the query string.
175+
* The field to use as default where no field prefix is given in the query string.
176+
* This parameter can be used only when the `q` query string parameter is specified.
90177
*/
91178
df?: string
92179
/**
93-
* Type of index that wildcard patterns can match.
180+
* The type of index that wildcard patterns can match.
94181
* If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams.
95-
* Supports comma-separated values, such as `open,hidden`.
182+
* It supports comma-separated values, such as `open,hidden`.
96183
* Valid values are: `all`, `open`, `closed`, `hidden`, `none`.
97184
*/
98185
expand_wildcards?: ExpandWildcards
@@ -104,36 +191,40 @@ export interface Request extends RequestBase {
104191
ignore_unavailable?: boolean
105192
/**
106193
* If `true`, format-based query failures (such as providing text to a numeric field) in the query string will be ignored.
194+
* This parameter can be used only when the `q` query string parameter is specified.
107195
* @server_default false
108196
*/
109197
lenient?: boolean
110198
/**
111-
* Maximum number of documents to process.
112-
* Defaults to all documents.
199+
* The maximum number of documents to process.
200+
* It defaults to all documents.
201+
* When set to a value less then or equal to `scroll_size` then a scroll will not be used to retrieve the results for the operation.
113202
*/
114203
max_docs?: long
115204
/**
116-
* ID of the pipeline to use to preprocess incoming documents.
205+
* The ID of the pipeline to use to preprocess incoming documents.
117206
* If the index has a default ingest pipeline specified, then setting the value to `_none` disables the default ingest pipeline for this request.
118207
* If a final pipeline is configured it will always run, regardless of the value of this parameter.
119208
*/
120209
pipeline?: string
121210
/**
122-
* Specifies the node or shard the operation should be performed on.
123-
* Random by default.
211+
* The node or shard the operation should be performed on.
212+
* It is random by default.
124213
*/
125214
preference?: string
126215
/**
127-
* Query in the Lucene query string syntax.
216+
* A query in the Lucene query string syntax.
128217
*/
129218
q?: string
130219
/**
131-
* If `true`, Elasticsearch refreshes affected shards to make the operation visible to search.
220+
* If `true`, Elasticsearch refreshes affected shards to make the operation visible to search after the request completes.
221+
* This is different than the update API's `refresh` parameter, which causes just the shard that received the request to be refreshed.
132222
* @server_default false
133223
*/
134224
refresh?: boolean
135225
/**
136226
* If `true`, the request cache is used for this request.
227+
* It defaults to the index-level setting.
137228
*/
138229
request_cache?: boolean
139230
/**
@@ -142,24 +233,27 @@ export interface Request extends RequestBase {
142233
*/
143234
requests_per_second?: float
144235
/**
145-
* Custom value used to route operations to a specific shard.
236+
* A custom value used to route operations to a specific shard.
146237
*/
147238
routing?: Routing
148239
/**
149-
* Period to retain the search context for scrolling.
240+
* The period to retain the search context for scrolling.
241+
* @server_default 5m
242+
* @ext_doc_id search-scroll-results
150243
*/
151244
scroll?: Duration
152245
/**
153-
* Size of the scroll request that powers the operation.
246+
* The size of the scroll request that powers the operation.
154247
* @server_default 1000
155248
*/
156249
scroll_size?: long
157250
/**
158-
* Explicit timeout for each search request.
251+
* An explicit timeout for each search request.
252+
* By default, there is no timeout.
159253
*/
160254
search_timeout?: Duration
161255
/**
162-
* The type of the search operation. Available options: `query_then_fetch`, `dfs_query_then_fetch`.
256+
* The type of the search operation. Available options include `query_then_fetch` and `dfs_query_then_fetch`.
163257
*/
164258
search_type?: SearchType
165259
/**
@@ -172,21 +266,25 @@ export interface Request extends RequestBase {
172266
*/
173267
sort?: string[]
174268
/**
175-
* Specific `tag` of the request for logging and statistical purposes.
269+
* The specific `tag` of the request for logging and statistical purposes.
176270
*/
177271
stats?: string[]
178272
/**
179-
* Maximum number of documents to collect for each shard.
273+
* The maximum number of documents to collect for each shard.
180274
* If a query reaches this limit, Elasticsearch terminates the query early.
181275
* Elasticsearch collects documents before sorting.
182-
* Use with caution.
276+
*
277+
* IMPORTANT: Use with caution.
183278
* Elasticsearch applies this parameter to each shard handling the request.
184279
* When possible, let Elasticsearch perform early termination automatically.
185280
* Avoid specifying this parameter for requests that target data streams with backing indices across multiple data tiers.
186281
*/
187282
terminate_after?: long
188283
/**
189-
* Period each update request waits for the following operations: dynamic mapping updates, waiting for active shards.
284+
* The period each update request waits for the following operations: dynamic mapping updates, waiting for active shards.
285+
* By default, it is one minute.
286+
* This guarantees Elasticsearch waits for at least the timeout before failing.
287+
* The actual wait time could be longer, particularly when multiple waits occur.
190288
* @server_default 1m
191289
*/
192290
timeout?: Duration
@@ -198,11 +296,15 @@ export interface Request extends RequestBase {
198296
/**
199297
* The number of shard copies that must be active before proceeding with the operation.
200298
* Set to `all` or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
299+
* The `timeout` parameter controls how long each write request waits for unavailable shards to become available.
300+
* Both work exactly the way they work in the bulk API.
201301
* @server_default 1
202302
*/
203303
wait_for_active_shards?: WaitForActiveShards
204304
/**
205305
* If `true`, the request blocks until the operation is complete.
306+
* If `false`, Elasticsearch performs some preflight checks, launches the request, and returns a task ID that you can use to cancel or get the status of the task.
307+
* Elasticsearch creates a record of this task as a document at `.tasks/task/${taskId}`.
206308
* @server_default true
207309
*/
208310
wait_for_completion?: boolean
@@ -213,19 +315,20 @@ export interface Request extends RequestBase {
213315
*/
214316
max_docs?: long
215317
/**
216-
* Specifies the documents to update using the Query DSL.
318+
* The documents to update using the Query DSL.
217319
*/
218320
query?: QueryContainer
219321
/**
220322
* The script to run to update the document source or metadata when updating.
323+
*
221324
*/
222325
script?: Script
223326
/**
224327
* Slice the request manually using the provided slice ID and total number of slices.
225328
*/
226329
slice?: SlicedScroll
227330
/**
228-
* What to do if update by query hits version conflicts: `abort` or `proceed`.
331+
* The preferred behavior when update by query hits version conflicts: `abort` or `proceed`.
229332
* @server_default abort
230333
*/
231334
conflicts?: Conflicts

specification/_global/update_by_query/UpdateByQueryResponse.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,43 @@ import { Duration, DurationValue, UnitMillis } from '@_types/Time'
2525

2626
export class Response {
2727
body: {
28+
/** The number of scroll responses pulled back by the update by query. */
2829
batches?: long
30+
/**
31+
* Array of failures if there were any unrecoverable errors during the process.
32+
* If this is non-empty then the request ended because of those failures.
33+
* Update by query is implemented using batches.
34+
* Any failure causes the entire process to end, but all failures in the current batch are collected into the array.
35+
* You can use the `conflicts` option to prevent reindex from ending when version conflicts occur. */
2936
failures?: BulkIndexByScrollFailure[]
37+
/** The number of documents that were ignored because the script used for the update by query returned a noop value for `ctx.op`. */
3038
noops?: long
39+
/** The number of documents that were successfully deleted. */
3140
deleted?: long
41+
/** The number of requests per second effectively run during the update by query. */
3242
requests_per_second?: float
43+
/**
44+
* The number of retries attempted by update by query.
45+
* `bulk` is the number of bulk actions retried.
46+
* `search` is the number of search actions retried. */
3347
retries?: Retries
3448
task?: TaskId
49+
/** If true, some requests timed out during the update by query. */
3550
timed_out?: boolean
51+
/** The number of milliseconds from start to end of the whole operation. */
3652
took?: DurationValue<UnitMillis>
53+
/** The number of documents that were successfully processed. */
3754
total?: long
55+
/** The number of documents that were successfully updated. */
3856
updated?: long
57+
/** The number of version conflicts that the update by query hit. */
3958
version_conflicts?: long
4059
throttled?: Duration
60+
/** The number of milliseconds the request slept to conform to `requests_per_second`. */
4161
throttled_millis?: DurationValue<UnitMillis>
4262
throttled_until?: Duration
63+
/** This field should always be equal to zero in an _update_by_query response.
64+
* It only has meaning when using the task API, where it indicates the next time (in milliseconds since epoch) a throttled request will be run again in order to conform to `requests_per_second`. */
4365
throttled_until_millis?: DurationValue<UnitMillis>
4466
}
4567
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
summary: Update selected documents
2+
# method_request: POST my-index-000001/_update_by_query?conflicts=proceed
3+
description: >
4+
Run `POST my-index-000001/_update_by_query?conflicts=proceed` to update documents that match a query.
5+
# type: "request"
6+
value: |-
7+
{
8+
"query": {
9+
"term": {
10+
"user.id": "kimchy"
11+
}
12+
}
13+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
summary: Update the document source
2+
# method_request: POST my-index-000001/_update_by_query
3+
description: >
4+
Run `POST my-index-000001/_update_by_query` with a script to update the document source.
5+
It increments the `count` field for all documents with a `user.id` of `kimchy` in `my-index-000001`.
6+
# type: "request"
7+
value: |-
8+
{
9+
"script": {
10+
"source": "ctx._source.count++",
11+
"lang": "painless"
12+
},
13+
"query": {
14+
"term": {
15+
"user.id": "kimchy"
16+
}
17+
}
18+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
summary: Slice manually
2+
# method_request: POST my-index-000001/_update_by_query
3+
description: >
4+
Run `POST my-index-000001/_update_by_query` to slice an update by query manually.
5+
Provide a slice ID and total number of slices to each request.
6+
# type: "request"
7+
value: |-
8+
{
9+
"slice": {
10+
"id": 0,
11+
"max": 2
12+
},
13+
"script": {
14+
"source": "ctx._source['extra'] = 'test'"
15+
}
16+
}

0 commit comments

Comments
 (0)