Search in sources :

Example 1 with InternalMax

use of org.opensearch.search.aggregations.metrics.InternalMax in project OpenSearch by opensearch-project.

the class SearchPhaseControllerTests method testConsumerConcurrently.

public void testConsumerConcurrently() throws Exception {
    int expectedNumResults = randomIntBetween(1, 100);
    int bufferSize = randomIntBetween(2, 200);
    SearchRequest request = randomSearchRequest();
    request.source(new SearchSourceBuilder().aggregation(AggregationBuilders.avg("foo")));
    request.setBatchedReduceSize(bufferSize);
    ArraySearchPhaseResults<SearchPhaseResult> consumer = searchPhaseController.newSearchPhaseResults(fixedExecutor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), SearchProgressListener.NOOP, request, expectedNumResults, exc -> {
    });
    AtomicInteger max = new AtomicInteger();
    Thread[] threads = new Thread[expectedNumResults];
    CountDownLatch latch = new CountDownLatch(expectedNumResults);
    for (int i = 0; i < expectedNumResults; i++) {
        int id = i;
        threads[i] = new Thread(() -> {
            int number = randomIntBetween(1, 1000);
            max.updateAndGet(prev -> Math.max(prev, number));
            QuerySearchResult result = new QuerySearchResult(new ShardSearchContextId("", id), new SearchShardTarget("node", new ShardId("a", "b", id), null, OriginalIndices.NONE), null);
            result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(0, number) }), number), new DocValueFormat[0]);
            InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new InternalMax("test", (double) number, DocValueFormat.RAW, Collections.emptyMap())));
            result.aggregations(aggs);
            result.setShardIndex(id);
            result.size(1);
            consumer.consumeResult(result, latch::countDown);
        });
        threads[i].start();
    }
    for (int i = 0; i < expectedNumResults; i++) {
        threads[i].join();
    }
    latch.await();
    SearchPhaseController.ReducedQueryPhase reduce = consumer.reduce();
    assertAggReduction(request);
    InternalMax internalMax = (InternalMax) reduce.aggregations.asList().get(0);
    assertEquals(max.get(), internalMax.getValue(), 0.0D);
    assertEquals(1, reduce.sortedTopDocs.scoreDocs.length);
    assertEquals(max.get(), reduce.maxScore, 0.0f);
    assertEquals(expectedNumResults, reduce.totalHits.value);
    assertEquals(max.get(), reduce.sortedTopDocs.scoreDocs[0].score, 0.0f);
    assertFalse(reduce.sortedTopDocs.isSortedByField);
    assertNull(reduce.sortedTopDocs.sortFields);
    assertNull(reduce.sortedTopDocs.collapseField);
    assertNull(reduce.sortedTopDocs.collapseValues);
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) SearchContext(org.opensearch.search.internal.SearchContext) TestThreadPool(org.opensearch.threadpool.TestThreadPool) FieldDoc(org.apache.lucene.search.FieldDoc) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) SortBy(org.opensearch.search.suggest.SortBy) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) CollapseTopFieldDocs(org.apache.lucene.search.grouping.CollapseTopFieldDocs) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) After(org.junit.After) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) SortField(org.apache.lucene.search.SortField) RandomizedContext(com.carrotsearch.randomizedtesting.RandomizedContext) BytesRef(org.apache.lucene.util.BytesRef) SearchHit(org.opensearch.search.SearchHit) Collections.emptyList(java.util.Collections.emptyList) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Settings(org.opensearch.common.settings.Settings) CompletionSuggestion(org.opensearch.search.suggest.completion.CompletionSuggestion) PhraseSuggestion(org.opensearch.search.suggest.phrase.PhraseSuggestion) Collectors(java.util.stream.Collectors) OriginalIndices(org.opensearch.action.OriginalIndices) OpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.OpenSearchThreadPoolExecutor) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) TopFieldDocs(org.apache.lucene.search.TopFieldDocs) BigArrays(org.opensearch.common.util.BigArrays) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) Matchers.containsString(org.hamcrest.Matchers.containsString) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TermSuggestion(org.opensearch.search.suggest.term.TermSuggestion) DocValueFormat(org.opensearch.search.DocValueFormat) ReduceContext(org.opensearch.search.aggregations.InternalAggregation.ReduceContext) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) PipelineTree(org.opensearch.search.aggregations.pipeline.PipelineAggregator.PipelineTree) Matchers.lessThan(org.hamcrest.Matchers.lessThan) UUIDs(org.opensearch.common.UUIDs) Before(org.junit.Before) CircuitBreakingException(org.opensearch.common.breaker.CircuitBreakingException) TopDocs(org.apache.lucene.search.TopDocs) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Relation(org.apache.lucene.search.TotalHits.Relation) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) TotalHits(org.apache.lucene.search.TotalHits) ShardId(org.opensearch.index.shard.ShardId) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) SearchShardTarget(org.opensearch.search.SearchShardTarget) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) Suggest(org.opensearch.search.suggest.Suggest) FetchSearchResult(org.opensearch.search.fetch.FetchSearchResult) Collections(java.util.Collections) Text(org.opensearch.common.text.Text) SearchModule(org.opensearch.search.SearchModule) TotalHits(org.apache.lucene.search.TotalHits) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) DocValueFormat(org.opensearch.search.DocValueFormat) CountDownLatch(java.util.concurrent.CountDownLatch) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker)

Example 2 with InternalMax

use of org.opensearch.search.aggregations.metrics.InternalMax in project OpenSearch by opensearch-project.

the class SearchPhaseControllerTests method testConsumerOnlyAggs.

public void testConsumerOnlyAggs() throws Exception {
    int expectedNumResults = randomIntBetween(1, 100);
    int bufferSize = randomIntBetween(2, 200);
    SearchRequest request = randomSearchRequest();
    request.source(new SearchSourceBuilder().aggregation(AggregationBuilders.avg("foo")).size(0));
    request.setBatchedReduceSize(bufferSize);
    QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(fixedExecutor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), SearchProgressListener.NOOP, request, expectedNumResults, exc -> {
    });
    AtomicInteger max = new AtomicInteger();
    CountDownLatch latch = new CountDownLatch(expectedNumResults);
    for (int i = 0; i < expectedNumResults; i++) {
        int number = randomIntBetween(1, 1000);
        max.updateAndGet(prev -> Math.max(prev, number));
        QuerySearchResult result = new QuerySearchResult(new ShardSearchContextId("", i), new SearchShardTarget("node", new ShardId("a", "b", i), null, OriginalIndices.NONE), null);
        result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[0]), number), new DocValueFormat[0]);
        InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new InternalMax("test", (double) number, DocValueFormat.RAW, Collections.emptyMap())));
        result.aggregations(aggs);
        result.setShardIndex(i);
        result.size(1);
        consumer.consumeResult(result, latch::countDown);
    }
    latch.await();
    SearchPhaseController.ReducedQueryPhase reduce = consumer.reduce();
    assertAggReduction(request);
    InternalMax internalMax = (InternalMax) reduce.aggregations.asList().get(0);
    assertEquals(max.get(), internalMax.getValue(), 0.0D);
    assertEquals(0, reduce.sortedTopDocs.scoreDocs.length);
    assertEquals(max.get(), reduce.maxScore, 0.0f);
    assertEquals(expectedNumResults, reduce.totalHits.value);
    assertFalse(reduce.sortedTopDocs.isSortedByField);
    assertNull(reduce.sortedTopDocs.sortFields);
    assertNull(reduce.sortedTopDocs.collapseField);
    assertNull(reduce.sortedTopDocs.collapseValues);
}
Also used : TotalHits(org.apache.lucene.search.TotalHits) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) CountDownLatch(java.util.concurrent.CountDownLatch) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker)

Example 3 with InternalMax

use of org.opensearch.search.aggregations.metrics.InternalMax in project OpenSearch by opensearch-project.

the class SearchPhaseControllerTests method testProgressListener.

public void testProgressListener() throws Exception {
    int expectedNumResults = randomIntBetween(10, 100);
    for (int bufferSize : new int[] { expectedNumResults, expectedNumResults / 2, expectedNumResults / 4, 2 }) {
        SearchRequest request = randomSearchRequest();
        request.source(new SearchSourceBuilder().aggregation(AggregationBuilders.avg("foo")));
        request.setBatchedReduceSize(bufferSize);
        AtomicInteger numQueryResultListener = new AtomicInteger();
        AtomicInteger numQueryFailureListener = new AtomicInteger();
        AtomicInteger numReduceListener = new AtomicInteger();
        AtomicReference<InternalAggregations> finalAggsListener = new AtomicReference<>();
        AtomicReference<TotalHits> totalHitsListener = new AtomicReference<>();
        SearchProgressListener progressListener = new SearchProgressListener() {

            @Override
            public void onQueryResult(int shardIndex) {
                assertThat(shardIndex, lessThan(expectedNumResults));
                numQueryResultListener.incrementAndGet();
            }

            @Override
            public void onQueryFailure(int shardIndex, SearchShardTarget shardTarget, Exception exc) {
                assertThat(shardIndex, lessThan(expectedNumResults));
                numQueryFailureListener.incrementAndGet();
            }

            @Override
            public void onPartialReduce(List<SearchShard> shards, TotalHits totalHits, InternalAggregations aggs, int reducePhase) {
                assertEquals(numReduceListener.incrementAndGet(), reducePhase);
            }

            @Override
            public void onFinalReduce(List<SearchShard> shards, TotalHits totalHits, InternalAggregations aggs, int reducePhase) {
                totalHitsListener.set(totalHits);
                finalAggsListener.set(aggs);
                assertEquals(numReduceListener.incrementAndGet(), reducePhase);
            }
        };
        QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(fixedExecutor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), progressListener, request, expectedNumResults, exc -> {
        });
        AtomicInteger max = new AtomicInteger();
        Thread[] threads = new Thread[expectedNumResults];
        CountDownLatch latch = new CountDownLatch(expectedNumResults);
        for (int i = 0; i < expectedNumResults; i++) {
            int id = i;
            threads[i] = new Thread(() -> {
                int number = randomIntBetween(1, 1000);
                max.updateAndGet(prev -> Math.max(prev, number));
                QuerySearchResult result = new QuerySearchResult(new ShardSearchContextId("", id), new SearchShardTarget("node", new ShardId("a", "b", id), null, OriginalIndices.NONE), null);
                result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(0, number) }), number), new DocValueFormat[0]);
                InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new InternalMax("test", (double) number, DocValueFormat.RAW, Collections.emptyMap())));
                result.aggregations(aggs);
                result.setShardIndex(id);
                result.size(1);
                consumer.consumeResult(result, latch::countDown);
            });
            threads[i].start();
        }
        for (int i = 0; i < expectedNumResults; i++) {
            threads[i].join();
        }
        latch.await();
        SearchPhaseController.ReducedQueryPhase reduce = consumer.reduce();
        assertAggReduction(request);
        InternalMax internalMax = (InternalMax) reduce.aggregations.asList().get(0);
        assertEquals(max.get(), internalMax.getValue(), 0.0D);
        assertEquals(1, reduce.sortedTopDocs.scoreDocs.length);
        assertEquals(max.get(), reduce.maxScore, 0.0f);
        assertEquals(expectedNumResults, reduce.totalHits.value);
        assertEquals(max.get(), reduce.sortedTopDocs.scoreDocs[0].score, 0.0f);
        assertFalse(reduce.sortedTopDocs.isSortedByField);
        assertNull(reduce.sortedTopDocs.sortFields);
        assertNull(reduce.sortedTopDocs.collapseField);
        assertNull(reduce.sortedTopDocs.collapseValues);
        assertEquals(reduce.aggregations, finalAggsListener.get());
        assertEquals(reduce.totalHits, totalHitsListener.get());
        assertEquals(expectedNumResults, numQueryResultListener.get());
        assertEquals(0, numQueryFailureListener.get());
        assertEquals(numReduceListener.get(), reduce.numReducePhases);
    }
}
Also used : TotalHits(org.apache.lucene.search.TotalHits) InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) SearchContext(org.opensearch.search.internal.SearchContext) TestThreadPool(org.opensearch.threadpool.TestThreadPool) FieldDoc(org.apache.lucene.search.FieldDoc) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) SortBy(org.opensearch.search.suggest.SortBy) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) CollapseTopFieldDocs(org.apache.lucene.search.grouping.CollapseTopFieldDocs) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) After(org.junit.After) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) SortField(org.apache.lucene.search.SortField) RandomizedContext(com.carrotsearch.randomizedtesting.RandomizedContext) BytesRef(org.apache.lucene.util.BytesRef) SearchHit(org.opensearch.search.SearchHit) Collections.emptyList(java.util.Collections.emptyList) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Settings(org.opensearch.common.settings.Settings) CompletionSuggestion(org.opensearch.search.suggest.completion.CompletionSuggestion) PhraseSuggestion(org.opensearch.search.suggest.phrase.PhraseSuggestion) Collectors(java.util.stream.Collectors) OriginalIndices(org.opensearch.action.OriginalIndices) OpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.OpenSearchThreadPoolExecutor) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) TopFieldDocs(org.apache.lucene.search.TopFieldDocs) BigArrays(org.opensearch.common.util.BigArrays) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) Matchers.containsString(org.hamcrest.Matchers.containsString) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TermSuggestion(org.opensearch.search.suggest.term.TermSuggestion) DocValueFormat(org.opensearch.search.DocValueFormat) ReduceContext(org.opensearch.search.aggregations.InternalAggregation.ReduceContext) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) PipelineTree(org.opensearch.search.aggregations.pipeline.PipelineAggregator.PipelineTree) Matchers.lessThan(org.hamcrest.Matchers.lessThan) UUIDs(org.opensearch.common.UUIDs) Before(org.junit.Before) CircuitBreakingException(org.opensearch.common.breaker.CircuitBreakingException) TopDocs(org.apache.lucene.search.TopDocs) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Relation(org.apache.lucene.search.TotalHits.Relation) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) TotalHits(org.apache.lucene.search.TotalHits) ShardId(org.opensearch.index.shard.ShardId) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) SearchShardTarget(org.opensearch.search.SearchShardTarget) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) Suggest(org.opensearch.search.suggest.Suggest) FetchSearchResult(org.opensearch.search.fetch.FetchSearchResult) Collections(java.util.Collections) Text(org.opensearch.common.text.Text) SearchModule(org.opensearch.search.SearchModule) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) Collections.singletonList(java.util.Collections.singletonList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) DocValueFormat(org.opensearch.search.DocValueFormat) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) CircuitBreakingException(org.opensearch.common.breaker.CircuitBreakingException) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget)

Example 4 with InternalMax

use of org.opensearch.search.aggregations.metrics.InternalMax in project OpenSearch by opensearch-project.

the class CompositeAggregatorTests method testWithTermsSubAggExecutionMode.

public void testWithTermsSubAggExecutionMode() throws Exception {
    // test with no bucket
    for (Aggregator.SubAggCollectionMode mode : Aggregator.SubAggCollectionMode.values()) {
        testSearchCase(Arrays.asList(new MatchAllDocsQuery(), new DocValuesFieldExistsQuery("keyword")), Collections.singletonList(createDocument()), () -> {
            TermsValuesSourceBuilder terms = new TermsValuesSourceBuilder("keyword").field("keyword");
            return new CompositeAggregationBuilder("name", Collections.singletonList(terms)).subAggregation(new TermsAggregationBuilder("terms").userValueTypeHint(ValueType.STRING).field("terms").collectMode(mode).subAggregation(new MaxAggregationBuilder("max").field("long")));
        }, (result) -> {
            assertEquals(0, result.getBuckets().size());
        });
    }
    final List<Map<String, List<Object>>> dataset = new ArrayList<>();
    dataset.addAll(Arrays.asList(createDocument("keyword", "a", "terms", "a", "long", 50L), createDocument("keyword", "c", "terms", "d", "long", 78L), createDocument("keyword", "a", "terms", "w", "long", 78L), createDocument("keyword", "d", "terms", "y", "long", 76L), createDocument("keyword", "c", "terms", "y", "long", 70L)));
    for (Aggregator.SubAggCollectionMode mode : Aggregator.SubAggCollectionMode.values()) {
        testSearchCase(Arrays.asList(new MatchAllDocsQuery(), new DocValuesFieldExistsQuery("keyword")), dataset, () -> {
            TermsValuesSourceBuilder terms = new TermsValuesSourceBuilder("keyword").field("keyword");
            return new CompositeAggregationBuilder("name", Collections.singletonList(terms)).subAggregation(new TermsAggregationBuilder("terms").userValueTypeHint(ValueType.STRING).field("terms").collectMode(mode).subAggregation(new MaxAggregationBuilder("max").field("long")));
        }, (result) -> {
            assertEquals(3, result.getBuckets().size());
            assertEquals("{keyword=a}", result.getBuckets().get(0).getKeyAsString());
            assertEquals(2L, result.getBuckets().get(0).getDocCount());
            StringTerms subTerms = result.getBuckets().get(0).getAggregations().get("terms");
            assertEquals(2, subTerms.getBuckets().size());
            assertEquals("a", subTerms.getBuckets().get(0).getKeyAsString());
            assertEquals("w", subTerms.getBuckets().get(1).getKeyAsString());
            InternalMax max = subTerms.getBuckets().get(0).getAggregations().get("max");
            assertEquals(50L, (long) max.getValue());
            max = subTerms.getBuckets().get(1).getAggregations().get("max");
            assertEquals(78L, (long) max.getValue());
            assertEquals("{keyword=c}", result.getBuckets().get(1).getKeyAsString());
            assertEquals(2L, result.getBuckets().get(1).getDocCount());
            subTerms = result.getBuckets().get(1).getAggregations().get("terms");
            assertEquals(2, subTerms.getBuckets().size());
            assertEquals("d", subTerms.getBuckets().get(0).getKeyAsString());
            assertEquals("y", subTerms.getBuckets().get(1).getKeyAsString());
            max = subTerms.getBuckets().get(0).getAggregations().get("max");
            assertEquals(78L, (long) max.getValue());
            max = subTerms.getBuckets().get(1).getAggregations().get("max");
            assertEquals(70L, (long) max.getValue());
            assertEquals("{keyword=d}", result.getBuckets().get(2).getKeyAsString());
            assertEquals(1L, result.getBuckets().get(2).getDocCount());
            subTerms = result.getBuckets().get(2).getAggregations().get("terms");
            assertEquals(1, subTerms.getBuckets().size());
            assertEquals("y", subTerms.getBuckets().get(0).getKeyAsString());
            max = subTerms.getBuckets().get(0).getAggregations().get("max");
            assertEquals(76L, (long) max.getValue());
        });
    }
}
Also used : InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) ArrayList(java.util.ArrayList) Aggregator(org.opensearch.search.aggregations.Aggregator) DocValuesFieldExistsQuery(org.apache.lucene.search.DocValuesFieldExistsQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) MaxAggregationBuilder(org.opensearch.search.aggregations.metrics.MaxAggregationBuilder) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) StringTerms(org.opensearch.search.aggregations.bucket.terms.StringTerms) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with InternalMax

use of org.opensearch.search.aggregations.metrics.InternalMax in project OpenSearch by opensearch-project.

the class NestedAggregatorTests method testNestedWithPipeline.

/**
 * This tests to make sure pipeline aggs embedded under a SingleBucket agg (like nested)
 * are properly reduced
 */
public void testNestedWithPipeline() throws IOException {
    int numRootDocs = randomIntBetween(1, 20);
    int expectedNestedDocs = 0;
    double expectedMaxValue = Double.NEGATIVE_INFINITY;
    try (Directory directory = newDirectory()) {
        try (RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
            for (int i = 0; i < numRootDocs; i++) {
                List<Document> documents = new ArrayList<>();
                expectedMaxValue = Math.max(expectedMaxValue, generateMaxDocs(documents, 1, i, NESTED_OBJECT, VALUE_FIELD_NAME));
                expectedNestedDocs += 1;
                Document document = new Document();
                document.add(new Field(IdFieldMapper.NAME, Uid.encodeId(Integer.toString(i)), IdFieldMapper.Defaults.FIELD_TYPE));
                document.add(sequenceIDFields.primaryTerm);
                documents.add(document);
                iw.addDocuments(documents);
            }
            iw.commit();
        }
        try (IndexReader indexReader = wrapInMockESDirectoryReader(DirectoryReader.open(directory))) {
            NestedAggregationBuilder nestedBuilder = new NestedAggregationBuilder(NESTED_AGG, NESTED_OBJECT).subAggregation(new TermsAggregationBuilder("terms").field(VALUE_FIELD_NAME).userValueTypeHint(ValueType.NUMERIC).subAggregation(new MaxAggregationBuilder(MAX_AGG_NAME).field(VALUE_FIELD_NAME)).subAggregation(new BucketScriptPipelineAggregationBuilder("bucketscript", Collections.singletonMap("_value", MAX_AGG_NAME), new Script(ScriptType.INLINE, MockScriptEngine.NAME, INVERSE_SCRIPT, Collections.emptyMap()))));
            MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType(VALUE_FIELD_NAME, NumberFieldMapper.NumberType.LONG);
            InternalNested nested = searchAndReduce(newSearcher(indexReader, false, true), new MatchAllDocsQuery(), nestedBuilder, fieldType);
            assertEquals(expectedNestedDocs, nested.getDocCount());
            assertEquals(NESTED_AGG, nested.getName());
            assertEquals(expectedNestedDocs, nested.getDocCount());
            InternalTerms<?, LongTerms.Bucket> terms = (InternalTerms) nested.getProperty("terms");
            assertNotNull(terms);
            for (LongTerms.Bucket bucket : terms.getBuckets()) {
                InternalMax max = (InternalMax) bucket.getAggregations().asMap().get(MAX_AGG_NAME);
                InternalSimpleValue bucketScript = (InternalSimpleValue) bucket.getAggregations().asMap().get("bucketscript");
                assertNotNull(max);
                assertNotNull(bucketScript);
                assertEquals(max.getValue(), -bucketScript.getValue(), Double.MIN_VALUE);
            }
            assertTrue(AggregationInspectionHelper.hasValue(nested));
        }
    }
}
Also used : BucketScriptPipelineAggregationBuilder(org.opensearch.search.aggregations.pipeline.BucketScriptPipelineAggregationBuilder) ArrayList(java.util.ArrayList) Document(org.apache.lucene.document.Document) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) Field(org.apache.lucene.document.Field) MaxAggregationBuilder(org.opensearch.search.aggregations.metrics.MaxAggregationBuilder) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Directory(org.apache.lucene.store.Directory) Script(org.opensearch.script.Script) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) InternalSimpleValue(org.opensearch.search.aggregations.pipeline.InternalSimpleValue) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) InternalTerms(org.opensearch.search.aggregations.bucket.terms.InternalTerms) IndexReader(org.apache.lucene.index.IndexReader) LongTerms(org.opensearch.search.aggregations.bucket.terms.LongTerms) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter)

Aggregations

InternalMax (org.opensearch.search.aggregations.metrics.InternalMax)19 ArrayList (java.util.ArrayList)10 MaxAggregationBuilder (org.opensearch.search.aggregations.metrics.MaxAggregationBuilder)9 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)7 IndexReader (org.apache.lucene.index.IndexReader)6 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)6 Directory (org.apache.lucene.store.Directory)6 MappedFieldType (org.opensearch.index.mapper.MappedFieldType)6 InternalAggregations (org.opensearch.search.aggregations.InternalAggregations)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 TopDocs (org.apache.lucene.search.TopDocs)5 TotalHits (org.apache.lucene.search.TotalHits)5 TopDocsAndMaxScore (org.opensearch.common.lucene.search.TopDocsAndMaxScore)5 ShardId (org.opensearch.index.shard.ShardId)5 SearchShardTarget (org.opensearch.search.SearchShardTarget)5 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)5 ShardSearchContextId (org.opensearch.search.internal.ShardSearchContextId)5 QuerySearchResult (org.opensearch.search.query.QuerySearchResult)5 NoopCircuitBreaker (org.opensearch.common.breaker.NoopCircuitBreaker)4 HashMap (java.util.HashMap)3