벌크 API - gRPC (Bulk API (gRPC))
3.0에서 도입
gRPC Bulk API는 HTTP Bulk API의 효율적인 바이너리 인코딩 대안을 제공합니다. 인덱싱, 업데이트, 삭제 같은 여러 문서 연산을 단 한 번의 호출로 수행할 수 있습니다. 이 서비스는 프로토콜 버퍼를 사용하며 매개변수와 구조 측면에서 REST API를 그대로 반영합니다.
출처: OpenSearch 문서
본문
Prerequisite
gRPC 요청을 제출하려면 클라이언트 측에 protobuf 세트가 있어야 합니다. protobuf를 얻는 방법은 Using gRPC APIs를 참고하세요.
gRPC service and method
gRPC 문서 API는 DocumentService에 위치합니다.
DocumentService 내의 Bulk gRPC 메서드를 호출해 벌크 요청을 제출할 수 있습니다. 이 메서드는 BulkRequest를 받아 BulkResponse를 반환합니다.
Document format
gRPC에서는 문서를 bytes로 제공하고 반환해야 합니다. gRPC 요청에서 문서를 제공하려면 Base64 인코딩을 사용하세요.
예를 들어 일반 Bulk API 요청에서 다음과 같은 문서를 생각해 보겠습니다.
"doc": "{\"title\": \"Inception\", \"year\": 2010}"
gRPC Bulk API 요청에서는 같은 문서를 Base64 인코딩으로 제공합니다.
"doc": "eyJ0aX...MTB9"
BulkRequest fields
BulkRequest 메시지는 gRPC 벌크 연산의 최상위 컨테이너입니다. 다음 필드를 받습니다.
| Field | Protobuf type | Description | | bulk_request_body | repeated BulkRequestBody | 벌크 연산 목록으로, 각각은 연산 유형(index/create/update/delete) 중 하나를 담고 있습니다. 필수입니다. | | index | string | bulk_request_body 에서 재정의하지 않는 한 모든 연산의 기본 인덱스입니다. BulkRequest 에서 인덱스를 지정하면 BulkRequestBody 에 포함할 필요가 없습니다. 선택 사항입니다. | | x_source | SourceConfigParam | 응답에서 전체 _source 를 반환할지, _source 를 반환하지 않을지, _source 에서 특정 필드만 반환할지 제어합니다. 선택 사항입니다. | | x_source_excludes | repeated string | 소스에서 제외할 필드입니다. 선택 사항입니다. | | x_source_includes | repeated string | 소스에서 포함할 필드입니다. 선택 사항입니다. | | pipeline | string | 전처리 ingest pipeline의 ID입니다. 선택 사항입니다. | | refresh | Refresh | 인덱싱 후 샤드를 refresh할지 여부입니다. 선택 사항입니다. | | require_alias | bool | true 이면 동작이 별칭을 대상으로 해야 합니다. 선택 사항입니다. | | routing | string | 샤드 할당을 위한 라우팅 값입니다. 선택 사항입니다. | | timeout | string | 타임아웃 기간(예: 1m)입니다. 선택 사항입니다. | | type (Deprecated) | string | 문서 유형(항상 _doc)입니다. 선택 사항입니다. | | wait_for_active_shards | WaitForActiveShards | 기다릴 최소 활성 샤드 수입니다. 선택 사항입니다. | | global_params | GlobalParams | 요청에 대한 전역 매개변수입니다. 선택 사항입니다. |
BulkRequestBody fields
BulkRequestBody 메시지는 BulkRequest 내의 단일 문서 수준 연산을 나타냅니다. 다음 필드를 받습니다.
| Field | Protobuf type | Description | | operation_container | OperationContainer | 수행할 연산(index, create, update, delete)입니다. 필수입니다. | | update_action | UpdateAction | 추가적인 update 전용 옵션입니다. 선택 사항입니다. | | object | bytes | create 및 index 연산과 함께 사용되는 전체 문서 내용입니다. 선택 사항입니다. |
OperationContainer fields
OperationContainer 메시지는 정확히 하나의 연산 유형을 담고 있습니다. 다음 필드를 받습니다.
| Field | Protobuf type | Description | | index | IndexOperation | 문서를 인덱싱합니다. 이미 존재하면 그 문서를 교체합니다. | | create | WriteOperation | 새 문서를 생성합니다. 문서가 이미 존재하면 실패합니다. | | update | UpdateOperation | 문서를 부분 업데이트하거나 upsert/script 옵션을 사용합니다. | | delete | DeleteOperation | ID로 문서를 삭제합니다. |
UpdateAction fields
UpdateAction 메시지는 update 연산에 대한 추가 옵션을 제공합니다. 다음 필드를 받습니다.
| Field | Protobuf type | Description | | detect_noop | bool | true 이면 문서 내용이 바뀌지 않았을 때 업데이트를 건너뜁니다. 선택 사항이며 기본값은 true 입니다. | | doc | bytes | update 연산을 위한 부분 또는 전체 문서 데이터입니다. 선택 사항입니다. | | doc_as_upsert | bool | true 이면 대상 문서가 존재하지 않을 때 그 문서를 전체 upsert 문서로 취급합니다. update 연산에서만 유효합니다. 선택 사항입니다. | | script | Script | 문서에 적용할 스크립트입니다(update와 함께 사용). 선택 사항입니다. | | scripted_upsert | bool | true 이면 문서 존재 여부와 상관없이 스크립트를 실행합니다. 선택 사항입니다. | | upsert | bytes | 대상이 존재하지 않을 때 사용할 전체 문서입니다. script와 함께 사용됩니다. 선택 사항입니다. | | x_source | SourceConfig | 문서 소스를 가져오거나 필터링하는 방법을 제어합니다. 선택 사항입니다. |
Create
WriteOperation은 아직 존재하지 않을 때만 새 문서를 추가합니다.
문서 자체는 BulkRequestBody 메시지의 object 필드에 제공해야 합니다.
다음 선택적 필드도 제공할 수 있습니다.
| Field | Protobuf type | Description | | x_id | string | 문서 ID입니다. 생략하면 자동 생성됩니다. 선택 사항입니다. | | x_index | string | 대상 인덱스입니다. BulkRequest 에서 전역으로 설정되지 않았다면 필수입니다. 선택 사항입니다. | | routing | string | 샤드 배치를 제어하는 데 사용하는 커스텀 라우팅 값입니다. 선택 사항입니다. | | pipeline | string | 전처리 ingest pipeline의 ID입니다. 선택 사항입니다. | | require_alias | bool | true 이면 모든 동작이 인덱스가 아닌 인덱스 별칭을 대상으로 해야 합니다. 기본값은 false 입니다. 선택 사항입니다. |
Example request
다음 예제는 create 연산이 포함된 벌크 요청을 보여 줍니다. movies 인덱스에 ID tt1375666 인 문서를 생성합니다. Base64 인코딩으로 제공된 문서 내용은 {"title": "Inception", "year": 2010} 을 나타냅니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"create": {
"x_index": "movies",
"x_id": "tt1375666"
}
},
"object": "eyJ0aX...MTB9"
}
]
}
Delete
DeleteOperation은 ID로 문서를 제거합니다. 다음 필드를 받습니다.
| Field | Protobuf type | Description | | x_id | string | 삭제할 문서의 ID입니다. 필수입니다. | | x_index | string | 대상 인덱스입니다. BulkRequest 에서 전역으로 설정되지 않았다면 필수입니다. 선택 사항입니다. | | routing | string | 샤드 배치를 제어하는 데 사용하는 커스텀 라우팅 값입니다. 선택 사항입니다. | | if_primary_term | int64 | 동시성 제어에 사용됩니다. 문서의 주 용어가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | if_seq_no | int64 | 동시성 제어에 사용됩니다. 문서의 시퀀스 번호가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | version | int64 | 동시성 제어를 위한 명시적 문서 버전입니다. 선택 사항입니다. | | version_type | VersionType | 버전 일치 동작을 제어합니다. 선택 사항입니다. |
Example request
다음 예제는 delete 연산이 포함된 벌크 요청을 보여 줍니다. movies 인덱스에서 ID tt1392214 인 문서를 삭제합니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"delete": {
"x_index": "movies",
"x_id": "tt1392214"
}
}
}
]
}
copy
Index
IndexOperation은 문서를 생성하거나 덮어씁니다. ID가 제공되지 않으면 하나가 생성됩니다.
문서 자체는 BulkRequestBody 메시지의 object 필드에 제공됩니다.
다음 선택적 필드도 제공할 수 있습니다.
| Field | Protobuf type | Description | | x_id | string | 문서 ID입니다. 생략하면 자동 생성됩니다. 선택 사항입니다. | | x_index | string | 대상 인덱스입니다. BulkRequest 에서 전역으로 설정되지 않은 경우에만 필수입니다. | | routing | string | 샤드 배치를 제어하는 데 사용하는 커스텀 라우팅 값입니다. 선택 사항입니다. | | if_primary_term | int64 | 동시성 제어에 사용됩니다. 문서의 주 용어가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | if_seq_no | int64 | 동시성 제어에 사용됩니다. 문서의 시퀀스 번호가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | op_type | OpType | 연산 유형입니다. 덮어쓰기 동작을 제어합니다. 유효한 값은 index (기본값)와 create 입니다. 선택 사항입니다. | | version | int64 | 동시성 제어를 위한 명시적 문서 버전입니다. 선택 사항입니다. | | version_type | VersionType | 버전 일치 동작을 제어합니다. 선택 사항입니다. | | pipeline | string | 전처리 ingest pipeline의 ID입니다. 선택 사항입니다. | | require_alias | bool | true 이면 모든 동작이 인덱스가 아닌 인덱스 별칭을 대상으로 해야 합니다. 기본값은 false 입니다. 선택 사항입니다. |
Example request
다음 예제는 index 연산이 포함된 벌크 요청을 보여 줍니다. ID tt0468569 인 Base64 인코딩 문서를 movies 인덱스에 인덱싱합니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"index": {
"x_index": "movies",
"x_id": "tt0468569"
}
},
"object": "eyJ0aX...MDh9"
}
]
}
copy
Update
UpdateOperation은 부분 문서 업데이트를 수행합니다.
업데이트 옵션은 BulkRequestBody 메시지 내의 update_action 필드에 제공됩니다.
다음 표에 나열된 모든 UpdateOperation 필드는 x_id 를 제외하면 모두 선택 사항입니다.
| Field | Protobuf type | Description | | x_id | string | 업데이트할 문서의 ID입니다. 필수입니다. | | x_index | string | 대상 인덱스입니다. BulkRequest 에서 전역으로 설정되지 않았다면 필수입니다. 선택 사항입니다. | | routing | string | 샤드 배치를 제어하는 데 사용하는 커스텀 라우팅 값입니다. 선택 사항입니다. | | if_primary_term | int64 | 동시성 제어에 사용됩니다. 문서의 주 용어가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | if_seq_no | int64 | 동시성 제어에 사용됩니다. 문서의 시퀀스 번호가 이 값과 일치할 때만 연산이 실행됩니다. 선택 사항입니다. | | require_alias | bool | true 이면 모든 동작이 인덱스가 아닌 인덱스 별칭을 대상으로 해야 합니다. 기본값은 false 입니다. 선택 사항입니다. | | retry_on_conflict | int32 | 버전 충돌이 발생했을 때 연산을 재시도할 횟수입니다. 선택 사항입니다. |
Example request
다음 예제는 update 연산이 포함된 벌크 요청을 보여 줍니다. movies 인덱스의 ID tt1375666 인 문서를 {"year": 2011} 로 업데이트합니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"update": {
"x_index": "movies",
"x_id": "tt1375666"
}
},
"update_action": {
"doc": "eyJ5ZW...xMX0=",
"detect_noop": true
}
}
]
}
copy
Upsert
upsert 연산은 문서가 이미 존재하면 업데이트하고, 그렇지 않으면 제공된 문서 내용으로 새 문서를 생성합니다.
문서를 upsert하려면 UpdateOperation 을 제공하고 BulkRequestBody 에서 doc_as_upsert 를 true 로 지정하세요. upsert할 문서는 doc 필드에 제공해야 합니다.
Example request
다음 예제는 upsert 연산이 포함된 벌크 요청을 보여 줍니다. movies 인덱스의 ID tt1375666 인 문서의 year 필드를 {"year": 2012} 로 업데이트합니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"update": {
"x_index": "movies",
"x_id": "tt1375666"
}
},
"update_action": {
"doc": "eyJ5ZW...xMn0=",
"doc_as_upsert": true
}
}
]
}
copy
Script
저장된 또는 인라인 스크립트를 실행해 문서를 수정합니다.
스크립트를 지정하려면 UpdateOperation 과 BulkRequestBody 의 script 필드를 제공하세요.
Example request
다음 예제는 script 연산이 포함된 벌크 요청을 보여 줍니다. movies 인덱스의 ID tt1375666 인 문서의 year 필드를 1만큼 증가시킵니다.
{
"index": "movies",
"bulk_request_body": [
{
"operation_container": {
"update": {
"x_index": "movies",
"x_id": "tt1375666"
}
},
"update_action": {
"script": {
"inline": {
"source": "ctx._source.year += 1",
"lang": {
"builtin": "BUILTIN_SCRIPT_LANGUAGE_PAINLESS"
}
}
}
}
}
]
}
copy
Response fields
gRPC Bulk API는 다음 응답 필드를 제공합니다.
BulkResponse fields
BulkResponse 메시지는 Bulk gRPC 메서드에서 직접 반환되며 벌크 연산의 요약과 항목별 결과를 제공합니다. 다음 필드를 포함합니다.
| Field | Protobuf type | Description | | errors | bool | 벌크 요청의 연산 중 하나라도 실패했는지 여부를 나타냅니다. 연산 하나라도 실패하면 응답의 errors 필드는 true 가 됩니다. 더 자세한 정보를 위해 개별 Item 동작들을 순회할 수 있습니다. | | items | repeated Item | 제출된 순서대로의 벌크 요청 내 모든 연산의 결과입니다. | | took | int64 | 벌크 요청을 처리하는 데 걸린 시간(밀리초)입니다. | | ingest_took | int64 | ingest pipeline을 통해 문서를 처리하는 데 걸린 시간(밀리초)입니다. |
Item fields
응답의 각 Item 은 요청의 단일 연산에 해당합니다. 각 연산에 대해 다음 필드 중 하나만 제공됩니다.
| Field | Protobuf type | Description | | create | ResponseItem | CreateOperation 의 결과입니다. | | delete | ResponseItem | DeleteOperation 의 결과입니다. | | index | ResponseItem | IndexOperation 의 결과입니다. | | update | ResponseItem | UpdateOperation 의 결과입니다. |
ResponseItem fields
각 ResponseItem 은 요청의 단일 연산에 해당합니다. 다음 필드를 포함합니다.
| Field | Protobuf type | Description | | type | string | 문서 유형입니다. | | id | string | 연산과 연결된 문서 ID입니다. | | index | string | 연산과 연결된 인덱스의 이름입니다. 데이터 스트림을 대상으로 했다면 이 값은 backing index입니다. | | status | int32 | 연산에 대해 반환된 HTTP 상태 코드입니다. (참고: 이 필드는 향후 gRPC 코드로 대체될 수 있습니다.) | | error | ErrorCause | 실패한 연산에 대한 추가 정보를 담고 있습니다. | | primary_term | int64 | 문서에 할당된 주 용어입니다. | | result | string | 연산 결과입니다. 유효한 값은 created, deleted, updated 입니다. | | seq_no | int64 | 버전 순서를 유지하기 위해 문서에 할당된 시퀀스 번호입니다. | | shards | ShardInfo | 연산에 대한 샤드 정보입니다(성공한 동작에 대해서만 반환). | | version | int64 | 문서 버전입니다(성공한 동작에 대해서만 반환). | | forced_refresh | bool | true 이면 연산 직후 문서가 즉시 보이도록 강제합니다. | | get | InlineGetDictUserDefined | 요청했다면 인라인 get 에서 반환된 문서 소스를 포함합니다. |
InlineGetDictUserDefined fields
InlineGetDictUserDefined 메시지는 인라인 get 연산에서 반환된 문서 소스를 담고 있습니다.
| Field | Protobuf type | Description | | metadata_fields | optional ObjectMap | 문서의 메타데이터 필드입니다. | | fields | optional ObjectMap | 문서의 저장된 필드입니다. | | found | bool | 문서가 존재하는지 여부입니다. | | x_seq_no | optional int64 | 문서의 시퀀스 번호입니다. | | x_primary_term | optional int64 | 문서의 주 용어입니다. | | x_routing | optional string | 문서의 라우팅 값입니다. | | x_source | optional bytes | 문서의 소스 데이터입니다. |
Example response
{
"errors": false,
"items": [
{
"index": {
"x_id": "2",
"x_index": "my_index",
"status": 201,
"x_primary_term": 1,
"result": "created",
"x_seq_no": 0,
"x_shards": {
"successful": 1,
"total": 2
},
"x_version": 1,
"forced_refresh": true
}
},
{
"create": {
"x_id": "1",
"x_index": "my_index",
"status": 201,
"x_primary_term": 1,
"result": "created",
"x_seq_no": 0,
"x_shards": {
"successful": 1,
"total": 2
},
"x_version": 1,
"forced_refresh": true
}
},
{
"update": {
"x_id": "2",
"x_index": "my_index",
"status": 200,
"x_primary_term": 1,
"result": "updated",
"x_seq_no": 1,
"x_shards": {
"successful": 1,
"total": 2
},
"x_version": 2,
"forced_refresh": true,
"get": {
"found": true,
"x_seq_no": 1,
"x_primary_term": 1,
"x_source": "e30="
}
}
},
{
"delete": {
"x_id": "2",
"x_index": "my_index",
"status": 200,
"x_primary_term": 1,
"result": "deleted",
"x_seq_no": 2,
"x_shards": {
"successful": 1,
"total": 2
},
"x_version": 3,
"forced_refresh": true
}
}
],
"took": 87,
"ingest_took": 0
}
copy
Java gRPC client example
다음 예제는 예시 벌크 gRPC 요청을 제출한 뒤 벌크 응답에 오류가 있었는지 확인하는 Java 클라이언트 프로그램을 보여 줍니다.
import org.opensearch.protobufs.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import com.google.protobuf.ByteString;
public class BulkClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400)
.usePlaintext()
.build();
DocumentServiceGrpc.DocumentServiceBlockingStub stub = DocumentServiceGrpc.newBlockingStub(channel);
// Create an index operation
IndexOperation indexOp = IndexOperation.newBuilder()
.setXIndex("my-index")
.setXId("1")
.build();
BulkRequestBody indexBody = BulkRequestBody.newBuilder()
.setOperationContainer(OperationContainer.newBuilder().setIndex(indexOp).build())
.setObject(ByteString.copyFromUtf8("{\"field\": \"value\"}"))
.build();
// Create a delete operation
DeleteOperation deleteOp = DeleteOperation.newBuilder()
.setXIndex("my-index")
.setXId("2")
.build();
BulkRequestBody deleteBody = BulkRequestBody.newBuilder()
.setOperationContainer(OperationContainer.newBuilder().setDelete(deleteOp).build())
.build();
// Build the bulk request
BulkRequest request = BulkRequest.newBuilder()
.setIndex("my-index")
.addBulkRequestBody(indexBody)
.addBulkRequestBody(deleteBody)
.build();
// Execute the bulk request
try {
BulkResponse response = stub.bulk(request);
// Handle the response
System.out.println("Bulk errors: " + response.getErrors());
System.out.println("Bulk took: " + response.getTook() + " ms");
if (response.hasIngestTook()) {
System.out.println("Ingest took: " + response.getIngestTook() + " ms");
}
// Process individual items
for (Item item : response.getItemsList()) {
if (item.hasIndex()) {
System.out.println("Index operation: " + item.getIndex().getStatus());
} else if (item.hasDelete()) {
System.out.println("Delete operation: " + item.getDelete().getStatus());
} else if (item.hasCreate()) {
System.out.println("Create operation: " + item.getCreate().getStatus());
} else if (item.hasUpdate()) {
System.out.println("Update operation: " + item.getUpdate().getStatus());
}
}
} catch (io.grpc.StatusRuntimeException e) {
System.err.println("gRPC request failed with status: " + e.getStatus());
System.err.println("Error message: " + e.getMessage());
}
channel.shutdown();
}
}
copy
Python gRPC client example
다음 예제는 Python 클라이언트 애플리케이션으로 같은 요청을 보내는 방법을 보여 줍니다.
먼저 pip 를 사용해 opensearch-protobufs 패키지를 설치합니다.
pip install opensearch-protobufs==1.2.0
copy
요청을 보내려면 다음 코드를 사용하세요.
import grpc
from opensearch.protobufs.schemas import *
from opensearch.protobufs.services import DocumentServiceStub
channel = grpc.insecure_channel(
target="localhost:9400",
)
document_stub = DocumentServiceStub(channel)
# Add documents to a request body
requestBody = BulkRequestBody(
operation_container=OperationContainer(index=IndexOperation())
)
requestBody.object = "{\"field\": \"value\"}".encode('utf-8')
# Append to a bulk request
request = BulkRequest()
request.index = "my-index"
request.bulk_request_body.append(requestBody)
# Send request and handle response
try:
response = document_stub.Bulk(request=request)
if response.items:
print("Received {} response items".format(len(response.items)))
print(response.items)
except grpc.RpcError as e:
if e.code() == StatusCode.UNAVAILABLE:
print("Failed to reach server: {}".format(e))
elif e.code() == StatusCode.PERMISSION_DENIED:
print("Permission denied: {}".format(e))
elif e.code() == StatusCode.INVALID_ARGUMENT:
print("Invalid argument: {}".format(e))
finally:
channel.close()
copy