Search in sources :

Example 1 with MultiSearchRequest

use of org.opensearch.action.search.MultiSearchRequest in project OpenSearch by opensearch-project.

the class RequestConverters method multiSearch.

static Request multiSearch(MultiSearchRequest multiSearchRequest) throws IOException {
    Request request = new Request(HttpPost.METHOD_NAME, "/_msearch");
    Params params = new Params();
    params.putParam(RestSearchAction.TYPED_KEYS_PARAM, "true");
    if (multiSearchRequest.maxConcurrentSearchRequests() != MultiSearchRequest.MAX_CONCURRENT_SEARCH_REQUESTS_DEFAULT) {
        params.putParam("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests()));
    }
    XContent xContent = REQUEST_BODY_CONTENT_TYPE.xContent();
    byte[] source = MultiSearchRequest.writeMultiLineFormat(multiSearchRequest, xContent);
    request.addParameters(params.asMap());
    request.setEntity(new NByteArrayEntity(source, createContentType(xContent.type())));
    return request;
}
Also used : NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) ToXContent(org.opensearch.common.xcontent.ToXContent) XContent(org.opensearch.common.xcontent.XContent) 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 2 with MultiSearchRequest

use of org.opensearch.action.search.MultiSearchRequest in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testMultiSearch.

public void testMultiSearch() throws IOException {
    int numberOfSearchRequests = randomIntBetween(0, 32);
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    for (int i = 0; i < numberOfSearchRequests; i++) {
        SearchRequest searchRequest = randomSearchRequest(() -> {
            // No need to return a very complex SearchSourceBuilder here, that is tested
            // elsewhere
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.from(randomInt(10));
            searchSourceBuilder.size(randomIntBetween(20, 100));
            return searchSourceBuilder;
        });
        // scroll is not supported in the current msearch api, so unset it:
        searchRequest.scroll((Scroll) null);
        // only expand_wildcards, ignore_unavailable and allow_no_indices can be
        // specified from msearch api, so unset other options:
        IndicesOptions randomlyGenerated = searchRequest.indicesOptions();
        IndicesOptions msearchDefault = new MultiSearchRequest().indicesOptions();
        searchRequest.indicesOptions(IndicesOptions.fromOptions(randomlyGenerated.ignoreUnavailable(), randomlyGenerated.allowNoIndices(), randomlyGenerated.expandWildcardsOpen(), randomlyGenerated.expandWildcardsClosed(), msearchDefault.expandWildcardsHidden(), msearchDefault.allowAliasesToMultipleIndices(), msearchDefault.forbidClosedIndices(), msearchDefault.ignoreAliases(), msearchDefault.ignoreThrottled()));
        multiSearchRequest.add(searchRequest);
    }
    Map<String, String> expectedParams = new HashMap<>();
    expectedParams.put(RestSearchAction.TYPED_KEYS_PARAM, "true");
    if (randomBoolean()) {
        multiSearchRequest.maxConcurrentSearchRequests(randomIntBetween(1, 8));
        expectedParams.put("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests()));
    }
    Request request = RequestConverters.multiSearch(multiSearchRequest);
    assertEquals("/_msearch", request.getEndpoint());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    assertEquals(expectedParams, request.getParameters());
    List<SearchRequest> requests = new ArrayList<>();
    CheckedBiConsumer<SearchRequest, XContentParser, IOException> consumer = (searchRequest, p) -> {
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.fromXContent(p, false);
        if (searchSourceBuilder.equals(new SearchSourceBuilder()) == false) {
            searchRequest.source(searchSourceBuilder);
        }
        requests.add(searchRequest);
    };
    MultiSearchRequest.readMultiLineFormat(new BytesArray(EntityUtils.toByteArray(request.getEntity())), REQUEST_BODY_CONTENT_TYPE.xContent(), consumer, null, multiSearchRequest.indicesOptions(), null, null, null, xContentRegistry(), true, deprecationLogger);
    assertEquals(requests, multiSearchRequest.requests());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Arrays(java.util.Arrays) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) Strings(org.opensearch.common.Strings) ScriptType(org.opensearch.script.ScriptType) 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) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) DeleteRequest(org.opensearch.action.delete.DeleteRequest) ValueType(org.opensearch.search.aggregations.support.ValueType) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) TimeValue(org.opensearch.common.unit.TimeValue) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) VersionType(org.opensearch.index.VersionType) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) BytesArray(org.opensearch.common.bytes.BytesArray) CollapseBuilder(org.opensearch.search.collapse.CollapseBuilder) UpdateRequest(org.opensearch.action.update.UpdateRequest) XContentType(org.opensearch.common.xcontent.XContentType) OpenSearchAssertions.assertToXContentEquivalent(org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) HttpHead(org.apache.http.client.methods.HttpHead) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) DocWriteRequest(org.opensearch.action.DocWriteRequest) RemoteInfo(org.opensearch.index.reindex.RemoteInfo) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RestSearchAction(org.opensearch.rest.action.search.RestSearchAction) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) Streams(org.opensearch.common.io.Streams) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) QueryBuilders(org.opensearch.index.query.QueryBuilders) Versions(org.opensearch.common.lucene.uid.Versions) QueryRescorerBuilder(org.opensearch.search.rescore.QueryRescorerBuilder) SearchType(org.opensearch.action.search.SearchType) TaskId(org.opensearch.tasks.TaskId) IOException(java.io.IOException) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) RankEvalSpec(org.opensearch.index.rankeval.RankEvalSpec) EndpointBuilder(org.opensearch.client.RequestConverters.EndpointBuilder) RestRankEvalAction(org.opensearch.index.rankeval.RestRankEvalAction) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) RequestConverters.enforceSameContentType(org.opensearch.client.RequestConverters.enforceSameContentType) CompletionSuggestionBuilder(org.opensearch.search.suggest.completion.CompletionSuggestionBuilder) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) ToXContent(org.opensearch.common.xcontent.ToXContent) BiFunction(java.util.function.BiFunction) BulkRequest(org.opensearch.action.bulk.BulkRequest) Matchers.hasKey(org.hamcrest.Matchers.hasKey) EntityUtils(org.apache.http.util.EntityUtils) XContentParser(org.opensearch.common.xcontent.XContentParser) MapperService(org.opensearch.index.mapper.MapperService) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) Locale(java.util.Locale) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) Scroll(org.opensearch.search.Scroll) RandomObjects(org.opensearch.test.RandomObjects) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) Script(org.opensearch.script.Script) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) Tuple(org.opensearch.common.collect.Tuple) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) BytesReference(org.opensearch.common.bytes.BytesReference) CheckedBiConsumer(org.opensearch.common.CheckedBiConsumer) HighlightBuilder(org.opensearch.search.fetch.subphase.highlight.HighlightBuilder) HashMap(java.util.HashMap) IndicesOptions(org.opensearch.action.support.IndicesOptions) Function(java.util.function.Function) REQUEST_BODY_CONTENT_TYPE(org.opensearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) HashSet(java.util.HashSet) HttpDelete(org.apache.http.client.methods.HttpDelete) Collections.singletonMap(java.util.Collections.singletonMap) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) Collections.emptyMap(java.util.Collections.emptyMap) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) Matchers(org.hamcrest.Matchers) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) Consumer(java.util.function.Consumer) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) HttpPut(org.apache.http.client.methods.HttpPut) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) StringJoiner(java.util.StringJoiner) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) IndexRequest(org.opensearch.action.index.IndexRequest) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) Collections(java.util.Collections) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) InputStream(java.io.InputStream) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) BytesArray(org.opensearch.common.bytes.BytesArray) HashMap(java.util.HashMap) 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) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) IndicesOptions(org.opensearch.action.support.IndicesOptions) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 3 with MultiSearchRequest

use of org.opensearch.action.search.MultiSearchRequest in project OpenSearch by opensearch-project.

the class SearchIT method testMultiSearch_withAgg.

public void testMultiSearch_withAgg() throws Exception {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    SearchRequest searchRequest1 = new SearchRequest("index1");
    searchRequest1.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)));
    multiSearchRequest.add(searchRequest1);
    SearchRequest searchRequest2 = new SearchRequest("index2");
    searchRequest2.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)));
    multiSearchRequest.add(searchRequest2);
    SearchRequest searchRequest3 = new SearchRequest("index3");
    searchRequest3.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)));
    multiSearchRequest.add(searchRequest3);
    MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync);
    assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L));
    assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3));
    assertThat(multiSearchResponse.getResponses()[0].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[0].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse());
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getTotalHits().value, Matchers.equalTo(2L));
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getHits().length, Matchers.equalTo(0));
    Terms terms = multiSearchResponse.getResponses()[0].getResponse().getAggregations().get("name");
    assertThat(terms.getBuckets().size(), Matchers.equalTo(2));
    assertThat(terms.getBuckets().get(0).getKeyAsString(), Matchers.equalTo("value1"));
    assertThat(terms.getBuckets().get(1).getKeyAsString(), Matchers.equalTo("value2"));
    assertThat(multiSearchResponse.getResponses()[1].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[1].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse());
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getTotalHits().value, Matchers.equalTo(2L));
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getHits().length, Matchers.equalTo(0));
    terms = multiSearchResponse.getResponses()[1].getResponse().getAggregations().get("name");
    assertThat(terms.getBuckets().size(), Matchers.equalTo(2));
    assertThat(terms.getBuckets().get(0).getKeyAsString(), Matchers.equalTo("value1"));
    assertThat(terms.getBuckets().get(1).getKeyAsString(), Matchers.equalTo("value2"));
    assertThat(multiSearchResponse.getResponses()[2].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[2].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse());
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getTotalHits().value, Matchers.equalTo(2L));
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getHits().length, Matchers.equalTo(0));
    terms = multiSearchResponse.getResponses()[2].getResponse().getAggregations().get("name");
    assertThat(terms.getBuckets().size(), Matchers.equalTo(2));
    assertThat(terms.getBuckets().get(0).getKeyAsString(), Matchers.equalTo("value1"));
    assertThat(terms.getBuckets().get(1).getKeyAsString(), Matchers.equalTo("value2"));
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) RareTermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.RareTermsAggregationBuilder) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) RareTerms(org.opensearch.search.aggregations.bucket.terms.RareTerms) Terms(org.opensearch.search.aggregations.bucket.terms.Terms) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest)

Example 4 with MultiSearchRequest

use of org.opensearch.action.search.MultiSearchRequest in project OpenSearch by opensearch-project.

the class SearchIT method testMultiSearch_withQuery.

public void testMultiSearch_withQuery() throws Exception {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    SearchRequest searchRequest1 = new SearchRequest("index1");
    searchRequest1.source().query(new TermsQueryBuilder("field", "value2"));
    multiSearchRequest.add(searchRequest1);
    SearchRequest searchRequest2 = new SearchRequest("index2");
    searchRequest2.source().query(new TermsQueryBuilder("field", "value2"));
    multiSearchRequest.add(searchRequest2);
    SearchRequest searchRequest3 = new SearchRequest("index3");
    searchRequest3.source().query(new TermsQueryBuilder("field", "value2"));
    multiSearchRequest.add(searchRequest3);
    MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync);
    assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L));
    assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3));
    assertThat(multiSearchResponse.getResponses()[0].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[0].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse());
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("2"));
    assertThat(multiSearchResponse.getResponses()[1].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[1].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[1].getResponse());
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("4"));
    assertThat(multiSearchResponse.getResponses()[2].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[2].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[2].getResponse());
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("6"));
    searchRequest1.source().highlighter(new HighlightBuilder().field("field"));
    searchRequest2.source().highlighter(new HighlightBuilder().field("field"));
    searchRequest3.source().highlighter(new HighlightBuilder().field("field"));
    multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync);
    assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L));
    assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3));
    assertThat(multiSearchResponse.getResponses()[0].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[0].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse());
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0].string(), Matchers.equalTo("<em>value2</em>"));
    assertThat(multiSearchResponse.getResponses()[1].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[1].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[1].getResponse());
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("4"));
    assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0].string(), Matchers.equalTo("<em>value2</em>"));
    assertThat(multiSearchResponse.getResponses()[2].getFailure(), Matchers.nullValue());
    assertThat(multiSearchResponse.getResponses()[2].isFailure(), Matchers.is(false));
    SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[2].getResponse());
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L));
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("6"));
    assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0].string(), Matchers.equalTo("<em>value2</em>"));
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) HighlightBuilder(org.opensearch.search.fetch.subphase.highlight.HighlightBuilder)

Example 5 with MultiSearchRequest

use of org.opensearch.action.search.MultiSearchRequest in project OpenSearch by opensearch-project.

the class SearchDocumentationIT method testMultiSearch.

public void testMultiSearch() throws Exception {
    indexSearchTestData();
    RestHighLevelClient client = highLevelClient();
    {
        // tag::multi-search-request-basic
        // <1>
        MultiSearchRequest request = new MultiSearchRequest();
        // <2>
        SearchRequest firstSearchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("user", "foobar"));
        firstSearchRequest.source(searchSourceBuilder);
        // <3>
        request.add(firstSearchRequest);
        // <4>
        SearchRequest secondSearchRequest = new SearchRequest();
        searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("user", "quxx"));
        secondSearchRequest.source(searchSourceBuilder);
        request.add(secondSearchRequest);
        // end::multi-search-request-basic
        // tag::multi-search-execute
        MultiSearchResponse response = client.msearch(request, RequestOptions.DEFAULT);
        // end::multi-search-execute
        // tag::multi-search-response
        // <1>
        MultiSearchResponse.Item firstResponse = response.getResponses()[0];
        // <2>
        assertNull(firstResponse.getFailure());
        // <3>
        SearchResponse searchResponse = firstResponse.getResponse();
        assertEquals(4, searchResponse.getHits().getTotalHits().value);
        // <4>
        MultiSearchResponse.Item secondResponse = response.getResponses()[1];
        assertNull(secondResponse.getFailure());
        searchResponse = secondResponse.getResponse();
        assertEquals(1, searchResponse.getHits().getTotalHits().value);
        // end::multi-search-response
        // tag::multi-search-execute-listener
        ActionListener<MultiSearchResponse> listener = new ActionListener<MultiSearchResponse>() {

            @Override
            public void onResponse(MultiSearchResponse response) {
            // <1>
            }

            @Override
            public void onFailure(Exception e) {
            // <2>
            }
        };
        // end::multi-search-execute-listener
        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        listener = new LatchedActionListener<>(listener, latch);
        // tag::multi-search-execute-async
        // <1>
        client.msearchAsync(request, RequestOptions.DEFAULT, listener);
        // end::multi-search-execute-async
        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) Item(org.opensearch.script.mustache.MultiSearchTemplateResponse.Item) LatchedActionListener(org.opensearch.action.LatchedActionListener) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest)

Aggregations

MultiSearchRequest (org.opensearch.action.search.MultiSearchRequest)16 SearchRequest (org.opensearch.action.search.SearchRequest)14 MultiSearchResponse (org.opensearch.action.search.MultiSearchResponse)9 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)8 ArrayList (java.util.ArrayList)6 ActionListener (org.opensearch.action.ActionListener)5 Script (org.opensearch.script.Script)5 List (java.util.List)4 NByteArrayEntity (org.apache.http.nio.entity.NByteArrayEntity)4 WriteRequest (org.opensearch.action.support.WriteRequest)4 IOException (java.io.IOException)3 Arrays (java.util.Arrays)3 Collections (java.util.Collections)3 Map (java.util.Map)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 LatchedActionListener (org.opensearch.action.LatchedActionListener)3 SearchResponse (org.opensearch.action.search.SearchResponse)3 IndicesOptions (org.opensearch.action.support.IndicesOptions)3 HashMap (java.util.HashMap)2 DocWriteRequest (org.opensearch.action.DocWriteRequest)2