Delete by Query API (쿼리 조건부 삭제 API)
Delete by Query API는 지정한 쿼리에 일치하는 모든 문서를 인덱스에서 제거하는 API예요. 문서를 하나씩 삭제하는 대신, 검색 조건에 맞는 여러 문서를 단일 요청으로 삭제할 수 있습니다.
이 API는 다음과 같은 상황에서 사용하면 좋아요.
- 날짜 범위나 다른 기준에 따라 시계열 인덱스에서 오래된 데이터 제거
- 특정 패턴에 일치하는 테스트 데이터나 잘못된 문서 정리
- 일정 나이를 초과한 문서를 삭제해 데이터 보존 정책 구현
- 민감한 정보가 담긴 문서 삭제
delete by query 요청을 보내면 OpenSearch는 작업 시작 시 인덱스의 스크롤 컨텍스트를 만들고, 내부 버전 관리(시퀀스 번호와 프라이머리 텀)를 사용해 일치하는 문서를 삭제해요. 작업은 일치하는 모든 문서를 찾기 위해 여러 검색 요청을 순차적으로 수행한 다음, 각 배치마다 일괄 삭제(bulk delete) 요청을 실행합니다. 스냅샷이 찍힌 시점과 삭제 작업이 처리되는 시점 사이에 문서가 변경되면 버전 충돌이 발생하는데, 이때 conflicts 파라미터를 proceed로 설정하지 않으면 해당 문서의 삭제는 실패합니다. 배치 안에서 이후 작업이 실패해도 성공적으로 삭제된 문서는 롤백되지 않습니다.
OpenSearch는 거부된 검색 또는 벌크 요청을 지수 백오프(exponential backoff)와 함께 최대 10번까지 재시도해요. 최대 재시도 횟수에 도달하면 작업이 중단되고 실패한 모든 요청이 응답에 포함됩니다.
참고: OpenSearch는 이 API로 버전 0인 문서를 삭제할 수 없어요. 내부 버전 관리 시스템이 삭제 작업을 올바르게 추적·처리하려면 버전 번호가 0보다 커야 하기 때문입니다.
출처: OpenSearch 문서
본문
Endpoints
POST /{index}/_delete_by_query
Path parameters
다음 표는 사용할 수 있는 경로 파라미터 목록이에요.
| Parameter | Required | Data type | Description | | index | Required | List or String | A comma-separated list of data streams, indexes, and aliases to search. Supports wildcards (*). To search all data streams or indexes, omit this parameter or use * or _all. |
Query parameters
다음 표는 사용할 수 있는 쿼리 파라미터 목록이에요. 모든 쿼리 파라미터는 선택 사항입니다.
| Parameter | Data type | Description | Default | | _source | Boolean or List or String | Set to true or false to return the _source field or not, or a list of fields to return. | N/A | | _source_excludes | List | List of fields to exclude from the returned _source field. | N/A | | _source_includes | List | List of fields to extract and return from the _source field. | N/A | | allow_no_indices | Boolean | If false, the request returns an error if any wildcard expression, index alias, or _all value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. For example, a request targeting foo*,bar* returns an error if an index starts with foo but no index starts with bar. | N/A | | analyze_wildcard | Boolean | If true, wildcard and prefix queries are analyzed. | false | | analyzer | String | Analyzer to use for the query string. | N/A | | conflicts | String | What to do if delete by query hits version conflicts: abort or proceed. Valid values are: - abort: Abort the operation on version conflicts. - proceed: Proceed with the operation on version conflicts. | N/A | | default_operator | String | The default operator for query string query: AND or OR. Valid values are: and, AND, or, and OR. | N/A | | df | String | Field to use as default where no field prefix is given in the query string. | N/A | | expand_wildcards | List or String | Type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. Supports comma-separated values, such as open,hidden. Valid values are: all, open, closed, hidden, none. Valid values are: - all: Match any index, including hidden ones. - closed: Match closed, non-hidden indexes. - hidden: Match hidden indexes. Must be combined with open, closed, or both. - none: Wildcard expressions are not accepted. - open: Match open, non-hidden indexes. | N/A | | from | Integer | Starting offset. | 0 | | ignore_unavailable | Boolean | If false, the request returns an error if it targets a missing or closed index. | N/A | | lenient | Boolean | If true, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. | N/A | | max_docs | Integer | Maximum number of documents to process. Defaults to all documents. | N/A | | preference | String | Specifies the node or shard the operation should be performed on. Random by default. | random | | q | String | Query in the Lucene query string syntax. | N/A | | refresh | Boolean or String | If true, OpenSearch refreshes all shards involved in the delete by query after the request completes. Valid values are: - false: Do not refresh the affected shards. - true: Refresh the affected shards immediately. - wait_for: Wait for the changes to become visible before replying. | N/A | | request_cache | Boolean | If true, the request cache is used for this request. Defaults to the index-level setting. | N/A | | requests_per_second | Float | The throttle for this request in sub-requests per second. | 0 | | routing | List or String | A custom value used to route operations to a specific shard. | N/A | | scroll | String | Period to retain the search context for scrolling. | N/A | | scroll_size | Integer | Size of the scroll request that powers the operation. | 100 | | search_timeout | String | Explicit timeout for each search request. Defaults to no timeout. | N/A | | search_type | String | The type of the search operation. Available options: query_then_fetch, dfs_query_then_fetch. Valid values are: - dfs_query_then_fetch: Documents are scored using global term and document frequencies across all shards. This is usually slower but more accurate. - query_then_fetch: Documents are scored using local term and document frequencies for the shard. This is usually faster but less accurate. | N/A | | size | Integer | Deprecated, use max_docs instead. | N/A | | slices | Integer or String | The number of slices this task should be divided into. Valid values are: - auto: Automatically determine the number of slices. | N/A | | sort | List | A comma-separated list of : pairs. | N/A | | stats | List | Specific tag of the request for logging and statistical purposes. | N/A | | terminate_after | Integer | Maximum number of documents to collect for each shard. If a query reaches this limit, OpenSearch terminates the query early. OpenSearch collects documents before sorting. Use with caution. OpenSearch applies this parameter to each shard handling the request. When possible, let OpenSearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indexes across multiple data tiers. | N/A | | timeout | String | Period each deletion request waits for active shards. | N/A | | version | Boolean | If true, returns the document version as part of a hit. | N/A | | wait_for_active_shards | Integer or String or NULL or String | The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (number_of_replicas+1). Valid values are: - all: Wait for all shards to be active. | N/A | | wait_for_completion | Boolean | If true, the request blocks until the operation is complete. | true |
Request body fields
요청 본문은 선택 사항이지만, 보통 어떤 문서를 삭제할지 지정하는 쿼리를 포함합니다.
| Field | Data type | Description | | query | Object | The query used to select documents for deletion. If not specified, the operation deletes all documents in the target index. For more information about query types, see Query DSL. | | slice | Object | Manually specify slice ID and maximum slices for parallel processing. Contains id (integer, slice number) and max (integer, total number of slices). Optional. | | max_docs | Integer | Maximum number of documents to process. Optional. |
Refreshing shards
refresh 파라미터를 지정하면 delete by query 작업이 완료된 후 관련된 모든 샤드를 새로고침합니다. 이 동작은 삭제 요청을 받은 샤드만 새로고침하는 Delete Document API의 refresh 파라미터와는 달라요. Delete by Query API는 refresh 파라미터의 wait_for 값을 지원하지 않습니다.
Running delete by query asynchronously
delete by query 작업을 비동기로 실행하려면 wait_for_completion 쿼리 파라미터를 false로 설정하세요. OpenSearch는 사전 검사(preflight check)를 수행하고 요청을 실행한 뒤, 진행 상황을 모니터링하거나 작업을 취소하는 데 사용할 수 있는 task ID를 반환합니다. 비동기로 실행하면 OpenSearch는 해당 작업의 기록을 .tasks/task/${taskId} 문서로 만듭니다. 작업이 완료되면 이 작업 문서를 삭제해 공간을 회수할 수 있게 해 주세요.
Waiting for active shards
wait_for_active_shards 파라미터는 요청을 처리하기 전에 활성 상태여야 하는 샤드 사본 수를 제어하고, timeout 파라미터는 각 쓰기 요청이 사용 불가능한 샤드를 기다리는 시간을 제어해요. 이 파라미터들은 Bulk API와 같은 방식으로 동작합니다. Delete by Query는 스크롤 검색을 사용하므로 scroll 파라미터로 검색 컨텍스트가 유지되는 시간을 지정할 수 있으며, 기본 스크롤 시간은 5분입니다.
Throttling delete requests
delete by query가 일괄 삭제 작업을 내보내는 속도를 제어하려면 requests_per_second를 양의 소수로 설정하세요. 각 배치에 대기 시간을 추가해 요청 속도를 조절(throttle)합니다. requests_per_second를 -1로 설정하면 스로틀링을 끌 수 있어요.
스로틀링은 배치 사이의 대기 시간을 사용해서 내부 스크롤 요청에 요청 패딩을 반영한 타임아웃을 줄 수 있게 합니다. 패딩 시간은 배치 크기를 requests_per_second로 나눈 값에서 쓰기 시간을 뺀 차이예요. 기본 배치 크기가 1,000이므로 requests_per_second를 500으로 설정하면:
target_time = 1,000 / 500 per second = 2 seconds
wait_time = target_time - write_time = 2 seconds - 0.5 seconds = 1.5 seconds
각 배치는 단일 벌크 요청으로 실행되기 때문에 배치 크기가 크면 OpenSearch가 많은 요청을 만든 뒤 다음 배치를 시작하기 전에 기다립니다. 이로 인해 높은 활동 시간과 유휴 대기 시간이 번갈아 나타나는 고르지 못한 처리 패턴이 생길 수 있어요.
Slicing for parallel processing
슬라이싱(slicing)을 사용하면 여러 스레드에서 삭제 작업을 병렬로 실행할 수 있어요. 이 방식은 삭제 작업을 독립적인 세그먼트로 나누기 때문에 대규모 삭제에서 성능을 높여 줍니다.
slices를 auto로 설정하면 OpenSearch가 대부분의 인덱스에 적절한 수를 선택합니다. 자동 슬라이싱을 사용하거나 수동으로 조정할 때는 다음 요소들을 고려하세요.
- 슬라이스 수를 샤드 수에 맞추면 쿼리 성능이 최적이에요. 하지만 샤드가 많은(500개 이상) 인덱스에서는 과도한 병렬화 오버헤드로 성능이 저하될 수 있으므로 슬라이스를 더 적게 사용하세요. 슬라이스 수를 샤드 수보다 많이 설정해도 일반적으로 효율이 높아지지 않고 오버헤드만 늘어납니다.
- 삭제 성능은 사용 가능한 리소스에 따라 슬라이스 수와 함께 선형적으로 확장됩니다.
- 런타임에서 쿼리 성능과 삭제 성능 중 무엇이 지배적인지는 삭제하는 문서와 클러스터 가용 리소스에 따라 달라집니다.
Example: Deleting documents matching a query
다음 예제 요청은 movies 인덱스에서 year 필드가 2000보다 작은 모든 문서를 삭제합니다.
REST Python
POST /movies/_delete_by_query
{
"query": {
"range": {
"year": {
"lt": 2000
}
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
body = {
"query": {
"range": {
"year": {
"lt": 2000
}
}
}
}
)
Copy
Example: Deleting with conflicts set to proceed
다음 예제 요청은 쿼리에 일치하는 문서를 삭제하면서 버전 충돌이 발생해도 계속 처리합니다.
REST Python
POST /movies/_delete_by_query?conflicts=proceed
{
"query": {
"match": {
"status": "archived"
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
params = { "conflicts": "proceed" },
body = {
"query": {
"match": {
"status": "archived"
}
}
}
)
Copy
Example: Deleting from multiple indexes
다음 예제 요청은 여러 인덱스에서 쿼리에 일치하는 문서를 삭제합니다.
REST Python
POST /movies,tv-shows/_delete_by_query
{
"query": {
"match_all": {}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies,tv-shows",
body = {
"query": {
"match_all": {}
}
}
)
Copy
Example: Using routing for targeted deletion
다음 예제 요청은 특정 라우팅 값을 가진 샤드로만 삭제 작업을 제한합니다.
REST Python
POST /movies/_delete_by_query?routing=user123
{
"query": {
"term": {
"user_id": "user123"
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
params = { "routing": "user123" },
body = {
"query": {
"term": {
"user_id": "user123"
}
}
}
)
Copy
Example: Using scroll_size to control batch size
다음 예제 요청은 사용자 지정 스크롤 배치 크기 5,000 문서를 사용합니다.
REST Python
POST /movies/_delete_by_query?scroll_size=5000
{
"query": {
"term": {
"genre": "documentary"
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
params = { "scroll_size": "5000" },
body = {
"query": {
"term": {
"genre": "documentary"
}
}
}
)
Copy
Example: Manual slicing for parallel processing
다음 예제 요청들은 병렬 처리를 위해 삭제 작업을 두 개의 슬라이스로 수동 분할합니다.
REST Python
POST /movies/_delete_by_query
{
"slice": {
"id": 0,
"max": 2
},
"query": {
"range": {
"rating": {
"lt": 5
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
body = {
"slice": {
"id": 0,
"max": 2
},
"query": {
"range": {
"rating": {
"lt": 5
}
}
}
}
)
Copy 별도의 요청에서 두 번째 슬라이스를 처리합니다.
REST Python
POST /movies/_delete_by_query
{
"slice": {
"id": 1,
"max": 2
},
"query": {
"range": {
"rating": {
"lt": 5
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
body = {
"slice": {
"id": 1,
"max": 2
},
"query": {
"range": {
"rating": {
"lt": 5
}
}
}
}
)
Copy
Example: Automatic slicing
다음 예제 요청은 자동 슬라이싱을 사용해 삭제 작업을 5개 슬라이스로 병렬화합니다.
REST Python
POST /movies/_delete_by_query?slices=5&refresh=true
{
"query": {
"range": {
"views": {
"lt": 100
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
params = { "slices": "5", "refresh": "true" },
body = {
"query": {
"range": {
"views": {
"lt": 100
}
}
}
}
)
Copy OpenSearch가 최적의 슬라이스 수를 자동으로 결정하게 하려면 slices=auto를 사용하세요.
REST Python
POST /movies/_delete_by_query?slices=auto
{
"query": {
"match": {
"category": "test"
}
}
}
Copy Copy as cURL
response = client.delete_by_query(
index = "movies",
params = { "slices": "auto" },
body = {
"query": {
"match": {
"category": "test"
}
}
}
)
Copy
Example response
다음 예제 응답은 8개 문서를 삭제한 성공적인 delete by query 작업을 보여줍니다.
{
"took": 88,
"timed_out": false,
"total": 8,
"deleted": 8,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0,
"failures": []
}
수동 슬라이싱을 사용하면 응답에는 어떤 슬라이스가 처리되었는지 나타내는 slice_id 필드가 포함됩니다.
{
"took": 13,
"timed_out": false,
"slice_id": 0,
"total": 9,
"deleted": 9,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0,
"failures": []
}
특정 슬라이스 수로 자동 슬라이싱을 사용하면 응답에는 각 슬라이스의 결과를 보여주는 slices 배열이 포함됩니다.
{
"took": 52,
"timed_out": false,
"total": 9,
"deleted": 9,
"batches": 4,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0,
"slices": [
{
"slice_id": 0,
"total": 3,
"deleted": 3,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0
},
{
"slice_id": 1,
"total": 2,
"deleted": 2,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0
},
{
"slice_id": 2,
"total": 0,
"deleted": 0,
"batches": 0,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0
},
{
"slice_id": 3,
"total": 1,
"deleted": 1,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0
},
{
"slice_id": 4,
"total": 3,
"deleted": 3,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0
}
],
"failures": []
}
Response body fields
다음 표는 모든 응답 본문 필드 목록이에요.
| Field | Data type | Description | | took | Integer | The amount of time from the start to the end of the entire operation, in milliseconds. | | timed_out | Boolean | Whether any of the requests executed during the delete by query operation timed out. When set to true, successfully completed deletions still stick and are not rolled back. | | total | Integer | The total number of documents that were successfully processed. | | deleted | Integer | The number of documents that were successfully deleted. | | batches | Integer | The number of scroll batches processed by the delete by query operation. | | version_conflicts | Integer | The number of version conflicts encountered by the delete by query operation. Occurs when a document changes between the time the snapshot is taken and when the delete operation is processed. | | noops | Integer | The number of no-operation requests. This field always returns 0 for delete by query. It exists to maintain response structure consistency with Update by Query and Reindex APIs. | | retries | Object | The number of retries attempted by the delete by query operation. Contains bulk (number of bulk action retries) and search (number of search action retries). | | throttled_millis | Integer | The amount of time the request was throttled to conform to requests_per_second, in milliseconds. | | requests_per_second | Float | The number of requests per second effectively executed during the delete by query operation. | | throttled_until_millis | Integer | The amount of time until the next throttled request will be executed, in milliseconds. Always equals 0 in a completed delete by query response. This field has meaning only when using the Tasks API to monitor an ongoing operation, where it indicates the next time a throttled request will execute. | | slice_id | Integer | The slice number for this response. Only present when using manual slicing. Indicates which slice of the operation this response represents. | | slices | Array | An array of slice results when using automatic slicing with a specific number. Each element contains the same response fields as the main response, showing the results for that individual slice. | | failures | Array | An array of failures if any unrecoverable errors occurred during the operation. If this array is not empty, the request aborted because of those failures. Delete by query is implemented using batches, and any failure causes the entire process to abort, but all failures in the current batch are collected in this array. You can use the conflicts parameter set to proceed to prevent the operation from aborting on version conflicts. |
Managing delete by query tasks
wait_for_completion=false로 설정해 delete by query 작업을 비동기로 실행하면 OpenSearch는 작업을 모니터링하거나 수정 또는 취소하는 데 사용할 수 있는 task ID를 반환합니다.
Retrieving the status of a delete by query operation
delete by query 작업의 상태를 가져오려면 Tasks API를 사용하세요.
GET _tasks?detailed=true&actions=*/delete/byquery
copy
응답에는 실행 중인 모든 delete by query 작업의 상태가 포함됩니다. 특정 작업의 상태를 가져오려면 task ID를 사용하세요.
GET _tasks/{task_id}
copy
응답에는 작업 진행 상황에 대한 상세 정보가 포함됩니다.
{
"nodes": {
"node_id": {
"tasks": {
"task_id": {
"status": {
"total": 1000,
"updated": 0,
"created": 0,
"deleted": 450,
"batches": 5,
"version_conflicts": 0,
"noops": 0,
"retries": 0,
"throttled_millis": 0
}
}
}
}
}
}
total 필드는 delete by query 작업이 수행하기로 예상한 총 작업 수를 나타냅니다. deleted 필드를 total 필드와 비교하면 진행 상황을 추정할 수 있어요. deleted가 total과 같아지면 작업이 완료된 것입니다.
Changing throttling for a running operation
실행 중인 delete by query 작업의 스로틀링을 변경하려면 Rethrottle Task API를 task ID와 함께 사용하세요.
POST _delete_by_query/{task_id}/_rethrottle?requests_per_second=100
copy
requests_per_second를 양의 소수 값 또는 -1로 설정해 스로틀링을 끌 수 있어요. 작업을 빨라지게 하는 리스로틀링은 즉시 적용됩니다. 작업을 느려지게 하는 리스로틀링은 현재 배치가 끝난 후 적용되어 스크롤 타임아웃을 방지합니다.
Canceling a delete by query operation
실행 중인 delete by query 작업을 취소하려면 task cancel API를 사용하세요.
POST _tasks/{task_id}/_cancel
copy
취소는 빠르게 일어나지만 몇 초가 걸릴 수 있어요. Tasks API는 취소된 것을 확인하고 스스로 종료할 때까지 delete by query 작업을 계속 나열합니다. 슬라이스와 함께 delete by query 작업을 취소하면 OpenSearch는 각 하위 요청을 취소합니다.
Required permissions
Security 플러그인을 사용한다면 indices:data/write/delete/byquery 권한이 있는지 확인하세요.
더 알아보기 (Learn more)
대량 삭제 작업은 클러스터에 부하를 줄 수 있으니 주의가 필요해요. 슬라이싱과 스로틀링을 적절히 조합하면 대규모 삭제를 안전하게 수행할 수 있습니다. 비동기 실행 시 Tasks API로 진행 상황을 추적하고, Update by Query나 Reindex API와의 응답 구조 차이도 함께 알아두면 운영에 유용합니다.