Search in sources :

Example 1 with Scroll

use of org.opensearch.search.Scroll 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 2 with Scroll

use of org.opensearch.search.Scroll in project OpenSearch by opensearch-project.

the class SearchScrollAsyncActionTests method testNodeNotAvailable.

public void testNodeNotAvailable() throws InterruptedException {
    ParsedScrollId scrollId = getParsedScrollId(new SearchContextIdForNode(null, "node1", new ShardSearchContextId("", 1)), new SearchContextIdForNode(null, "node2", new ShardSearchContextId("", 2)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("", 17)), new SearchContextIdForNode(null, "node1", new ShardSearchContextId("", 0)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("", 0)));
    // node2 is not available
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(new DiscoveryNode("node1", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node3", buildNewFakeTransportAddress(), Version.CURRENT)).build();
    AtomicArray<SearchAsyncActionTests.TestSearchPhaseResult> results = new AtomicArray<>(scrollId.getContext().length);
    SearchScrollRequest request = new SearchScrollRequest();
    request.scroll(new Scroll(TimeValue.timeValueMinutes(1)));
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger movedCounter = new AtomicInteger(0);
    SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult> action = new SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult>(scrollId, logger, discoveryNodes, dummyListener(), null, request, null) {

        @Override
        protected void executeInitialPhase(Transport.Connection connection, InternalScrollSearchRequest internalRequest, SearchActionListener<SearchAsyncActionTests.TestSearchPhaseResult> searchActionListener) {
            try {
                assertNotEquals("node2 is not available", "node2", connection.getNode().getId());
            } catch (NullPointerException e) {
                logger.warn(e);
            }
            new Thread(() -> {
                SearchAsyncActionTests.TestSearchPhaseResult testSearchPhaseResult = new SearchAsyncActionTests.TestSearchPhaseResult(internalRequest.contextId(), connection.getNode());
                testSearchPhaseResult.setSearchShardTarget(new SearchShardTarget(connection.getNode().getId(), new ShardId("test", "_na_", 1), null, OriginalIndices.NONE));
                searchActionListener.onResponse(testSearchPhaseResult);
            }).start();
        }

        @Override
        protected Transport.Connection getConnection(String clusterAlias, DiscoveryNode node) {
            return new SearchAsyncActionTests.MockConnection(node);
        }

        @Override
        protected SearchPhase moveToNextPhase(BiFunction<String, String, DiscoveryNode> clusterNodeLookup) {
            assertEquals(1, movedCounter.incrementAndGet());
            return new SearchPhase("test") {

                @Override
                public void run() throws IOException {
                    latch.countDown();
                }
            };
        }

        @Override
        protected void onFirstPhaseResult(int shardId, SearchAsyncActionTests.TestSearchPhaseResult result) {
            results.setOnce(shardId, result);
        }
    };
    action.run();
    latch.await();
    ShardSearchFailure[] shardSearchFailures = action.buildShardFailures();
    assertEquals(1, shardSearchFailures.length);
    assertEquals("IllegalStateException[node [node2] is not available]", shardSearchFailures[0].reason());
    SearchContextIdForNode[] context = scrollId.getContext();
    for (int i = 0; i < results.length(); i++) {
        if (context[i].getNode().equals("node2")) {
            assertNull(results.get(i));
        } else {
            assertNotNull(results.get(i));
            assertEquals(context[i].getSearchContextId(), results.get(i).getContextId());
            assertEquals(context[i].getNode(), results.get(i).node.getId());
        }
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) InternalScrollSearchRequest(org.opensearch.search.internal.InternalScrollSearchRequest) ShardId(org.opensearch.index.shard.ShardId) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Scroll(org.opensearch.search.Scroll) CountDownLatch(java.util.concurrent.CountDownLatch) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiFunction(java.util.function.BiFunction) SearchShardTarget(org.opensearch.search.SearchShardTarget) Transport(org.opensearch.transport.Transport)

Example 3 with Scroll

use of org.opensearch.search.Scroll in project OpenSearch by opensearch-project.

the class SearchScrollAsyncActionTests method testFailNextPhase.

public void testFailNextPhase() throws InterruptedException {
    ParsedScrollId scrollId = getParsedScrollId(new SearchContextIdForNode(null, "node1", new ShardSearchContextId("", 1)), new SearchContextIdForNode(null, "node2", new ShardSearchContextId("a", 2)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("b", 17)), new SearchContextIdForNode(null, "node1", new ShardSearchContextId("c", 0)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("d", 0)));
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(new DiscoveryNode("node1", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node2", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node3", buildNewFakeTransportAddress(), Version.CURRENT)).build();
    AtomicArray<SearchAsyncActionTests.TestSearchPhaseResult> results = new AtomicArray<>(scrollId.getContext().length);
    SearchScrollRequest request = new SearchScrollRequest();
    request.scroll(new Scroll(TimeValue.timeValueMinutes(1)));
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger movedCounter = new AtomicInteger(0);
    ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {

        @Override
        public void onResponse(SearchResponse o) {
            try {
                fail("got a result");
            } finally {
                latch.countDown();
            }
        }

        @Override
        public void onFailure(Exception e) {
            try {
                assertTrue(e instanceof SearchPhaseExecutionException);
                SearchPhaseExecutionException ex = (SearchPhaseExecutionException) e;
                assertEquals("BOOM", ex.getCause().getMessage());
                assertEquals("TEST_PHASE", ex.getPhaseName());
                assertEquals("Phase failed", ex.getMessage());
            } finally {
                latch.countDown();
            }
        }
    };
    SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult> action = new SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult>(scrollId, logger, discoveryNodes, listener, null, request, null) {

        @Override
        protected void executeInitialPhase(Transport.Connection connection, InternalScrollSearchRequest internalRequest, SearchActionListener<SearchAsyncActionTests.TestSearchPhaseResult> searchActionListener) {
            new Thread(() -> {
                SearchAsyncActionTests.TestSearchPhaseResult testSearchPhaseResult = new SearchAsyncActionTests.TestSearchPhaseResult(internalRequest.contextId(), connection.getNode());
                testSearchPhaseResult.setSearchShardTarget(new SearchShardTarget(connection.getNode().getId(), new ShardId("test", "_na_", 1), null, OriginalIndices.NONE));
                searchActionListener.onResponse(testSearchPhaseResult);
            }).start();
        }

        @Override
        protected Transport.Connection getConnection(String clusterAlias, DiscoveryNode node) {
            return new SearchAsyncActionTests.MockConnection(node);
        }

        @Override
        protected SearchPhase moveToNextPhase(BiFunction<String, String, DiscoveryNode> clusterNodeLookup) {
            assertEquals(1, movedCounter.incrementAndGet());
            return new SearchPhase("TEST_PHASE") {

                @Override
                public void run() throws IOException {
                    throw new IllegalArgumentException("BOOM");
                }
            };
        }

        @Override
        protected void onFirstPhaseResult(int shardId, SearchAsyncActionTests.TestSearchPhaseResult result) {
            results.setOnce(shardId, result);
        }
    };
    action.run();
    latch.await();
    ShardSearchFailure[] shardSearchFailures = action.buildShardFailures();
    assertEquals(0, shardSearchFailures.length);
    SearchContextIdForNode[] context = scrollId.getContext();
    for (int i = 0; i < results.length(); i++) {
        assertNotNull(results.get(i));
        assertEquals(context[i].getSearchContextId(), results.get(i).getContextId());
        assertEquals(context[i].getNode(), results.get(i).node.getId());
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) InternalScrollSearchRequest(org.opensearch.search.internal.InternalScrollSearchRequest) ShardId(org.opensearch.index.shard.ShardId) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Scroll(org.opensearch.search.Scroll) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) ActionListener(org.opensearch.action.ActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiFunction(java.util.function.BiFunction) SearchShardTarget(org.opensearch.search.SearchShardTarget) Transport(org.opensearch.transport.Transport)

Example 4 with Scroll

use of org.opensearch.search.Scroll in project OpenSearch by opensearch-project.

the class SearchScrollAsyncActionTests method testSendRequestsToNodes.

public void testSendRequestsToNodes() throws InterruptedException {
    ParsedScrollId scrollId = getParsedScrollId(new SearchContextIdForNode(null, "node1", new ShardSearchContextId(UUIDs.randomBase64UUID(), 1)), new SearchContextIdForNode(null, "node2", new ShardSearchContextId(UUIDs.randomBase64UUID(), 2)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId(UUIDs.randomBase64UUID(), 17)), new SearchContextIdForNode(null, "node1", new ShardSearchContextId(UUIDs.randomBase64UUID(), 0)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId(UUIDs.randomBase64UUID(), 0)));
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(new DiscoveryNode("node1", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node2", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node3", buildNewFakeTransportAddress(), Version.CURRENT)).build();
    AtomicArray<SearchAsyncActionTests.TestSearchPhaseResult> results = new AtomicArray<>(scrollId.getContext().length);
    SearchScrollRequest request = new SearchScrollRequest();
    request.scroll(new Scroll(TimeValue.timeValueMinutes(1)));
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger movedCounter = new AtomicInteger(0);
    SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult> action = new SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult>(scrollId, logger, discoveryNodes, dummyListener(), null, request, null) {

        @Override
        protected void executeInitialPhase(Transport.Connection connection, InternalScrollSearchRequest internalRequest, SearchActionListener<SearchAsyncActionTests.TestSearchPhaseResult> searchActionListener) {
            new Thread(() -> {
                SearchAsyncActionTests.TestSearchPhaseResult testSearchPhaseResult = new SearchAsyncActionTests.TestSearchPhaseResult(internalRequest.contextId(), connection.getNode());
                testSearchPhaseResult.setSearchShardTarget(new SearchShardTarget(connection.getNode().getId(), new ShardId("test", "_na_", 1), null, OriginalIndices.NONE));
                searchActionListener.onResponse(testSearchPhaseResult);
            }).start();
        }

        @Override
        protected Transport.Connection getConnection(String clusterAlias, DiscoveryNode node) {
            return new SearchAsyncActionTests.MockConnection(node);
        }

        @Override
        protected SearchPhase moveToNextPhase(BiFunction<String, String, DiscoveryNode> clusterNodeLookup) {
            assertEquals(1, movedCounter.incrementAndGet());
            return new SearchPhase("test") {

                @Override
                public void run() throws IOException {
                    latch.countDown();
                }
            };
        }

        @Override
        protected void onFirstPhaseResult(int shardId, SearchAsyncActionTests.TestSearchPhaseResult result) {
            results.setOnce(shardId, result);
        }
    };
    action.run();
    latch.await();
    ShardSearchFailure[] shardSearchFailures = action.buildShardFailures();
    assertEquals(0, shardSearchFailures.length);
    SearchContextIdForNode[] context = scrollId.getContext();
    for (int i = 0; i < results.length(); i++) {
        assertNotNull(results.get(i));
        assertEquals(context[i].getSearchContextId(), results.get(i).getContextId());
        assertEquals(context[i].getNode(), results.get(i).node.getId());
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) InternalScrollSearchRequest(org.opensearch.search.internal.InternalScrollSearchRequest) ShardId(org.opensearch.index.shard.ShardId) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Scroll(org.opensearch.search.Scroll) CountDownLatch(java.util.concurrent.CountDownLatch) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiFunction(java.util.function.BiFunction) SearchShardTarget(org.opensearch.search.SearchShardTarget) Transport(org.opensearch.transport.Transport)

Example 5 with Scroll

use of org.opensearch.search.Scroll in project OpenSearch by opensearch-project.

the class SearchScrollAsyncActionTests method testAllShardsFailed.

public void testAllShardsFailed() throws InterruptedException {
    ParsedScrollId scrollId = getParsedScrollId(new SearchContextIdForNode(null, "node1", new ShardSearchContextId("", 1)), new SearchContextIdForNode(null, "node2", new ShardSearchContextId("", 2)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("", 17)), new SearchContextIdForNode(null, "node1", new ShardSearchContextId("", 0)), new SearchContextIdForNode(null, "node3", new ShardSearchContextId("", 0)));
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(new DiscoveryNode("node1", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node2", buildNewFakeTransportAddress(), Version.CURRENT)).add(new DiscoveryNode("node3", buildNewFakeTransportAddress(), Version.CURRENT)).build();
    AtomicArray<SearchAsyncActionTests.TestSearchPhaseResult> results = new AtomicArray<>(scrollId.getContext().length);
    SearchScrollRequest request = new SearchScrollRequest();
    request.scroll(new Scroll(TimeValue.timeValueMinutes(1)));
    CountDownLatch latch = new CountDownLatch(1);
    ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {

        @Override
        public void onResponse(SearchResponse o) {
            try {
                fail("got a result");
            } finally {
                latch.countDown();
            }
        }

        @Override
        public void onFailure(Exception e) {
            try {
                assertTrue(e instanceof SearchPhaseExecutionException);
                SearchPhaseExecutionException ex = (SearchPhaseExecutionException) e;
                assertEquals("BOOM on shard", ex.getCause().getMessage());
                assertEquals("query", ex.getPhaseName());
                assertEquals("all shards failed", ex.getMessage());
            } finally {
                latch.countDown();
            }
        }
    };
    SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult> action = new SearchScrollAsyncAction<SearchAsyncActionTests.TestSearchPhaseResult>(scrollId, logger, discoveryNodes, listener, null, request, null) {

        @Override
        protected void executeInitialPhase(Transport.Connection connection, InternalScrollSearchRequest internalRequest, SearchActionListener<SearchAsyncActionTests.TestSearchPhaseResult> searchActionListener) {
            new Thread(() -> searchActionListener.onFailure(new IllegalArgumentException("BOOM on shard"))).start();
        }

        @Override
        protected Transport.Connection getConnection(String clusterAlias, DiscoveryNode node) {
            return new SearchAsyncActionTests.MockConnection(node);
        }

        @Override
        protected SearchPhase moveToNextPhase(BiFunction<String, String, DiscoveryNode> clusterNodeLookup) {
            fail("don't move all shards failed");
            return null;
        }

        @Override
        protected void onFirstPhaseResult(int shardId, SearchAsyncActionTests.TestSearchPhaseResult result) {
            results.setOnce(shardId, result);
        }
    };
    action.run();
    latch.await();
    SearchContextIdForNode[] context = scrollId.getContext();
    ShardSearchFailure[] shardSearchFailures = action.buildShardFailures();
    assertEquals(context.length, shardSearchFailures.length);
    assertEquals("IllegalArgumentException[BOOM on shard]", shardSearchFailures[0].reason());
    for (int i = 0; i < results.length(); i++) {
        assertNull(results.get(i));
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) InternalScrollSearchRequest(org.opensearch.search.internal.InternalScrollSearchRequest) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Scroll(org.opensearch.search.Scroll) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) ActionListener(org.opensearch.action.ActionListener) BiFunction(java.util.function.BiFunction) Transport(org.opensearch.transport.Transport)

Aggregations

Scroll (org.opensearch.search.Scroll)14 BiFunction (java.util.function.BiFunction)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)5 DiscoveryNodes (org.opensearch.cluster.node.DiscoveryNodes)5 AtomicArray (org.opensearch.common.util.concurrent.AtomicArray)5 InternalScrollSearchRequest (org.opensearch.search.internal.InternalScrollSearchRequest)5 ShardSearchContextId (org.opensearch.search.internal.ShardSearchContextId)5 Transport (org.opensearch.transport.Transport)5 IOException (java.io.IOException)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 ShardId (org.opensearch.index.shard.ShardId)4 SearchShardTarget (org.opensearch.search.SearchShardTarget)4 ArrayList (java.util.ArrayList)3 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2 List (java.util.List)2 ActionListener (org.opensearch.action.ActionListener)2 SearchRequestBuilder (org.opensearch.action.search.SearchRequestBuilder)2 SearchResponse (org.opensearch.action.search.SearchResponse)2