Search in sources :

Example 1 with InternalAggregation

use of org.elasticsearch.search.aggregations.InternalAggregation in project elasticsearch by elastic.

the class InternalSingleBucketAggregationTestCase method createTestInstance.

@Override
protected final T createTestInstance(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
    List<InternalAggregation> internal = new ArrayList<>();
    if (hasInternalMax) {
        internal.add(new InternalMax("max", randomDouble(), randomFrom(DocValueFormat.BOOLEAN, DocValueFormat.GEOHASH, DocValueFormat.IP, DocValueFormat.RAW), emptyList(), emptyMap()));
    }
    if (hasInternalMin) {
        internal.add(new InternalMin("min", randomDouble(), randomFrom(DocValueFormat.BOOLEAN, DocValueFormat.GEOHASH, DocValueFormat.IP, DocValueFormat.RAW), emptyList(), emptyMap()));
    }
    // we shouldn't use the full long range here since we sum doc count on reduce, and don't want to overflow the long range there
    long docCount = between(0, Integer.MAX_VALUE);
    return createTestInstance(name, docCount, new InternalAggregations(internal), pipelineAggregators, metaData);
}
Also used : InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) InternalMax(org.elasticsearch.search.aggregations.metrics.max.InternalMax) InternalMin(org.elasticsearch.search.aggregations.metrics.min.InternalMin) ArrayList(java.util.ArrayList)

Example 2 with InternalAggregation

use of org.elasticsearch.search.aggregations.InternalAggregation in project elasticsearch by elastic.

the class SignificanceHeuristicTests method createInternalAggregations.

// Create aggregations as they might come from three different shards and return as list.
private List<InternalAggregation> createInternalAggregations() {
    SignificanceHeuristic significanceHeuristic = getRandomSignificanceheuristic();
    TestAggFactory<?, ?> factory = randomBoolean() ? new StringTestAggFactory() : new LongTestAggFactory();
    List<InternalAggregation> aggs = new ArrayList<>();
    aggs.add(factory.createAggregation(significanceHeuristic, 4, 10, 1, (f, i) -> f.createBucket(4, 4, 5, 10, 0)));
    aggs.add(factory.createAggregation(significanceHeuristic, 4, 10, 1, (f, i) -> f.createBucket(4, 4, 5, 10, 1)));
    aggs.add(factory.createAggregation(significanceHeuristic, 8, 10, 2, (f, i) -> f.createBucket(4, 4, 5, 10, i)));
    return aggs;
}
Also used : InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) BiFunction(java.util.function.BiFunction) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) DocValueFormat(org.elasticsearch.search.DocValueFormat) JsonXContent(org.elasticsearch.common.xcontent.json.JsonXContent) Collections.singletonList(java.util.Collections.singletonList) InputStreamStreamInput(org.elasticsearch.common.io.stream.InputStreamStreamInput) Settings(org.elasticsearch.common.settings.Settings) ByteArrayInputStream(java.io.ByteArrayInputStream) TestSearchContext(org.elasticsearch.test.TestSearchContext) SignificanceHeuristicParser(org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParser) MutualInformation(org.elasticsearch.search.aggregations.bucket.significant.heuristics.MutualInformation) BytesRef(org.apache.lucene.util.BytesRef) Collections.emptyList(java.util.Collections.emptyList) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) ParseFieldRegistry(org.elasticsearch.common.xcontent.ParseFieldRegistry) Collectors(java.util.stream.Collectors) QueryParseContext(org.elasticsearch.index.query.QueryParseContext) StandardCharsets(java.nio.charset.StandardCharsets) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) Version(org.elasticsearch.Version) ChiSquare(org.elasticsearch.search.aggregations.bucket.significant.heuristics.ChiSquare) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.containsString(org.hamcrest.Matchers.containsString) AggregationBuilders.significantTerms(org.elasticsearch.search.aggregations.AggregationBuilders.significantTerms) IntStream(java.util.stream.IntStream) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) SearchShardTarget(org.elasticsearch.search.SearchShardTarget) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ParsingException(org.elasticsearch.common.ParsingException) PercentageScore(org.elasticsearch.search.aggregations.bucket.significant.heuristics.PercentageScore) Index(org.elasticsearch.index.Index) OutputStreamStreamOutput(org.elasticsearch.common.io.stream.OutputStreamStreamOutput) ArrayList(java.util.ArrayList) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) Matchers.lessThan(org.hamcrest.Matchers.lessThan) ESTestCase(org.elasticsearch.test.ESTestCase) VersionUtils.randomVersion(org.elasticsearch.test.VersionUtils.randomVersion) SignificanceHeuristic(org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic) SearchModule(org.elasticsearch.search.SearchModule) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) PipelineAggregator(org.elasticsearch.search.aggregations.pipeline.PipelineAggregator) IOException(java.io.IOException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) GND(org.elasticsearch.search.aggregations.bucket.significant.heuristics.GND) StreamInput(org.elasticsearch.common.io.stream.StreamInput) JLHScore(org.elasticsearch.search.aggregations.bucket.significant.heuristics.JLHScore) ArrayList(java.util.ArrayList) SignificanceHeuristic(org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic)

Example 3 with InternalAggregation

use of org.elasticsearch.search.aggregations.InternalAggregation in project elasticsearch by elastic.

the class TermsAggregatorTests method testMixLongAndDouble.

public void testMixLongAndDouble() throws Exception {
    for (TermsAggregatorFactory.ExecutionMode executionMode : TermsAggregatorFactory.ExecutionMode.values()) {
        TermsAggregationBuilder aggregationBuilder = new TermsAggregationBuilder("_name", ValueType.LONG).executionHint(executionMode.toString()).field("number").order(Terms.Order.term(true));
        List<InternalAggregation> aggs = new ArrayList<>();
        int numLongs = randomIntBetween(1, 3);
        for (int i = 0; i < numLongs; i++) {
            final Directory dir;
            try (IndexReader reader = createIndexWithLongs()) {
                dir = ((DirectoryReader) reader).directory();
                IndexSearcher searcher = new IndexSearcher(reader);
                MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.LONG);
                fieldType.setName("number");
                fieldType.setHasDocValues(true);
                aggs.add(buildInternalAggregation(aggregationBuilder, fieldType, searcher));
            }
            dir.close();
        }
        int numDoubles = randomIntBetween(1, 3);
        for (int i = 0; i < numDoubles; i++) {
            final Directory dir;
            try (IndexReader reader = createIndexWithDoubles()) {
                dir = ((DirectoryReader) reader).directory();
                IndexSearcher searcher = new IndexSearcher(reader);
                MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.DOUBLE);
                fieldType.setName("number");
                fieldType.setHasDocValues(true);
                aggs.add(buildInternalAggregation(aggregationBuilder, fieldType, searcher));
            }
            dir.close();
        }
        InternalAggregation.ReduceContext ctx = new InternalAggregation.ReduceContext(new MockBigArrays(Settings.EMPTY, new NoneCircuitBreakerService()), null, true);
        for (InternalAggregation internalAgg : aggs) {
            InternalAggregation mergedAggs = internalAgg.doReduce(aggs, ctx);
            assertTrue(mergedAggs instanceof DoubleTerms);
            long expected = numLongs + numDoubles;
            List<Terms.Bucket> buckets = ((DoubleTerms) mergedAggs).getBuckets();
            assertEquals(4, buckets.size());
            assertEquals("1.0", buckets.get(0).getKeyAsString());
            assertEquals(expected, buckets.get(0).getDocCount());
            assertEquals("10.0", buckets.get(1).getKeyAsString());
            assertEquals(expected * 2, buckets.get(1).getDocCount());
            assertEquals("100.0", buckets.get(2).getKeyAsString());
            assertEquals(expected * 2, buckets.get(2).getDocCount());
            assertEquals("1000.0", buckets.get(3).getKeyAsString());
            assertEquals(expected, buckets.get(3).getDocCount());
        }
    }
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) ArrayList(java.util.ArrayList) MockBigArrays(org.elasticsearch.common.util.MockBigArrays) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) IndexReader(org.apache.lucene.index.IndexReader) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) Directory(org.apache.lucene.store.Directory) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Example 4 with InternalAggregation

use of org.elasticsearch.search.aggregations.InternalAggregation in project elasticsearch by elastic.

the class BucketScriptPipelineAggregator method reduce.

@Override
public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext reduceContext) {
    InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket> originalAgg = (InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
    List<? extends Bucket> buckets = originalAgg.getBuckets();
    CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS);
    List newBuckets = new ArrayList<>();
    for (Bucket bucket : buckets) {
        Map<String, Object> vars = new HashMap<>();
        if (script.getParams() != null) {
            vars.putAll(script.getParams());
        }
        boolean skipBucket = false;
        for (Map.Entry<String, String> entry : bucketsPathsMap.entrySet()) {
            String varName = entry.getKey();
            String bucketsPath = entry.getValue();
            Double value = resolveBucketValue(originalAgg, bucket, bucketsPath, gapPolicy);
            if (GapPolicy.SKIP == gapPolicy && (value == null || Double.isNaN(value))) {
                skipBucket = true;
                break;
            }
            vars.put(varName, value);
        }
        if (skipBucket) {
            newBuckets.add(bucket);
        } else {
            ExecutableScript executableScript = reduceContext.scriptService().executable(compiledScript, vars);
            Object returned = executableScript.run();
            if (returned == null) {
                newBuckets.add(bucket);
            } else {
                if (!(returned instanceof Number)) {
                    throw new AggregationExecutionException("series_arithmetic script for reducer [" + name() + "] must return a Number");
                }
                final List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false).map((p) -> {
                    return (InternalAggregation) p;
                }).collect(Collectors.toList());
                aggs.add(new InternalSimpleValue(name(), ((Number) returned).doubleValue(), formatter, new ArrayList<>(), metaData()));
                InternalMultiBucketAggregation.InternalBucket newBucket = originalAgg.createBucket(new InternalAggregations(aggs), (InternalMultiBucketAggregation.InternalBucket) bucket);
                newBuckets.add(newBucket);
            }
        }
    }
    return originalAgg.create(newBuckets);
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) HashMap(java.util.HashMap) DocValueFormat(org.elasticsearch.search.DocValueFormat) ScriptContext(org.elasticsearch.script.ScriptContext) ArrayList(java.util.ArrayList) InternalMultiBucketAggregation(org.elasticsearch.search.aggregations.InternalMultiBucketAggregation) BucketHelpers.resolveBucketValue(org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) Bucket(org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket) Map(java.util.Map) GapPolicy(org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy) StreamSupport(java.util.stream.StreamSupport) AggregationExecutionException(org.elasticsearch.search.aggregations.AggregationExecutionException) Script(org.elasticsearch.script.Script) PipelineAggregator(org.elasticsearch.search.aggregations.pipeline.PipelineAggregator) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) ReduceContext(org.elasticsearch.search.aggregations.InternalAggregation.ReduceContext) List(java.util.List) CompiledScript(org.elasticsearch.script.CompiledScript) InternalSimpleValue(org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ExecutableScript(org.elasticsearch.script.ExecutableScript) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExecutableScript(org.elasticsearch.script.ExecutableScript) ArrayList(java.util.ArrayList) List(java.util.List) InternalMultiBucketAggregation(org.elasticsearch.search.aggregations.InternalMultiBucketAggregation) AggregationExecutionException(org.elasticsearch.search.aggregations.AggregationExecutionException) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) InternalSimpleValue(org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) Bucket(org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with InternalAggregation

use of org.elasticsearch.search.aggregations.InternalAggregation in project elasticsearch by elastic.

the class DoubleTerms method doReduce.

@Override
public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
    boolean promoteToDouble = false;
    for (InternalAggregation agg : aggregations) {
        if (agg instanceof LongTerms && ((LongTerms) agg).format == DocValueFormat.RAW) {
            /**
                 * this terms agg mixes longs and doubles, we must promote longs to doubles to make the internal aggs
                 * compatible
                 */
            promoteToDouble = true;
            break;
        }
    }
    if (promoteToDouble == false) {
        return super.doReduce(aggregations, reduceContext);
    }
    List<InternalAggregation> newAggs = new ArrayList<>();
    for (InternalAggregation agg : aggregations) {
        if (agg instanceof LongTerms) {
            DoubleTerms dTerms = LongTerms.convertLongTermsToDouble((LongTerms) agg, format);
            newAggs.add(dTerms);
        } else {
            newAggs.add(agg);
        }
    }
    return newAggs.get(0).doReduce(newAggs, reduceContext);
}
Also used : InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) ArrayList(java.util.ArrayList)

Aggregations

InternalAggregation (org.elasticsearch.search.aggregations.InternalAggregation)33 ArrayList (java.util.ArrayList)23 List (java.util.List)16 Map (java.util.Map)10 InternalAggregations (org.elasticsearch.search.aggregations.InternalAggregations)10 IOException (java.io.IOException)8 Collectors (java.util.stream.Collectors)8 PipelineAggregator (org.elasticsearch.search.aggregations.pipeline.PipelineAggregator)8 StreamSupport (java.util.stream.StreamSupport)7 StreamInput (org.elasticsearch.common.io.stream.StreamInput)7 ReduceContext (org.elasticsearch.search.aggregations.InternalAggregation.ReduceContext)7 Bucket (org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket)7 InternalSimpleValue (org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue)6 HashMap (java.util.HashMap)5 DocValueFormat (org.elasticsearch.search.DocValueFormat)5 StreamOutput (org.elasticsearch.common.io.stream.StreamOutput)4 Settings (org.elasticsearch.common.settings.Settings)4 SignificanceHeuristic (org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic)4 GapPolicy (org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy)4 BucketHelpers.resolveBucketValue (org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue)4