Search in sources :

Example 1 with BulkRequest

use of org.opensearch.action.bulk.BulkRequest in project OpenSearch by opensearch-project.

the class RequestConverters method bulk.

static Request bulk(BulkRequest bulkRequest) throws IOException {
    Request request = new Request(HttpPost.METHOD_NAME, "/_bulk");
    Params parameters = new Params();
    parameters.withTimeout(bulkRequest.timeout());
    parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy());
    parameters.withPipeline(bulkRequest.pipeline());
    parameters.withRouting(bulkRequest.routing());
    // Bulk API only supports newline delimited JSON or Smile. Before executing
    // the bulk, we need to check that all requests have the same content-type
    // and this content-type is supported by the Bulk API.
    XContentType bulkContentType = null;
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> action = bulkRequest.requests().get(i);
        DocWriteRequest.OpType opType = action.opType();
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            bulkContentType = enforceSameContentType((IndexRequest) action, bulkContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) action;
            if (updateRequest.doc() != null) {
                bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType);
            }
            if (updateRequest.upsertRequest() != null) {
                bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType);
            }
        }
    }
    if (bulkContentType == null) {
        bulkContentType = XContentType.JSON;
    }
    final byte separator = bulkContentType.xContent().streamSeparator();
    final ContentType requestContentType = createContentType(bulkContentType);
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    for (DocWriteRequest<?> action : bulkRequest.requests()) {
        DocWriteRequest.OpType opType = action.opType();
        try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) {
            metadata.startObject();
            {
                metadata.startObject(opType.getLowercase());
                if (Strings.hasLength(action.index())) {
                    metadata.field("_index", action.index());
                }
                if (Strings.hasLength(action.id())) {
                    metadata.field("_id", action.id());
                }
                if (Strings.hasLength(action.routing())) {
                    metadata.field("routing", action.routing());
                }
                if (action.version() != Versions.MATCH_ANY) {
                    metadata.field("version", action.version());
                }
                VersionType versionType = action.versionType();
                if (versionType != VersionType.INTERNAL) {
                    if (versionType == VersionType.EXTERNAL) {
                        metadata.field("version_type", "external");
                    } else if (versionType == VersionType.EXTERNAL_GTE) {
                        metadata.field("version_type", "external_gte");
                    }
                }
                if (action.ifSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) {
                    metadata.field("if_seq_no", action.ifSeqNo());
                    metadata.field("if_primary_term", action.ifPrimaryTerm());
                }
                if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
                    IndexRequest indexRequest = (IndexRequest) action;
                    if (Strings.hasLength(indexRequest.getPipeline())) {
                        metadata.field("pipeline", indexRequest.getPipeline());
                    }
                } else if (opType == DocWriteRequest.OpType.UPDATE) {
                    UpdateRequest updateRequest = (UpdateRequest) action;
                    if (updateRequest.retryOnConflict() > 0) {
                        metadata.field("retry_on_conflict", updateRequest.retryOnConflict());
                    }
                    if (updateRequest.fetchSource() != null) {
                        metadata.field("_source", updateRequest.fetchSource());
                    }
                }
                metadata.endObject();
            }
            metadata.endObject();
            BytesRef metadataSource = BytesReference.bytes(metadata).toBytesRef();
            content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length);
            content.write(separator);
        }
        BytesRef source = null;
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest indexRequest = (IndexRequest) action;
            BytesReference indexSource = indexRequest.source();
            XContentType indexXContentType = indexRequest.getContentType();
            try (XContentParser parser = XContentHelper.createParser(/*
                         * EMPTY and THROW are fine here because we just call
                         * copyCurrentStructure which doesn't touch the
                         * registry or deprecation.
                         */
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, indexSource, indexXContentType)) {
                try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) {
                    builder.copyCurrentStructure(parser);
                    source = BytesReference.bytes(builder).toBytesRef();
                }
            }
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            source = XContentHelper.toXContent((UpdateRequest) action, bulkContentType, false).toBytesRef();
        }
        if (source != null) {
            content.write(source.bytes, source.offset, source.length);
            content.write(separator);
        }
    }
    request.addParameters(parameters.asMap());
    request.setEntity(new NByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType));
    return request;
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) ContentType(org.apache.http.entity.ContentType) XContentType(org.opensearch.common.xcontent.XContentType) UpdateRequest(org.opensearch.action.update.UpdateRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) CountRequest(org.opensearch.client.core.CountRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ClusterHealthRequest(org.opensearch.action.admin.cluster.health.ClusterHealthRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IndexRequest(org.opensearch.action.index.IndexRequest) VersionType(org.opensearch.index.VersionType) XContentType(org.opensearch.common.xcontent.XContentType) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) DocWriteRequest(org.opensearch.action.DocWriteRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) BytesRef(org.apache.lucene.util.BytesRef) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 2 with BulkRequest

use of org.opensearch.action.bulk.BulkRequest in project OpenSearch by opensearch-project.

the class BulkRequestWithGlobalParametersIT method testIndexGlobalAndPerRequest.

@SuppressWarnings("unchecked")
public void testIndexGlobalAndPerRequest() throws IOException {
    BulkRequest request = new BulkRequest("global_index");
    request.add(new IndexRequest("local_index").id("1").source(XContentType.JSON, "field", "bulk1"));
    request.add(// will take global index
    new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2"));
    bulk(request);
    Iterable<SearchHit> hits = searchAll("local_index", "global_index");
    assertThat(hits, containsInAnyOrder(both(hasId("1")).and(hasIndex("local_index")), both(hasId("2")).and(hasIndex("global_index"))));
}
Also used : SearchHit(org.opensearch.search.SearchHit) BulkRequest(org.opensearch.action.bulk.BulkRequest) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 3 with BulkRequest

use of org.opensearch.action.bulk.BulkRequest in project OpenSearch by opensearch-project.

the class BulkRequestWithGlobalParametersIT method testGlobalIndex.

public void testGlobalIndex() throws IOException {
    BulkRequest request = new BulkRequest("global_index");
    request.add(new IndexRequest().id("1").source(XContentType.JSON, "field", "bulk1"));
    request.add(new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2"));
    bulk(request);
    Iterable<SearchHit> hits = searchAll("global_index");
    assertThat(hits, everyItem(hasIndex("global_index")));
}
Also used : SearchHit(org.opensearch.search.SearchHit) BulkRequest(org.opensearch.action.bulk.BulkRequest) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 4 with BulkRequest

use of org.opensearch.action.bulk.BulkRequest in project OpenSearch by opensearch-project.

the class BulkRequestWithGlobalParametersIT method testGlobalPipelineOnBulkRequest.

public void testGlobalPipelineOnBulkRequest() throws IOException {
    createFieldAddingPipleine("xyz", "fieldNameXYZ", "valueXYZ");
    BulkRequest request = new BulkRequest();
    request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1"));
    request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2"));
    request.pipeline("xyz");
    bulk(request);
    Iterable<SearchHit> hits = searchAll("test");
    assertThat(hits, containsInAnyOrder(hasId("1"), hasId("2")));
    assertThat(hits, everyItem(hasProperty(fieldFromSource("fieldNameXYZ"), equalTo("valueXYZ"))));
}
Also used : SearchHit(org.opensearch.search.SearchHit) BulkRequest(org.opensearch.action.bulk.BulkRequest) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 5 with BulkRequest

use of org.opensearch.action.bulk.BulkRequest in project OpenSearch by opensearch-project.

the class BulkRequestWithGlobalParametersIT method testGlobalRouting.

public void testGlobalRouting() throws IOException {
    createIndexWithMultipleShards("index");
    BulkRequest request = new BulkRequest((String) null);
    request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1"));
    request.add(new IndexRequest("index").id("2").source(XContentType.JSON, "field", "bulk1"));
    request.routing("1");
    bulk(request);
    Iterable<SearchHit> emptyHits = searchAll(new SearchRequest("index").routing("xxx"));
    assertThat(emptyHits, is(emptyIterable()));
    Iterable<SearchHit> hits = searchAll(new SearchRequest("index").routing("1"));
    assertThat(hits, containsInAnyOrder(hasId("1"), hasId("2")));
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) SearchHit(org.opensearch.search.SearchHit) BulkRequest(org.opensearch.action.bulk.BulkRequest) IndexRequest(org.opensearch.action.index.IndexRequest)

Aggregations

BulkRequest (org.opensearch.action.bulk.BulkRequest)68 IndexRequest (org.opensearch.action.index.IndexRequest)59 BulkResponse (org.opensearch.action.bulk.BulkResponse)35 Settings (org.opensearch.common.settings.Settings)20 ThreadPool (org.opensearch.threadpool.ThreadPool)16 SearchRequest (org.opensearch.action.search.SearchRequest)15 BulkShardRequest (org.opensearch.action.bulk.BulkShardRequest)14 ShardId (org.opensearch.index.shard.ShardId)14 HashMap (java.util.HashMap)12 UpdateRequest (org.opensearch.action.update.UpdateRequest)12 Releasable (org.opensearch.common.lease.Releasable)12 List (java.util.List)11 DocWriteRequest (org.opensearch.action.DocWriteRequest)10 DeleteRequest (org.opensearch.action.delete.DeleteRequest)10 XContentType (org.opensearch.common.xcontent.XContentType)10 Map (java.util.Map)9 Matchers.containsString (org.hamcrest.Matchers.containsString)9 SearchHit (org.opensearch.search.SearchHit)9 Arrays (java.util.Arrays)8 Collections (java.util.Collections)8