delete-by-query.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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 index 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`.
  73. ===== Refreshing shards
  74. Specifying the `refresh` parameter refreshes all shards involved in the delete
  75. by query once the request completes. This is different than the delete API's
  76. `refresh` parameter, which causes just the shard that received the delete
  77. request to be refreshed. Unlike the delete API, it does not support
  78. `wait_for`.
  79. [[docs-delete-by-query-task-api]]
  80. ===== Running delete by query asynchronously
  81. If the request contains `wait_for_completion=false`, {es}
  82. performs some preflight checks, launches the request, and returns a
  83. <<tasks,`task`>> you can use to cancel or get the status of the task. {es} creates a
  84. record of this task as a document at `.tasks/task/${taskId}`. When you are
  85. done with a task, you should delete the task document so {es} can reclaim the
  86. space.
  87. ===== Waiting for active shards
  88. `wait_for_active_shards` controls how many copies of a shard must be active
  89. before proceeding with the request. See <<index-wait-for-active-shards>>
  90. for details. `timeout` controls how long each write request waits for unavailable
  91. shards to become available. Both work exactly the way they work in the
  92. <<docs-bulk,Bulk API>>. Delete by query uses scrolled searches, so you can also
  93. specify the `scroll` parameter to control how long it keeps the search context
  94. alive, for example `?scroll=10m`. The default is 5 minutes.
  95. ===== Throttling delete requests
  96. To control the rate at which delete by query issues batches of delete operations,
  97. you can set `requests_per_second` to any positive decimal number. This pads each
  98. batch with a wait time to throttle the rate. Set `requests_per_second` to `-1`
  99. to disable throttling.
  100. Throttling uses a wait time between batches so that the internal scroll requests
  101. can be given a timeout that takes the request padding into account. The padding
  102. time is the difference between the batch size divided by the
  103. `requests_per_second` and the time spent writing. By default the batch size is
  104. `1000`, so if `requests_per_second` is set to `500`:
  105. [source,txt]
  106. --------------------------------------------------
  107. target_time = 1000 / 500 per second = 2 seconds
  108. wait_time = target_time - write_time = 2 seconds - .5 seconds = 1.5 seconds
  109. --------------------------------------------------
  110. Since the batch is issued as a single `_bulk` request, large batch sizes
  111. cause {es} to create many requests and wait before starting the next set.
  112. This is "bursty" instead of "smooth".
  113. [[docs-delete-by-query-slice]]
  114. ===== Slicing
  115. Delete by query supports <<slice-scroll, sliced scroll>> to parallelize the
  116. delete process. This can improve efficiency and provide a
  117. convenient way to break the request down into smaller parts.
  118. Setting `slices` to `auto` chooses a reasonable number for most data streams and indices.
  119. If you're slicing manually or otherwise tuning automatic slicing, keep in mind
  120. that:
  121. * Query performance is most efficient when the number of `slices` is equal to
  122. the number of shards in the index or backing index. If that number is large (for example,
  123. 500), choose a lower number as too many `slices` hurts performance. Setting
  124. `slices` higher than the number of shards generally does not improve efficiency
  125. and adds overhead.
  126. * Delete performance scales linearly across available resources with the
  127. number of slices.
  128. Whether query or delete performance dominates the runtime depends on the
  129. documents being reindexed and cluster resources.
  130. [[docs-delete-by-query-api-path-params]]
  131. ==== {api-path-parms-title}
  132. `<target>`::
  133. (Optional, string)
  134. Comma-separated list of data streams, indices, and index aliases to search.
  135. Wildcard (`*`) expressions are supported.
  136. +
  137. To search all data streams or indices in a cluster, omit this parameter or use
  138. `_all` or `*`.
  139. [[docs-delete-by-query-api-query-params]]
  140. ==== {api-query-parms-title}
  141. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=allow-no-indices]
  142. +
  143. Defaults to `true`.
  144. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=analyzer]
  145. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=analyze_wildcard]
  146. `conflicts`::
  147. (Optional, string) What to do if delete by query hits version conflicts:
  148. `abort` or `proceed`. Defaults to `abort`.
  149. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=default_operator]
  150. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=df]
  151. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=expand-wildcards]
  152. +
  153. Defaults to `open`.
  154. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=from]
  155. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=index-ignore-unavailable]
  156. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=lenient]
  157. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=max_docs]
  158. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=preference]
  159. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=search-q]
  160. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=request_cache]
  161. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=refresh]
  162. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=requests_per_second]
  163. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=routing]
  164. `scroll`::
  165. (Optional, <<time-units,time value>>)
  166. Period to retain the <<scroll-search-context,search context>> for scrolling. See
  167. <<scroll-search-results>>.
  168. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=scroll_size]
  169. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=search_type]
  170. `search_timeout`::
  171. (Optional, <<time-units, time units>>)
  172. Explicit timeout for each search request.
  173. Defaults to no timeout.
  174. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=slices]
  175. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=sort]
  176. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=source]
  177. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=source_excludes]
  178. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=source_includes]
  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. [discrete]
  321. [[docs-delete-by-query-manual-slice]]
  322. ===== Slice manually
  323. Slice a delete by query manually by providing a slice id and total number of
  324. slices:
  325. [source,console]
  326. ----------------------------------------------------------------
  327. POST my-index-000001/_delete_by_query
  328. {
  329. "slice": {
  330. "id": 0,
  331. "max": 2
  332. },
  333. "query": {
  334. "range": {
  335. "http.response.bytes": {
  336. "lt": 2000000
  337. }
  338. }
  339. }
  340. }
  341. POST my-index-000001/_delete_by_query
  342. {
  343. "slice": {
  344. "id": 1,
  345. "max": 2
  346. },
  347. "query": {
  348. "range": {
  349. "http.response.bytes": {
  350. "lt": 2000000
  351. }
  352. }
  353. }
  354. }
  355. ----------------------------------------------------------------
  356. // TEST[setup:my_index_big]
  357. Which you can verify works with:
  358. [source,console]
  359. ----------------------------------------------------------------
  360. GET _refresh
  361. POST my-index-000001/_search?size=0&filter_path=hits.total
  362. {
  363. "query": {
  364. "range": {
  365. "http.response.bytes": {
  366. "lt": 2000000
  367. }
  368. }
  369. }
  370. }
  371. ----------------------------------------------------------------
  372. // TEST[continued]
  373. Which results in a sensible `total` like this one:
  374. [source,console-result]
  375. ----------------------------------------------------------------
  376. {
  377. "hits": {
  378. "total" : {
  379. "value": 0,
  380. "relation": "eq"
  381. }
  382. }
  383. }
  384. ----------------------------------------------------------------
  385. [discrete]
  386. [[docs-delete-by-query-automatic-slice]]
  387. ===== Use automatic slicing
  388. You can also let delete-by-query automatically parallelize using
  389. <<slice-scroll, sliced scroll>> to slice on `_id`. Use `slices` to specify
  390. the number of slices to use:
  391. [source,console]
  392. ----------------------------------------------------------------
  393. POST my-index-000001/_delete_by_query?refresh&slices=5
  394. {
  395. "query": {
  396. "range": {
  397. "http.response.bytes": {
  398. "lt": 2000000
  399. }
  400. }
  401. }
  402. }
  403. ----------------------------------------------------------------
  404. // TEST[setup:my_index_big]
  405. Which you also can verify works with:
  406. [source,console]
  407. ----------------------------------------------------------------
  408. POST my-index-000001/_search?size=0&filter_path=hits.total
  409. {
  410. "query": {
  411. "range": {
  412. "http.response.bytes": {
  413. "lt": 2000000
  414. }
  415. }
  416. }
  417. }
  418. ----------------------------------------------------------------
  419. // TEST[continued]
  420. Which results in a sensible `total` like this one:
  421. [source,console-result]
  422. ----------------------------------------------------------------
  423. {
  424. "hits": {
  425. "total" : {
  426. "value": 0,
  427. "relation": "eq"
  428. }
  429. }
  430. }
  431. ----------------------------------------------------------------
  432. Setting `slices` to `auto` will let {es} choose the number of slices
  433. to use. This setting will use one slice per shard, up to a certain limit. If
  434. there are multiple source data streams or indices, it will choose the number of slices based
  435. on the index or backing index with the smallest number of shards.
  436. Adding `slices` to `_delete_by_query` just automates the manual process used in
  437. the section above, creating sub-requests which means it has some quirks:
  438. * You can see these requests in the
  439. <<tasks,Tasks APIs>>. These sub-requests are "child"
  440. tasks of the task for the request with `slices`.
  441. * Fetching the status of the task for the request with `slices` only contains
  442. the status of completed slices.
  443. * These sub-requests are individually addressable for things like cancellation
  444. and rethrottling.
  445. * Rethrottling the request with `slices` will rethrottle the unfinished
  446. sub-request proportionally.
  447. * Canceling the request with `slices` will cancel each sub-request.
  448. * Due to the nature of `slices` each sub-request won't get a perfectly even
  449. portion of the documents. All documents will be addressed, but some slices may
  450. be larger than others. Expect larger slices to have a more even distribution.
  451. * Parameters like `requests_per_second` and `max_docs` on a request with
  452. `slices` are distributed proportionally to each sub-request. Combine that with
  453. the point above about distribution being uneven and you should conclude that
  454. using `max_docs` with `slices` might not result in exactly `max_docs` documents
  455. being deleted.
  456. * Each sub-request gets a slightly different snapshot of the source data stream or index
  457. though these are all taken at approximately the same time.
  458. [discrete]
  459. [[docs-delete-by-query-rethrottle]]
  460. ===== Change throttling for a request
  461. The value of `requests_per_second` can be changed on a running delete by query
  462. using the `_rethrottle` API. Rethrottling that speeds up the
  463. query takes effect immediately but rethrotting that slows down the query
  464. takes effect after completing the current batch to prevent scroll
  465. timeouts.
  466. [source,console]
  467. --------------------------------------------------
  468. POST _delete_by_query/r1A2WoRbTwKZ516z6NEs5A:36619/_rethrottle?requests_per_second=-1
  469. --------------------------------------------------
  470. Use the <<tasks,tasks API>> to get the task ID. Set `requests_per_second`
  471. to any positive decimal value or `-1` to disable throttling.
  472. ===== Get the status of a delete by query operation
  473. Use the <<tasks,tasks API>> to get the status of a delete by query
  474. operation:
  475. [source,console]
  476. --------------------------------------------------
  477. GET _tasks?detailed=true&actions=*/delete/byquery
  478. --------------------------------------------------
  479. // TEST[skip:No tasks to retrieve]
  480. The response looks like:
  481. [source,console-result]
  482. --------------------------------------------------
  483. {
  484. "nodes" : {
  485. "r1A2WoRbTwKZ516z6NEs5A" : {
  486. "name" : "r1A2WoR",
  487. "transport_address" : "127.0.0.1:9300",
  488. "host" : "127.0.0.1",
  489. "ip" : "127.0.0.1:9300",
  490. "attributes" : {
  491. "testattr" : "test",
  492. "portsfile" : "true"
  493. },
  494. "tasks" : {
  495. "r1A2WoRbTwKZ516z6NEs5A:36619" : {
  496. "node" : "r1A2WoRbTwKZ516z6NEs5A",
  497. "id" : 36619,
  498. "type" : "transport",
  499. "action" : "indices:data/write/delete/byquery",
  500. "status" : { <1>
  501. "total" : 6154,
  502. "updated" : 0,
  503. "created" : 0,
  504. "deleted" : 3500,
  505. "batches" : 36,
  506. "version_conflicts" : 0,
  507. "noops" : 0,
  508. "retries": 0,
  509. "throttled_millis": 0
  510. },
  511. "description" : ""
  512. }
  513. }
  514. }
  515. }
  516. }
  517. --------------------------------------------------
  518. <1> This object contains the actual status. It is just like the response JSON
  519. with the important addition of the `total` field. `total` is the total number
  520. of operations that the reindex expects to perform. You can estimate the
  521. progress by adding the `updated`, `created`, and `deleted` fields. The request
  522. will finish when their sum is equal to the `total` field.
  523. With the task id you can look up the task directly:
  524. [source,console]
  525. --------------------------------------------------
  526. GET /_tasks/r1A2WoRbTwKZ516z6NEs5A:36619
  527. --------------------------------------------------
  528. // TEST[catch:missing]
  529. The advantage of this API is that it integrates with `wait_for_completion=false`
  530. to transparently return the status of completed tasks. If the task is completed
  531. and `wait_for_completion=false` was set on it then it'll come back with
  532. `results` or an `error` field. The cost of this feature is the document that
  533. `wait_for_completion=false` creates at `.tasks/task/${taskId}`. It is up to
  534. you to delete that document.
  535. [discrete]
  536. [[docs-delete-by-query-cancel-task-api]]
  537. ===== Cancel a delete by query operation
  538. Any delete by query can be canceled using the <<tasks,task cancel API>>:
  539. [source,console]
  540. --------------------------------------------------
  541. POST _tasks/r1A2WoRbTwKZ516z6NEs5A:36619/_cancel
  542. --------------------------------------------------
  543. The task ID can be found using the <<tasks,tasks API>>.
  544. Cancellation should happen quickly but might take a few seconds. The task status
  545. API above will continue to list the delete by query task until this task checks that it
  546. has been cancelled and terminates itself.