Search in sources :

Example 16 with QuerySearchResult

use of org.opensearch.search.query.QuerySearchResult in project OpenSearch by opensearch-project.

the class QueryPhaseResultConsumerTests method testProgressListenerExceptionsAreCaught.

public void testProgressListenerExceptionsAreCaught() throws Exception {
    ThrowingSearchProgressListener searchProgressListener = new ThrowingSearchProgressListener();
    List<SearchShard> searchShards = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        searchShards.add(new SearchShard(null, new ShardId("index", "uuid", i)));
    }
    searchProgressListener.notifyListShards(searchShards, Collections.emptyList(), SearchResponse.Clusters.EMPTY, false);
    SearchRequest searchRequest = new SearchRequest("index");
    searchRequest.setBatchedReduceSize(2);
    AtomicReference<Exception> onPartialMergeFailure = new AtomicReference<>();
    QueryPhaseResultConsumer queryPhaseResultConsumer = new QueryPhaseResultConsumer(searchRequest, executor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), searchPhaseController, searchProgressListener, writableRegistry(), 10, e -> onPartialMergeFailure.accumulateAndGet(e, (prev, curr) -> {
        curr.addSuppressed(prev);
        return curr;
    }));
    CountDownLatch partialReduceLatch = new CountDownLatch(10);
    for (int i = 0; i < 10; i++) {
        SearchShardTarget searchShardTarget = new SearchShardTarget("node", new ShardId("index", "uuid", i), null, OriginalIndices.NONE);
        QuerySearchResult querySearchResult = new QuerySearchResult();
        TopDocs topDocs = new TopDocs(new TotalHits(0, TotalHits.Relation.EQUAL_TO), new ScoreDoc[0]);
        querySearchResult.topDocs(new TopDocsAndMaxScore(topDocs, Float.NaN), new DocValueFormat[0]);
        querySearchResult.setSearchShardTarget(searchShardTarget);
        querySearchResult.setShardIndex(i);
        queryPhaseResultConsumer.consumeResult(querySearchResult, partialReduceLatch::countDown);
    }
    assertEquals(10, searchProgressListener.onQueryResult.get());
    assertTrue(partialReduceLatch.await(10, TimeUnit.SECONDS));
    assertNull(onPartialMergeFailure.get());
    assertEquals(8, searchProgressListener.onPartialReduce.get());
    queryPhaseResultConsumer.reduce();
    assertEquals(1, searchProgressListener.onFinalReduce.get());
}
Also used : ScoreDoc(org.apache.lucene.search.ScoreDoc) DocValueFormat(org.opensearch.search.DocValueFormat) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) After(org.junit.After) Before(org.junit.Before) TopDocs(org.apache.lucene.search.TopDocs) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) OriginalIndices(org.opensearch.action.OriginalIndices) TotalHits(org.apache.lucene.search.TotalHits) OpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.OpenSearchThreadPoolExecutor) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SearchShardTarget(org.opensearch.search.SearchShardTarget) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) PipelineAggregator(org.opensearch.search.aggregations.pipeline.PipelineAggregator) BigArrays(org.opensearch.common.util.BigArrays) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) Collections(java.util.Collections) TotalHits(org.apache.lucene.search.TotalHits) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker)

Example 17 with QuerySearchResult

use of org.opensearch.search.query.QuerySearchResult in project security by opensearch-project.

the class DlsFlsValveImpl method onQueryPhase.

@Override
public void onQueryPhase(QuerySearchResult queryResult) {
    InternalAggregations aggregations = queryResult.aggregations().expand();
    assert aggregations != null;
    queryResult.aggregations(InternalAggregations.from(StreamSupport.stream(aggregations.spliterator(), false).map(aggregation -> aggregateBuckets((InternalAggregation) aggregation)).collect(ImmutableList.toImmutableList())));
}
Also used : ResizeRequest(org.opensearch.action.admin.indices.shrink.ResizeRequest) BucketOrder(org.opensearch.search.aggregations.BucketOrder) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) RealtimeRequest(org.opensearch.action.RealtimeRequest) DocValueFormat(org.opensearch.search.DocValueFormat) SearchContext(org.opensearch.search.internal.SearchContext) ThreadPool(org.opensearch.threadpool.ThreadPool) LoggerFactory(org.slf4j.LoggerFactory) BulkRequest(org.opensearch.action.bulk.BulkRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) ActionRequest(org.opensearch.action.ActionRequest) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) ConfigConstants(org.opensearch.security.support.ConfigConstants) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) SearchRequest(org.opensearch.action.search.SearchRequest) StreamSupport(java.util.stream.StreamSupport) SpecialPermission(org.opensearch.SpecialPermission) ActionListener(org.opensearch.action.ActionListener) Bucket(org.opensearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket) BulkItemRequest(org.opensearch.action.bulk.BulkItemRequest) Logger(org.slf4j.Logger) BytesRef(org.apache.lucene.util.BytesRef) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) HeaderHelper(org.opensearch.security.support.HeaderHelper) Set(java.util.Set) RestStatus(org.opensearch.rest.RestStatus) Field(java.lang.reflect.Field) PrivilegedAction(java.security.PrivilegedAction) Objects(java.util.Objects) Consumer(java.util.function.Consumer) OpenSearchSecurityException(org.opensearch.OpenSearchSecurityException) InternalTerms(org.opensearch.search.aggregations.bucket.terms.InternalTerms) List(java.util.List) SecurityUtils(org.opensearch.security.support.SecurityUtils) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) UpdateRequest(org.opensearch.action.update.UpdateRequest) AccessController(java.security.AccessController) Comparator(java.util.Comparator) ParsedQuery(org.opensearch.index.query.ParsedQuery) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations)

Example 18 with QuerySearchResult

use of org.opensearch.search.query.QuerySearchResult in project OpenSearch by opensearch-project.

the class TermsReduceBenchmark method reduceAggs.

@Benchmark
public SearchPhaseController.ReducedQueryPhase reduceAggs(TermsList candidateList) throws Exception {
    List<QuerySearchResult> shards = new ArrayList<>();
    for (int i = 0; i < candidateList.size(); i++) {
        QuerySearchResult result = new QuerySearchResult();
        result.setShardIndex(i);
        result.from(0);
        result.size(0);
        result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1000, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), new ScoreDoc[0]), Float.NaN), new DocValueFormat[] { DocValueFormat.RAW });
        result.aggregations(candidateList.get(i));
        result.setSearchShardTarget(new SearchShardTarget("node", new ShardId(new Index("index", "index"), i), null, OriginalIndices.NONE));
        shards.add(result);
    }
    SearchRequest request = new SearchRequest();
    request.source(new SearchSourceBuilder().size(0).aggregation(AggregationBuilders.terms("test")));
    request.setBatchedReduceSize(bufferSize);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    QueryPhaseResultConsumer consumer = new QueryPhaseResultConsumer(request, executor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), controller, SearchProgressListener.NOOP, namedWriteableRegistry, shards.size(), exc -> {
    });
    CountDownLatch latch = new CountDownLatch(shards.size());
    for (int i = 0; i < shards.size(); i++) {
        consumer.consumeResult(shards.get(i), () -> latch.countDown());
    }
    latch.await();
    SearchPhaseController.ReducedQueryPhase phase = consumer.reduce();
    executor.shutdownNow();
    return phase;
}
Also used : TotalHits(org.apache.lucene.search.TotalHits) SearchRequest(org.opensearch.action.search.SearchRequest) ArrayList(java.util.ArrayList) QueryPhaseResultConsumer(org.opensearch.action.search.QueryPhaseResultConsumer) Index(org.opensearch.index.Index) CountDownLatch(java.util.concurrent.CountDownLatch) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocs(org.apache.lucene.search.TopDocs) ShardId(org.opensearch.index.shard.ShardId) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) ExecutorService(java.util.concurrent.ExecutorService) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) SearchPhaseController(org.opensearch.action.search.SearchPhaseController) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 19 with QuerySearchResult

use of org.opensearch.search.query.QuerySearchResult in project OpenSearch by opensearch-project.

the class SearchScrollQueryThenFetchAsyncAction method moveToNextPhase.

@Override
protected SearchPhase moveToNextPhase(BiFunction<String, String, DiscoveryNode> clusterNodeLookup) {
    return new SearchPhase("fetch") {

        @Override
        public void run() {
            final SearchPhaseController.ReducedQueryPhase reducedQueryPhase = searchPhaseController.reducedScrollQueryPhase(queryResults.asList());
            ScoreDoc[] scoreDocs = reducedQueryPhase.sortedTopDocs.scoreDocs;
            if (scoreDocs.length == 0) {
                sendResponse(reducedQueryPhase, fetchResults);
                return;
            }
            final IntArrayList[] docIdsToLoad = searchPhaseController.fillDocIdsToLoad(queryResults.length(), scoreDocs);
            final ScoreDoc[] lastEmittedDocPerShard = searchPhaseController.getLastEmittedDocPerShard(reducedQueryPhase, queryResults.length());
            final CountDown counter = new CountDown(docIdsToLoad.length);
            for (int i = 0; i < docIdsToLoad.length; i++) {
                final int index = i;
                final IntArrayList docIds = docIdsToLoad[index];
                if (docIds != null) {
                    final QuerySearchResult querySearchResult = queryResults.get(index);
                    ScoreDoc lastEmittedDoc = lastEmittedDocPerShard[index];
                    ShardFetchRequest shardFetchRequest = new ShardFetchRequest(querySearchResult.getContextId(), docIds, lastEmittedDoc);
                    SearchShardTarget searchShardTarget = querySearchResult.getSearchShardTarget();
                    DiscoveryNode node = clusterNodeLookup.apply(searchShardTarget.getClusterAlias(), searchShardTarget.getNodeId());
                    assert node != null : "target node is null in secondary phase";
                    Transport.Connection connection = getConnection(searchShardTarget.getClusterAlias(), node);
                    searchTransportService.sendExecuteFetchScroll(connection, shardFetchRequest, task, new SearchActionListener<FetchSearchResult>(querySearchResult.getSearchShardTarget(), index) {

                        @Override
                        protected void innerOnResponse(FetchSearchResult response) {
                            fetchResults.setOnce(response.getShardIndex(), response);
                            if (counter.countDown()) {
                                sendResponse(reducedQueryPhase, fetchResults);
                            }
                        }

                        @Override
                        public void onFailure(Exception t) {
                            onShardFailure(getName(), counter, querySearchResult.getContextId(), t, querySearchResult.getSearchShardTarget(), () -> sendResponsePhase(reducedQueryPhase, fetchResults));
                        }
                    });
                } else {
                    // which can have null values so we have to count them down too
                    if (counter.countDown()) {
                        sendResponse(reducedQueryPhase, fetchResults);
                    }
                }
            }
        }
    };
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) FetchSearchResult(org.opensearch.search.fetch.FetchSearchResult) ShardFetchRequest(org.opensearch.search.fetch.ShardFetchRequest) CountDown(org.opensearch.common.util.concurrent.CountDown) ScoreDoc(org.apache.lucene.search.ScoreDoc) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) ScrollQuerySearchResult(org.opensearch.search.query.ScrollQuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) IntArrayList(com.carrotsearch.hppc.IntArrayList) Transport(org.opensearch.transport.Transport)

Example 20 with QuerySearchResult

use of org.opensearch.search.query.QuerySearchResult in project OpenSearch by opensearch-project.

the class SearchPhaseController method reducedScrollQueryPhase.

/**
 * Reduces the given query results and consumes all aggregations and profile results.
 * @param queryResults a list of non-null query shard results
 */
ReducedQueryPhase reducedScrollQueryPhase(Collection<? extends SearchPhaseResult> queryResults) {
    InternalAggregation.ReduceContextBuilder aggReduceContextBuilder = new InternalAggregation.ReduceContextBuilder() {

        @Override
        public ReduceContext forPartialReduction() {
            throw new UnsupportedOperationException("Scroll requests don't have aggs");
        }

        @Override
        public ReduceContext forFinalReduction() {
            throw new UnsupportedOperationException("Scroll requests don't have aggs");
        }
    };
    final TopDocsStats topDocsStats = new TopDocsStats(SearchContext.TRACK_TOTAL_HITS_ACCURATE);
    final List<TopDocs> topDocs = new ArrayList<>();
    for (SearchPhaseResult sortedResult : queryResults) {
        QuerySearchResult queryResult = sortedResult.queryResult();
        final TopDocsAndMaxScore td = queryResult.consumeTopDocs();
        assert td != null;
        topDocsStats.add(td, queryResult.searchTimedOut(), queryResult.terminatedEarly());
        // make sure we set the shard index before we add it - the consumer didn't do that yet
        if (td.topDocs.scoreDocs.length > 0) {
            setShardIndex(td.topDocs, queryResult.getShardIndex());
            topDocs.add(td.topDocs);
        }
    }
    return reducedQueryPhase(queryResults, Collections.emptyList(), topDocs, topDocsStats, 0, true, aggReduceContextBuilder, true);
}
Also used : InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) TopDocs(org.apache.lucene.search.TopDocs) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) IntArrayList(com.carrotsearch.hppc.IntArrayList) ArrayList(java.util.ArrayList) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore)

Aggregations

QuerySearchResult (org.opensearch.search.query.QuerySearchResult)37 SearchShardTarget (org.opensearch.search.SearchShardTarget)26 TopDocs (org.apache.lucene.search.TopDocs)25 TopDocsAndMaxScore (org.opensearch.common.lucene.search.TopDocsAndMaxScore)25 TotalHits (org.apache.lucene.search.TotalHits)23 ShardId (org.opensearch.index.shard.ShardId)23 NoopCircuitBreaker (org.opensearch.common.breaker.NoopCircuitBreaker)21 ShardSearchContextId (org.opensearch.search.internal.ShardSearchContextId)20 ScoreDoc (org.apache.lucene.search.ScoreDoc)18 CountDownLatch (java.util.concurrent.CountDownLatch)14 ArrayList (java.util.ArrayList)11 SearchPhaseResult (org.opensearch.search.SearchPhaseResult)10 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)10 InternalAggregations (org.opensearch.search.aggregations.InternalAggregations)9 FetchSearchResult (org.opensearch.search.fetch.FetchSearchResult)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 QueryFetchSearchResult (org.opensearch.search.fetch.QueryFetchSearchResult)8 SearchHit (org.opensearch.search.SearchHit)7 SearchHits (org.opensearch.search.SearchHits)7 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)6