Search in sources :

Example 1 with XContentType

use of org.opensearch.common.xcontent.XContentType 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 XContentType

use of org.opensearch.common.xcontent.XContentType in project OpenSearch by opensearch-project.

the class RequestConverters method update.

static Request update(UpdateRequest updateRequest) throws IOException {
    String endpoint = endpoint(updateRequest.index(), "_update", updateRequest.id());
    Request request = new Request(HttpPost.METHOD_NAME, endpoint);
    Params parameters = new Params();
    parameters.withRouting(updateRequest.routing());
    parameters.withTimeout(updateRequest.timeout());
    parameters.withRefreshPolicy(updateRequest.getRefreshPolicy());
    parameters.withWaitForActiveShards(updateRequest.waitForActiveShards());
    parameters.withDocAsUpsert(updateRequest.docAsUpsert());
    parameters.withFetchSourceContext(updateRequest.fetchSource());
    parameters.withRetryOnConflict(updateRequest.retryOnConflict());
    parameters.withVersion(updateRequest.version());
    parameters.withVersionType(updateRequest.versionType());
    parameters.withRequireAlias(updateRequest.isRequireAlias());
    // The Java API allows update requests with different content types
    // set for the partial document and the upsert document. This client
    // only accepts update requests that have the same content types set
    // for both doc and upsert.
    XContentType xContentType = null;
    if (updateRequest.doc() != null) {
        xContentType = updateRequest.doc().getContentType();
    }
    if (updateRequest.upsertRequest() != null) {
        XContentType upsertContentType = updateRequest.upsertRequest().getContentType();
        if ((xContentType != null) && (xContentType != upsertContentType)) {
            throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + " and upsert [" + upsertContentType + "] documents");
        } else {
            xContentType = upsertContentType;
        }
    }
    if (xContentType == null) {
        xContentType = Requests.INDEX_CONTENT_TYPE;
    }
    request.addParameters(parameters.asMap());
    request.setEntity(createEntity(updateRequest, xContentType));
    return request;
}
Also used : XContentType(org.opensearch.common.xcontent.XContentType) 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)

Example 3 with XContentType

use of org.opensearch.common.xcontent.XContentType in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testUpdate.

public void testUpdate() throws IOException {
    XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> expectedParams = new HashMap<>();
    String index = randomAlphaOfLengthBetween(3, 10);
    String id = randomAlphaOfLengthBetween(3, 10);
    UpdateRequest updateRequest = new UpdateRequest(index, id);
    updateRequest.detectNoop(randomBoolean());
    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.doc(new IndexRequest().source(source, xContentType));
        boolean docAsUpsert = randomBoolean();
        updateRequest.docAsUpsert(docAsUpsert);
        if (docAsUpsert) {
            expectedParams.put("doc_as_upsert", "true");
        }
    } else {
        updateRequest.script(mockScript("_value + 1"));
        updateRequest.scriptedUpsert(randomBoolean());
    }
    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.upsert(new IndexRequest().source(source, xContentType));
    }
    if (randomBoolean()) {
        String routing = randomAlphaOfLengthBetween(3, 10);
        updateRequest.routing(routing);
        expectedParams.put("routing", routing);
    }
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        updateRequest.timeout(timeout);
        expectedParams.put("timeout", timeout);
    } else {
        expectedParams.put("timeout", ReplicationRequest.DEFAULT_TIMEOUT.getStringRep());
    }
    if (randomBoolean()) {
        WriteRequest.RefreshPolicy refreshPolicy = randomFrom(WriteRequest.RefreshPolicy.values());
        updateRequest.setRefreshPolicy(refreshPolicy);
        if (refreshPolicy != WriteRequest.RefreshPolicy.NONE) {
            expectedParams.put("refresh", refreshPolicy.getValue());
        }
    }
    setRandomWaitForActiveShards(updateRequest::waitForActiveShards, expectedParams);
    // if* params are passed in the body
    setRandomIfSeqNoAndTerm(updateRequest, new HashMap<>());
    if (randomBoolean()) {
        int retryOnConflict = randomIntBetween(0, 5);
        updateRequest.retryOnConflict(retryOnConflict);
        if (retryOnConflict > 0) {
            expectedParams.put("retry_on_conflict", String.valueOf(retryOnConflict));
        }
    }
    if (randomBoolean()) {
        randomizeFetchSourceContextParams(updateRequest::fetchSource, expectedParams);
    }
    Request request = RequestConverters.update(updateRequest);
    assertEquals("/" + index + "/_update/" + id, request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    HttpEntity entity = request.getEntity();
    assertTrue(entity instanceof NByteArrayEntity);
    UpdateRequest parsedUpdateRequest = new UpdateRequest();
    XContentType entityContentType = XContentType.fromMediaTypeOrFormat(entity.getContentType().getValue());
    try (XContentParser parser = createParser(entityContentType.xContent(), entity.getContent())) {
        parsedUpdateRequest.fromXContent(parser);
    }
    assertEquals(updateRequest.scriptedUpsert(), parsedUpdateRequest.scriptedUpsert());
    assertEquals(updateRequest.docAsUpsert(), parsedUpdateRequest.docAsUpsert());
    assertEquals(updateRequest.detectNoop(), parsedUpdateRequest.detectNoop());
    assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
    assertIfSeqNoAndTerm(updateRequest, parsedUpdateRequest);
    assertEquals(updateRequest.script(), parsedUpdateRequest.script());
    if (updateRequest.doc() != null) {
        assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), xContentType);
    } else {
        assertNull(parsedUpdateRequest.doc());
    }
    if (updateRequest.upsertRequest() != null) {
        assertToXContentEquivalent(updateRequest.upsertRequest().source(), parsedUpdateRequest.upsertRequest().source(), xContentType);
    } else {
        assertNull(parsedUpdateRequest.upsertRequest());
    }
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) UpdateRequest(org.opensearch.action.update.UpdateRequest) WriteRequest(org.opensearch.action.support.WriteRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) 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) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) XContentType(org.opensearch.common.xcontent.XContentType) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 4 with XContentType

use of org.opensearch.common.xcontent.XContentType in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testEnforceSameContentType.

public void testEnforceSameContentType() {
    XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
    IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), xContentType);
    assertEquals(xContentType, enforceSameContentType(indexRequest, null));
    assertEquals(xContentType, enforceSameContentType(indexRequest, xContentType));
    XContentType bulkContentType = randomBoolean() ? xContentType : null;
    IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.CBOR), bulkContentType));
    assertEquals("Unsupported content-type found for request with content-type [CBOR], only JSON and SMILE are supported", exception.getMessage());
    exception = expectThrows(IllegalArgumentException.class, () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.YAML), bulkContentType));
    assertEquals("Unsupported content-type found for request with content-type [YAML], only JSON and SMILE are supported", exception.getMessage());
    XContentType requestContentType = xContentType == XContentType.JSON ? XContentType.SMILE : XContentType.JSON;
    exception = expectThrows(IllegalArgumentException.class, () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType));
    assertEquals("Mismatching content-type found for request with content-type [" + requestContentType + "], " + "previous requests have content-type [" + xContentType + "]", exception.getMessage());
}
Also used : XContentType(org.opensearch.common.xcontent.XContentType) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 5 with XContentType

use of org.opensearch.common.xcontent.XContentType in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testBulk.

public void testBulk() throws IOException {
    Map<String, String> expectedParams = new HashMap<>();
    BulkRequest bulkRequest = new BulkRequest();
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        bulkRequest.timeout(timeout);
        expectedParams.put("timeout", timeout);
    } else {
        expectedParams.put("timeout", BulkShardRequest.DEFAULT_TIMEOUT.getStringRep());
    }
    setRandomRefreshPolicy(bulkRequest::setRefreshPolicy, expectedParams);
    XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
    int nbItems = randomIntBetween(10, 100);
    DocWriteRequest<?>[] requests = new DocWriteRequest<?>[nbItems];
    for (int i = 0; i < nbItems; i++) {
        String index = randomAlphaOfLength(5);
        String id = randomAlphaOfLength(5);
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values());
        DocWriteRequest<?> docWriteRequest;
        if (opType == DocWriteRequest.OpType.INDEX) {
            IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, xContentType);
            docWriteRequest = indexRequest;
            if (randomBoolean()) {
                indexRequest.setPipeline(randomAlphaOfLength(5));
            }
        } else if (opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest createRequest = new IndexRequest(index).id(id).source(source, xContentType).create(true);
            docWriteRequest = createRequest;
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            final UpdateRequest updateRequest = new UpdateRequest(index, id).doc(new IndexRequest().source(source, xContentType));
            docWriteRequest = updateRequest;
            if (randomBoolean()) {
                updateRequest.retryOnConflict(randomIntBetween(1, 5));
            }
            if (randomBoolean()) {
                randomizeFetchSourceContextParams(updateRequest::fetchSource, new HashMap<>());
            }
        } else if (opType == DocWriteRequest.OpType.DELETE) {
            docWriteRequest = new DeleteRequest(index, id);
        } else {
            throw new UnsupportedOperationException("optype [" + opType + "] not supported");
        }
        if (randomBoolean()) {
            docWriteRequest.routing(randomAlphaOfLength(10));
        }
        if (opType != DocWriteRequest.OpType.UPDATE && randomBoolean()) {
            docWriteRequest.setIfSeqNo(randomNonNegativeLong());
            docWriteRequest.setIfPrimaryTerm(randomLongBetween(1, 200));
        }
        requests[i] = docWriteRequest;
    }
    bulkRequest.add(requests);
    Request request = RequestConverters.bulk(bulkRequest);
    assertEquals("/_bulk", request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType().getValue());
    byte[] content = new byte[(int) request.getEntity().getContentLength()];
    try (InputStream inputStream = request.getEntity().getContent()) {
        Streams.readFully(inputStream, content);
    }
    BulkRequest parsedBulkRequest = new BulkRequest();
    parsedBulkRequest.add(content, 0, content.length, xContentType);
    assertEquals(bulkRequest.numberOfActions(), parsedBulkRequest.numberOfActions());
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> originalRequest = bulkRequest.requests().get(i);
        DocWriteRequest<?> parsedRequest = parsedBulkRequest.requests().get(i);
        assertEquals(originalRequest.opType(), parsedRequest.opType());
        assertEquals(originalRequest.index(), parsedRequest.index());
        assertEquals(originalRequest.id(), parsedRequest.id());
        assertEquals(originalRequest.routing(), parsedRequest.routing());
        assertEquals(originalRequest.version(), parsedRequest.version());
        assertEquals(originalRequest.versionType(), parsedRequest.versionType());
        assertEquals(originalRequest.ifSeqNo(), parsedRequest.ifSeqNo());
        assertEquals(originalRequest.ifPrimaryTerm(), parsedRequest.ifPrimaryTerm());
        DocWriteRequest.OpType opType = originalRequest.opType();
        if (opType == DocWriteRequest.OpType.INDEX) {
            IndexRequest indexRequest = (IndexRequest) originalRequest;
            IndexRequest parsedIndexRequest = (IndexRequest) parsedRequest;
            assertEquals(indexRequest.getPipeline(), parsedIndexRequest.getPipeline());
            assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), xContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) originalRequest;
            UpdateRequest parsedUpdateRequest = (UpdateRequest) parsedRequest;
            assertEquals(updateRequest.retryOnConflict(), parsedUpdateRequest.retryOnConflict());
            assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
            if (updateRequest.doc() != null) {
                assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), xContentType);
            } else {
                assertNull(parsedUpdateRequest.doc());
            }
        }
    }
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) HashMap(java.util.HashMap) UpdateRequest(org.opensearch.action.update.UpdateRequest) InputStream(java.io.InputStream) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) 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) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) XContentType(org.opensearch.common.xcontent.XContentType) BulkRequest(org.opensearch.action.bulk.BulkRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest)

Aggregations

XContentType (org.opensearch.common.xcontent.XContentType)148 BytesReference (org.opensearch.common.bytes.BytesReference)99 XContentParser (org.opensearch.common.xcontent.XContentParser)85 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)44 IOException (java.io.IOException)31 HashMap (java.util.HashMap)31 Map (java.util.Map)30 ToXContent (org.opensearch.common.xcontent.ToXContent)22 List (java.util.List)18 IndexRequest (org.opensearch.action.index.IndexRequest)16 ArrayList (java.util.ArrayList)15 Predicate (java.util.function.Predicate)14 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)14 XContentTestUtils.insertRandomFields (org.opensearch.test.XContentTestUtils.insertRandomFields)12 Matchers.containsString (org.hamcrest.Matchers.containsString)11 DocWriteRequest (org.opensearch.action.DocWriteRequest)11 XContentHelper.toXContent (org.opensearch.common.xcontent.XContentHelper.toXContent)11 Collections (java.util.Collections)10 DeleteRequest (org.opensearch.action.delete.DeleteRequest)10 OpenSearchAssertions.assertToXContentEquivalent (org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent)10