문서 삭제 API (Delete Document API)
Delete Document API는 인덱스에서 문서를 제거해요. 인덱스 이름과 문서 ID를 모두 지정해야 합니다. 문서가 삭제되면 OpenSearch는 해당 문서의 버전 번호를 증가시키고 다음 세그먼트 병합 때 제거 대상으로 표시합니다.
출처: OpenSearch 문서
본문
Endpoints
DELETE /{index}/_doc/{id}
Path parameters
다음 표는 사용 가능한 경로 파라미터를 보여줘요.
| Parameter | Required | Data type | Description | | id | Required | String | The unique identifier for the document. | | index | Required | String | Name of the target index. |
Query parameters
다음 표는 사용 가능한 쿼리 파라미터를 보여줘요. 모든 쿼리 파라미터는 선택사항이에요.
| Parameter | Data type | Description | | if_seq_no | Integer | Only perform the delete operation if the document has this sequence number. See Optimistic concurrency control. | | if_primary_term | Integer | Only perform the delete operation if the document has this primary term. See Optimistic concurrency control. | | refresh | Boolean or String | Controls when changes made by the delete operation become visible to search. Valid values are true (refresh immediately), false (default, do not refresh), and wait_for (wait for a refresh before responding). See Refresh. | | routing | String | A custom value used to route the operation to a specific shard. Required if the document was indexed with a routing value. See Routing. | | timeout | Time | How long to wait for the primary shard to become available. Default is 1m (1 minute). See Timeout. | | version | Integer | Explicit version number for concurrency control. The specified version must match the current version of the document for the request to succeed. See Versioning. | | version_type | Enum | Specifies the version type: internal (default), external, or external_gte. With external, the version number must be greater than the current version. With external_gte, it must be greater than or equal. See Versioning. | | wait_for_active_shards | String | The number of shard copies that must be active before proceeding with the operation. Default is 1 (only the primary shard). Set to all or any positive integer up to the total number of shards in the index (number_of_replicas+1). See Wait for active shards. |
Example request
다음 예시 요청은 products 인덱스에서 ID가 1인 문서를 삭제해요.
REST Python
DELETE /products/_doc/1
Copy Copy as cURL
response = client.delete(
id = "1",
index = "products"
)
Copy
Example response
다음 예시 응답은 성공적인 삭제 연산을 보여줘요.
{
"_index" : "products",
"_id" : "1",
"_version" : 9,
"result" : "deleted",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 45,
"_primary_term" : 1
}
Response body fields
응답 본문에는 삭제 연산과 영향을 받은 문서에 대한 정보가 들어 있어요.
| Field | Description | | _index | The name of the index from which the document was deleted. | | _id | The unique identifier of the deleted document. | | _version | The new version number of the document after deletion. Each delete operation increments the version number. | | result | The result of the delete operation. Returns deleted if the document was successfully deleted or not_found if the document did not exist. | | _shards | Contains information about the shards involved in the delete operation. | | _shards.total | The total number of shards (primary and replicas) that should have acknowledged the delete operation. | | _shards.successful | The number of shards that successfully processed the delete operation. | | _shards.failed | The number of shards that failed to process the delete operation. When this value is greater than 0, the failures array contains details about the failures. | | _seq_no | The sequence number assigned to the delete operation. Sequence numbers are used for optimistic concurrency control. | | _primary_term | The primary term at the time of the delete operation. Combined with _seq_no, this value is used for optimistic concurrency control. |
Optimistic concurrency control
삭제 연산은 if_seq_no와 if_primary_term 파라미터를 통해 낙관적 동시성 제어를 지원해요. 이 파라미터들을 지정하면 OpenSearch는 문서의 현재 시퀀스 번호와 primary term이 제공된 값과 일치할 때만 삭제 연산을 수행합니다. 불일치하면 OpenSearch는 문서가 마지막으로 조회된 이후 수정됐다는 것을 나타내는 status code 409의 version_conflict_engine_exception 오류를 반환해요.
다음 예시 요청은 시퀀스 번호가 43이고 primary term이 1일 때만 문서를 삭제해요.
REST Python
DELETE /products/_doc/3?if_seq_no=43&if_primary_term=1
Copy Copy as cURL
response = client.delete(
id = "3",
index = "products",
params = { "if_seq_no": "43", "if_primary_term": "1" }
)
Copy 문서의 현재 시퀀스 번호나 primary term이 지정된 값과 일치하지 않으면 OpenSearch는 status code 409의 버전 충돌 오류를 반환해요.
Versioning
삭제를 포함한 문서의 모든 쓰기 연산은 문서의 버전 번호를 증가시킵니다. 문서가 삭제된 후에도 그 버전 번호는 동시성 연산을 지원하기 위해 짧은 시간 동안 유지됩니다. 이 버전 정보가 보존되는 기간은 기본값이 60초인 index.gc_deletes 인덱스 설정으로 제어됩니다. 이를 통해 OpenSearch는 동시 삭제 요청을 제대로 처리하고 복제본(replica) 간 일관성을 유지할 수 있어요.
Automatic index creation
외부 버전 관리 변형(version_type=external 또는 version_type=external_gte)을 사용하면 삭제 연산은 지정된 인덱스가 존재하지 않을 때 그 인덱스를 자동으로 생성합니다. 이 동작은 외부 버전 관리 유형에서만 발생하며 기본 내부 버전 관리에는 적용되지 않아요.
다음 예시 요청은 외부 버전 관리를 사용하므로 auto-created-index 인덱스를 자동으로 생성해요.
REST Python
DELETE /auto-created-index/_doc/1?version=5&version_type=external
Copy Copy as cURL
response = client.delete(
id = "1",
index = "auto-created-index",
params = { "version": "5", "version_type": "external" }
)
Copy 문서가 존재하지 않으므로 연산은 not_found 결과를 반환하지만, 인덱스는 부수 효과로 생성됩니다. 외부 버전 관리가 없으면 존재하지 않는 인덱스에서 문서를 삭제하려는 시도는 index_not_found_exception 오류를 반환해요.
Routing
문서가 특정 routing 값으로 인덱싱되면 OpenSearch는 그 값을 사용해 문서를 저장할 샤드를 결정합니다. 라우팅된 문서를 삭제하려면 인덱싱할 때 사용한 것과 동일한 routing 값을 제공해야 해요. 인덱스의 매핑이 _routing을 required로 설정하고 있는데 routing 값을 지정하지 않고 문서를 삭제하려 하면 OpenSearch는 RoutingMissingException으로 요청을 거부합니다.
다음 예시 요청은 routing 값 electronics로 인덱싱된 문서를 삭제해요.
REST Python
DELETE /products/_doc/2?routing=electronics
Copy Copy as cURL
response = client.delete(
id = "2",
index = "products",
params = { "routing": "electronics" }
)
Copy 올바른 routing 값이 없으면 OpenSearch는 적절한 샤드에서 문서를 찾을 수 없고 삭제 연산은 실패해요.
Distributed execution
삭제 요청을 보내면 OpenSearch는 문서 ID를 해시해서 대상 샤드를 결정합니다. 그런 다음 요청은 해당 샤드 그룹의 기본(primary) 샤드로 라우팅됩니다. 기본 샤드가 삭제 연산을 처리한 뒤에는 변경 사항이 같은 샤드 그룹의 모든 복제 샤드에 복제되어 클러스터 전체의 일관성을 보장해요.
Refresh
기본적으로 삭제된 문서는 기본적으로 1초마다 발생하는 다음 인덱스 리프레시(refresh) 이후에만 검색 연산에서 보입니다. 이 동작은 refresh 파라미터로 제어할 수 있어요.
- false (기본값): 삭제 연산은 즉시 반환되고 변경 사항은 다음 자동 리프레시 이후에 보입니다.
- true: OpenSearch는 삭제 연산 직후 모든 영향받은 샤드를 리프레시해서 변경 사항이 바로 검색 연산에 보이게 합니다. 이 옵션은 성능에 영향을 주므로 드물게 사용해야 해요.
- wait_for: 삭제 연산은 응답을 반환하기 전에 다음 자동 리프레시를 기다려서, API 호출이 완료될 때 변경 사항이 보이도록 보장합니다.
Wait for active shards
wait_for_active_shards 파라미터는 OpenSearch가 삭제 요청을 처리하기 전에 몇 개의 샤드 복사본을 사용할 수 있어야 하는지 제어합니다. 기본값은 1로, 기본 샤드만 활성화되어 있으면 됩니다. all로 설정하면 모든 샤드 복사본(기본 및 복제)이 활성화되어야 하고, 양의 정수를 지정하면 특정 수의 활성 샤드를 요구할 수 있어요. 이 설정은 삭제 연산을 확인하기 전에 복제본이 준비되기를 기다려 데이터 내구성을 보장하는 데 도움이 됩니다.
Timeout
삭제 요청이 도착했을 때 기본 샤드를 사용할 수 없다면(예: 복구나 재배치 중), OpenSearch는 샤드를 사용할 수 있을 때까지 기다립니다. timeout 파라미터는 요청을 실패시키기 전까지 기다릴 시간을 지정해요. 기본 타임아웃은 1분입니다. 지정된 타임아웃 기간 안에 기본 샤드를 사용할 수 없게 되면 OpenSearch는 오류를 반환합니다.
다음 예시 요청은 커스텀 타임아웃을 30초로 설정해요.
REST Python
DELETE /products/_doc/4?timeout=30s
Copy Copy as cURL
response = client.delete(
id = "4",
index = "products",
params = { "timeout": "30s" }
)
Copy
Required permissions
Security 플러그인을 사용한다면 적절한 권한(indices:data/write/delete)을 가지고 있는지 확인하세요.