delete-by-query.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. [[docs-delete-by-query]]
  2. === Delete by query API
  3. ++++
  4. <titleabbrev>Delete by query</titleabbrev>
  5. ++++
  6. Deletes documents that match the specified query.
  7. [source,console]
  8. --------------------------------------------------
  9. POST /my-index-000001/_delete_by_query
  10. {
  11. "query": {
  12. "match": {
  13. "user.id": "elkbee"
  14. }
  15. }
  16. }
  17. --------------------------------------------------
  18. // TEST[setup:my_index_big]
  19. ////
  20. [source,console-result]
  21. --------------------------------------------------
  22. {
  23. "took" : 147,
  24. "timed_out": false,
  25. "deleted": 119,
  26. "batches": 1,
  27. "version_conflicts": 0,
  28. "noops": 0,
  29. "retries": {
  30. "bulk": 0,
  31. "search": 0
  32. },
  33. "throttled_millis": 0,
  34. "requests_per_second": -1.0,
  35. "throttled_until_millis": 0,
  36. "total": 119,
  37. "failures" : [ ]
  38. }
  39. --------------------------------------------------
  40. // TESTRESPONSE[s/"took" : 147/"took" : "$body.took"/]
  41. ////
  42. [[docs-delete-by-query-api-request]]
  43. ==== {api-request-title}
  44. `POST /<target>/_delete_by_query`
  45. [[docs-delete-by-query-api-prereqs]]
  46. ==== {api-prereq-title}
  47. * If the {es} {security-features} are enabled, you must have the following
  48. <<privileges-list-indices,index privileges>> for the target data stream, index,
  49. or alias:
  50. ** `read`
  51. ** `delete` or `write`
  52. [[docs-delete-by-query-api-desc]]
  53. ==== {api-description-title}
  54. You can specify the query criteria in the request URI or the request body
  55. using the same syntax as the <<search-search,Search API>>.
  56. When you submit a delete by query request, {es} gets a snapshot of the data stream or index
  57. when it begins processing the request and deletes matching documents using
  58. `internal` versioning. If a document changes between the time that the
  59. snapshot is taken and the delete operation is processed, it results in a version
  60. conflict and the delete operation fails.
  61. NOTE: Documents with a version equal to 0 cannot be deleted using delete by
  62. query because `internal` versioning does not support 0 as a valid
  63. version number.
  64. While processing a delete by query request, {es} performs multiple search
  65. requests sequentially to find all of the matching documents to delete. A bulk
  66. delete request is performed for each batch of matching documents. If a
  67. search or bulk request is rejected, the requests are retried up to 10 times, with
  68. exponential back off. If the maximum retry limit is reached, processing halts
  69. and all failed requests are returned in the response. Any delete requests that
  70. completed successfully still stick, they are not rolled back.
  71. You can opt to count version conflicts instead of halting and returning by
  72. setting `conflicts` to `proceed`. Note that if you opt to count version conflicts
  73. the operation could attempt to delete more documents from the source
  74. than `max_docs` until it has successfully deleted `max_docs` documents, or it has gone through
  75. every document in the source query.
  76. ===== Refreshing shards
  77. Specifying the `refresh` parameter refreshes all shards involved in the delete
  78. by query once the request completes. This is different than the delete API's
  79. `refresh` parameter, which causes just the shard that received the delete
  80. request to be refreshed. Unlike the delete API, it does not support
  81. `wait_for`.
  82. [[docs-delete-by-query-task-api]]
  83. ===== Running delete by query asynchronously
  84. If the request contains `wait_for_completion=false`, {es}
  85. performs some preflight checks, launches the request, and returns a
  86. <<tasks,`task`>> you can use to cancel or get the status of the task. {es} creates a
  87. record of this task as a document at `.tasks/task/${taskId}`. When you are
  88. done with a task, you should delete the task document so {es} can reclaim the
  89. space.
  90. ===== Waiting for active shards
  91. `wait_for_active_shards` controls how many copies of a shard must be active
  92. before proceeding with the request. See <<index-wait-for-active-shards>>
  93. for details. `timeout` controls how long each write request waits for unavailable
  94. shards to become available. Both work exactly the way they work in the
  95. <<docs-bulk,Bulk API>>. Delete by query uses scrolled searches, so you can also
  96. specify the `scroll` parameter to control how long it keeps the search context
  97. alive, for example `?scroll=10m`. The default is 5 minutes.
  98. [[docs-delete-by-query-throttle]]
  99. ===== Throttling delete requests
  100. To control the rate at which delete by query issues batches of delete operations,
  101. you can set `requests_per_second` to any positive decimal number. This pads each
  102. batch with a wait time to throttle the rate. Set `requests_per_second` to `-1`
  103. to disable throttling.
  104. Throttling uses a wait time between batches so that the internal scroll requests
  105. can be given a timeout that takes the request padding into account. The padding
  106. time is the difference between the batch size divided by the
  107. `requests_per_second` and the time spent writing. By default the batch size is
  108. `1000`, so if `requests_per_second` is set to `500`:
  109. [source,txt]
  110. --------------------------------------------------
  111. target_time = 1000 / 500 per second = 2 seconds
  112. wait_time = target_time - write_time = 2 seconds - .5 seconds = 1.5 seconds
  113. --------------------------------------------------
  114. Since the batch is issued as a single `_bulk` request, large batch sizes
  115. cause {es} to create many requests and wait before starting the next set.
  116. This is "bursty" instead of "smooth".
  117. [[docs-delete-by-query-slice]]
  118. ===== Slicing
  119. Delete by query supports <<slice-scroll, sliced scroll>> to parallelize the
  120. delete process. This can improve efficiency and provide a
  121. convenient way to break the request down into smaller parts.
  122. Setting `slices` to `auto` chooses a reasonable number for most data streams and indices.
  123. If you're slicing manually or otherwise tuning automatic slicing, keep in mind
  124. that:
  125. * Query performance is most efficient when the number of `slices` is equal to
  126. the number of shards in the index or backing index. If that number is large (for example,
  127. 500), choose a lower number as too many `slices` hurts performance. Setting
  128. `slices` higher than the number of shards generally does not improve efficiency
  129. and adds overhead.
  130. * Delete performance scales linearly across available resources with the
  131. number of slices.
  132. Whether query or delete performance dominates the runtime depends on the
  133. documents being reindexed and cluster resources.
  134. [[docs-delete-by-query-api-path-params]]
  135. ==== {api-path-parms-title}
  136. `<target>`::
  137. (Optional, string) Comma-separated list of data streams, indices, and aliases to
  138. search. Supports wildcards (`*`). To search all data streams or indices, omit
  139. this parameter or use `* or `_all`.
  140. [[docs-delete-by-query-api-query-params]]
  141. ==== {api-query-parms-title}
  142. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=allow-no-indices]
  143. +
  144. Defaults to `true`.
  145. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=analyzer]
  146. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=analyze_wildcard]
  147. `conflicts`::
  148. (Optional, string) What to do if delete by query hits version conflicts:
  149. `abort` or `proceed`. Defaults to `abort`.
  150. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=default_operator]
  151. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=df]
  152. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=expand-wildcards]
  153. +
  154. Defaults to `open`.
  155. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=from]
  156. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=index-ignore-unavailable]
  157. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=lenient]
  158. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=max_docs]
  159. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=preference]
  160. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=search-q]
  161. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=request_cache]
  162. `refresh`::
  163. (Optional, Boolean) If `true`, {es} refreshes all shards involved in the
  164. delete by query after the request completes. Defaults to `false`.
  165. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=requests_per_second]
  166. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=routing]
  167. `scroll`::
  168. (Optional, <<time-units,time value>>)
  169. Period to retain the <<scroll-search-context,search context>> for scrolling. See
  170. <<scroll-search-results>>.
  171. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=scroll_size]
  172. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=search_type]
  173. `search_timeout`::
  174. (Optional, <<time-units, time units>>)
  175. Explicit timeout for each search request.
  176. Defaults to no timeout.
  177. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=slices]
  178. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=sort]
  179. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=stats]
  180. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=terminate_after]
  181. `timeout`::
  182. (Optional, <<time-units, time units>>)
  183. Period each deletion request <<index-wait-for-active-shards,waits for active
  184. shards>>. Defaults to `1m` (one minute).
  185. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=version]
  186. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=wait_for_active_shards]
  187. [[docs-delete-by-query-api-request-body]]
  188. ==== {api-request-body-title}
  189. `query`::
  190. (Optional, <<query-dsl,query object>>) Specifies the documents to delete
  191. using the <<query-dsl,Query DSL>>.
  192. [[docs-delete-by-query-api-response-body]]
  193. ==== Response body
  194. //////////////////////////
  195. [source,console]
  196. --------------------------------------------------
  197. POST /my-index-000001/_delete_by_query
  198. {
  199. "query": { <1>
  200. "match": {
  201. "user.id": "elkbee"
  202. }
  203. }
  204. }
  205. --------------------------------------------------
  206. // TEST[setup:my_index_big]
  207. //////////////////////////
  208. The JSON response looks like this:
  209. [source,console-result]
  210. --------------------------------------------------
  211. {
  212. "took" : 147,
  213. "timed_out": false,
  214. "total": 119,
  215. "deleted": 119,
  216. "batches": 1,
  217. "version_conflicts": 0,
  218. "noops": 0,
  219. "retries": {
  220. "bulk": 0,
  221. "search": 0
  222. },
  223. "throttled_millis": 0,
  224. "requests_per_second": -1.0,
  225. "throttled_until_millis": 0,
  226. "failures" : [ ]
  227. }
  228. --------------------------------------------------
  229. // TESTRESPONSE[s/: [0-9]+/: $body.$_path/]
  230. `took`::
  231. The number of milliseconds from start to end of the whole operation.
  232. `timed_out`::
  233. This flag is set to `true` if any of the requests executed during the
  234. delete by query execution has timed out.
  235. `total`::
  236. The number of documents that were successfully processed.
  237. `deleted`::
  238. The number of documents that were successfully deleted.
  239. `batches`::
  240. The number of scroll responses pulled back by the delete by query.
  241. `version_conflicts`::
  242. The number of version conflicts that the delete by query hit.
  243. `noops`::
  244. This field is always equal to zero for delete by query. It only exists
  245. so that delete by query, update by query, and reindex APIs return responses
  246. with the same structure.
  247. `retries`::
  248. The number of retries attempted by delete by query. `bulk` is the number
  249. of bulk actions retried, and `search` is the number of search actions retried.
  250. `throttled_millis`::
  251. Number of milliseconds the request slept to conform to `requests_per_second`.
  252. `requests_per_second`::
  253. The number of requests per second effectively executed during the delete by query.
  254. `throttled_until_millis`::
  255. This field should always be equal to zero in a `_delete_by_query` response. It only
  256. has meaning when using the <<tasks, Task API>>, where it
  257. indicates the next time (in milliseconds since epoch) a throttled request will be
  258. executed again in order to conform to `requests_per_second`.
  259. `failures`::
  260. Array of failures if there were any unrecoverable errors during the process. If
  261. this is non-empty then the request aborted because of those failures.
  262. Delete by query is implemented using batches, and any failure causes the entire
  263. process to abort but all failures in the current batch are collected into the
  264. array. You can use the `conflicts` option to prevent reindex from aborting on
  265. version conflicts.
  266. [[docs-delete-by-query-api-example]]
  267. ==== {api-examples-title}
  268. Delete all documents from the `my-index-000001` data stream or index:
  269. [source,console]
  270. --------------------------------------------------
  271. POST my-index-000001/_delete_by_query?conflicts=proceed
  272. {
  273. "query": {
  274. "match_all": {}
  275. }
  276. }
  277. --------------------------------------------------
  278. // TEST[setup:my_index]
  279. Delete documents from multiple data streams or indices:
  280. [source,console]
  281. --------------------------------------------------
  282. POST /my-index-000001,my-index-000002/_delete_by_query
  283. {
  284. "query": {
  285. "match_all": {}
  286. }
  287. }
  288. --------------------------------------------------
  289. // TEST[s/^/PUT my-index-000001\nPUT my-index-000002\n/]
  290. Limit the delete by query operation to shards that a particular routing
  291. value:
  292. [source,console]
  293. --------------------------------------------------
  294. POST my-index-000001/_delete_by_query?routing=1
  295. {
  296. "query": {
  297. "range" : {
  298. "age" : {
  299. "gte" : 10
  300. }
  301. }
  302. }
  303. }
  304. --------------------------------------------------
  305. // TEST[setup:my_index]
  306. By default `_delete_by_query` uses scroll batches of 1000. You can change the
  307. batch size with the `scroll_size` URL parameter:
  308. [source,console]
  309. --------------------------------------------------
  310. POST my-index-000001/_delete_by_query?scroll_size=5000
  311. {
  312. "query": {
  313. "term": {
  314. "user.id": "kimchy"
  315. }
  316. }
  317. }
  318. --------------------------------------------------
  319. // TEST[setup:my_index]
  320. Delete a document using a unique attribute:
  321. [source,console]
  322. --------------------------------------------------
  323. POST my-index-000001/_delete_by_query
  324. {
  325. "query": {
  326. "term": {
  327. "user.id": "kimchy"
  328. }
  329. },
  330. "max_docs": 1
  331. }
  332. --------------------------------------------------
  333. // TEST[setup:my_index]
  334. [discrete]
  335. [[docs-delete-by-query-manual-slice]]
  336. ===== Slice manually
  337. Slice a delete by query manually by providing a slice id and total number of
  338. slices:
  339. [source,console]
  340. ----------------------------------------------------------------
  341. POST my-index-000001/_delete_by_query
  342. {
  343. "slice": {
  344. "id": 0,
  345. "max": 2
  346. },
  347. "query": {
  348. "range": {
  349. "http.response.bytes": {
  350. "lt": 2000000
  351. }
  352. }
  353. }
  354. }
  355. POST my-index-000001/_delete_by_query
  356. {
  357. "slice": {
  358. "id": 1,
  359. "max": 2
  360. },
  361. "query": {
  362. "range": {
  363. "http.response.bytes": {
  364. "lt": 2000000
  365. }
  366. }
  367. }
  368. }
  369. ----------------------------------------------------------------
  370. // TEST[setup:my_index_big]
  371. Which you can verify works with:
  372. [source,console]
  373. ----------------------------------------------------------------
  374. GET _refresh
  375. POST my-index-000001/_search?size=0&filter_path=hits.total
  376. {
  377. "query": {
  378. "range": {
  379. "http.response.bytes": {
  380. "lt": 2000000
  381. }
  382. }
  383. }
  384. }
  385. ----------------------------------------------------------------
  386. // TEST[continued]
  387. Which results in a sensible `total` like this one:
  388. [source,console-result]
  389. ----------------------------------------------------------------
  390. {
  391. "hits": {
  392. "total" : {
  393. "value": 0,
  394. "relation": "eq"
  395. }
  396. }
  397. }
  398. ----------------------------------------------------------------
  399. [discrete]
  400. [[docs-delete-by-query-automatic-slice]]
  401. ===== Use automatic slicing
  402. You can also let delete-by-query automatically parallelize using
  403. <<slice-scroll, sliced scroll>> to slice on `_id`. Use `slices` to specify
  404. the number of slices to use:
  405. [source,console]
  406. ----------------------------------------------------------------
  407. POST my-index-000001/_delete_by_query?refresh&slices=5
  408. {
  409. "query": {
  410. "range": {
  411. "http.response.bytes": {
  412. "lt": 2000000
  413. }
  414. }
  415. }
  416. }
  417. ----------------------------------------------------------------
  418. // TEST[setup:my_index_big]
  419. Which you also can verify works with:
  420. [source,console]
  421. ----------------------------------------------------------------
  422. POST my-index-000001/_search?size=0&filter_path=hits.total
  423. {
  424. "query": {
  425. "range": {
  426. "http.response.bytes": {
  427. "lt": 2000000
  428. }
  429. }
  430. }
  431. }
  432. ----------------------------------------------------------------
  433. // TEST[continued]
  434. Which results in a sensible `total` like this one:
  435. [source,console-result]
  436. ----------------------------------------------------------------
  437. {
  438. "hits": {
  439. "total" : {
  440. "value": 0,
  441. "relation": "eq"
  442. }
  443. }
  444. }
  445. ----------------------------------------------------------------
  446. Setting `slices` to `auto` will let {es} choose the number of slices
  447. to use. This setting will use one slice per shard, up to a certain limit. If
  448. there are multiple source data streams or indices, it will choose the number of slices based
  449. on the index or backing index with the smallest number of shards.
  450. Adding `slices` to `_delete_by_query` just automates the manual process used in
  451. the section above, creating sub-requests which means it has some quirks:
  452. * You can see these requests in the
  453. <<tasks,Tasks APIs>>. These sub-requests are "child"
  454. tasks of the task for the request with `slices`.
  455. * Fetching the status of the task for the request with `slices` only contains
  456. the status of completed slices.
  457. * These sub-requests are individually addressable for things like cancellation
  458. and rethrottling.
  459. * Rethrottling the request with `slices` will rethrottle the unfinished
  460. sub-request proportionally.
  461. * Canceling the request with `slices` will cancel each sub-request.
  462. * Due to the nature of `slices` each sub-request won't get a perfectly even
  463. portion of the documents. All documents will be addressed, but some slices may
  464. be larger than others. Expect larger slices to have a more even distribution.
  465. * Parameters like `requests_per_second` and `max_docs` on a request with
  466. `slices` are distributed proportionally to each sub-request. Combine that with
  467. the point above about distribution being uneven and you should conclude that
  468. using `max_docs` with `slices` might not result in exactly `max_docs` documents
  469. being deleted.
  470. * Each sub-request gets a slightly different snapshot of the source data stream or index
  471. though these are all taken at approximately the same time.
  472. [discrete]
  473. [[docs-delete-by-query-rethrottle]]
  474. ===== Change throttling for a request
  475. The value of `requests_per_second` can be changed on a running delete by query
  476. using the `_rethrottle` API. Rethrottling that speeds up the
  477. query takes effect immediately but rethrotting that slows down the query
  478. takes effect after completing the current batch to prevent scroll
  479. timeouts.
  480. [source,console]
  481. --------------------------------------------------
  482. POST _delete_by_query/r1A2WoRbTwKZ516z6NEs5A:36619/_rethrottle?requests_per_second=-1
  483. --------------------------------------------------
  484. Use the <<tasks,tasks API>> to get the task ID. Set `requests_per_second`
  485. to any positive decimal value or `-1` to disable throttling.
  486. ===== Get the status of a delete by query operation
  487. Use the <<tasks,tasks API>> to get the status of a delete by query
  488. operation:
  489. [source,console]
  490. --------------------------------------------------
  491. GET _tasks?detailed=true&actions=*/delete/byquery
  492. --------------------------------------------------
  493. // TEST[skip:No tasks to retrieve]
  494. The response looks like:
  495. [source,console-result]
  496. --------------------------------------------------
  497. {
  498. "nodes" : {
  499. "r1A2WoRbTwKZ516z6NEs5A" : {
  500. "name" : "r1A2WoR",
  501. "transport_address" : "127.0.0.1:9300",
  502. "host" : "127.0.0.1",
  503. "ip" : "127.0.0.1:9300",
  504. "attributes" : {
  505. "testattr" : "test",
  506. "portsfile" : "true"
  507. },
  508. "tasks" : {
  509. "r1A2WoRbTwKZ516z6NEs5A:36619" : {
  510. "node" : "r1A2WoRbTwKZ516z6NEs5A",
  511. "id" : 36619,
  512. "type" : "transport",
  513. "action" : "indices:data/write/delete/byquery",
  514. "status" : { <1>
  515. "total" : 6154,
  516. "updated" : 0,
  517. "created" : 0,
  518. "deleted" : 3500,
  519. "batches" : 36,
  520. "version_conflicts" : 0,
  521. "noops" : 0,
  522. "retries": 0,
  523. "throttled_millis": 0
  524. },
  525. "description" : ""
  526. }
  527. }
  528. }
  529. }
  530. }
  531. --------------------------------------------------
  532. <1> This object contains the actual status. It is just like the response JSON
  533. with the important addition of the `total` field. `total` is the total number
  534. of operations that the reindex expects to perform. You can estimate the
  535. progress by adding the `updated`, `created`, and `deleted` fields. The request
  536. will finish when their sum is equal to the `total` field.
  537. With the task id you can look up the task directly:
  538. [source,console]
  539. --------------------------------------------------
  540. GET /_tasks/r1A2WoRbTwKZ516z6NEs5A:36619
  541. --------------------------------------------------
  542. // TEST[catch:missing]
  543. The advantage of this API is that it integrates with `wait_for_completion=false`
  544. to transparently return the status of completed tasks. If the task is completed
  545. and `wait_for_completion=false` was set on it then it'll come back with
  546. `results` or an `error` field. The cost of this feature is the document that
  547. `wait_for_completion=false` creates at `.tasks/task/${taskId}`. It is up to
  548. you to delete that document.
  549. [discrete]
  550. [[docs-delete-by-query-cancel-task-api]]
  551. ===== Cancel a delete by query operation
  552. Any delete by query can be canceled using the <<tasks,task cancel API>>:
  553. [source,console]
  554. --------------------------------------------------
  555. POST _tasks/r1A2WoRbTwKZ516z6NEs5A:36619/_cancel
  556. --------------------------------------------------
  557. The task ID can be found using the <<tasks,tasks API>>.
  558. Cancellation should happen quickly but might take a few seconds. The task status
  559. API above will continue to list the delete by query task until this task checks that it
  560. has been cancelled and terminates itself.