org.elasticsearch.search.aggregations.BucketOrder Java Examples

The following examples show how to use org.elasticsearch.search.aggregations.BucketOrder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TermsAggregationParser.java    From elasticsearch-sql with MIT License 6 votes vote down vote up
@Override
public void parseAggregateItemClauseContext(AggregateQuery aggregateQuery, ElasticsearchParser.AggregateItemClauseContext aggregateItemClauseContext) {
    if (StringUtils.equalsIgnoreCase(aggregateItemClauseContext.ID().getText(), AGG_TERMS_METHOD)) {
        try {
            String field = aggregateItemClauseContext.collection().identity(0).getText();
            int size = 10;
            if (aggregateItemClauseContext.collection().identity().size() > 1) {
                size = Integer.parseInt(aggregateItemClauseContext.collection().identity(1).getText());
            }
            aggregateQuery.setAggregationBuilder(AggregationBuilders.terms(field + "_terms").field(field).size(size)
                    .minDocCount(1).shardMinDocCount(1).shardSize(size << 1).order(BucketOrder.count(false)));
        } catch (IllegalArgumentException e) {
            throw new ElasticSql2DslException(e);
        }
    }
}
 
Example #2
Source File: PathHierarchyAggregatorFactory.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
PathHierarchyAggregatorFactory(String name,
                               ValuesSourceConfig<ValuesSource> config,
                               String separator,
                               int minDepth,
                               int maxDepth,
                               boolean keepBlankPath,
                               BucketOrder order,
                               long minDocCount,
                               PathHierarchyAggregator.BucketCountThresholds bucketCountThresholds,
                               QueryShardContext context,
                               AggregatorFactory parent,
                               AggregatorFactories.Builder subFactoriesBuilder,
                               Map<String, Object> metaData
) throws IOException {
    super(name, config, context, parent, subFactoriesBuilder, metaData);
    this.separator = new BytesRef(separator);
    this.minDepth = minDepth;
    this.maxDepth = maxDepth;
    this.keepBlankPath = keepBlankPath;
    this.order = order;
    this.minDocCount = minDocCount;
    this.bucketCountThresholds = bucketCountThresholds;
}
 
Example #3
Source File: DateHierarchyAggregatorFactory.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
DateHierarchyAggregatorFactory(String name,
                               ValuesSourceConfig<ValuesSource.Numeric> config,
                               BucketOrder order,
                               List<DateHierarchyAggregationBuilder.RoundingInfo> roundingsInfo,
                               long minDocCount,
                               DateHierarchyAggregator.BucketCountThresholds bucketCountThresholds,
                               QueryShardContext context,
                               AggregatorFactory parent,
                               AggregatorFactories.Builder subFactoriesBuilder,
                               Map<String, Object> metaData
) throws IOException {
    super(name, config, context, parent, subFactoriesBuilder, metaData);
    this.order = order;
    this.roundingsInfo = roundingsInfo;
    this.minDocCount = minDocCount;
    this.bucketCountThresholds = bucketCountThresholds;
}
 
Example #4
Source File: InternalDateHierarchy.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
public InternalDateHierarchy(
        String name,
        List<InternalBucket> buckets,
        BucketOrder order,
        long minDocCount,
        int requiredSize,
        int shardSize,
        long otherHierarchyNodes,
        List<PipelineAggregator> pipelineAggregators,
        Map<String, Object> metaData
) {
    super(name, pipelineAggregators, metaData);
    this.buckets = buckets;
    this.order = order;
    this.minDocCount = minDocCount;
    this.requiredSize = requiredSize;
    this.shardSize = shardSize;
    this.otherHierarchyNodes = otherHierarchyNodes;
}
 
Example #5
Source File: InternalPathHierarchy.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
public InternalPathHierarchy(
        String name,
        List<InternalBucket> buckets,
        BucketOrder order,
        long minDocCount,
        int requiredSize,
        int shardSize,
        long otherHierarchyNodes,
        BytesRef separator,
        List<PipelineAggregator> pipelineAggregators,
        Map<String, Object> metaData
) {
    super(name, pipelineAggregators, metaData);
    this.buckets = buckets;
    this.order = order;
    this.minDocCount = minDocCount;
    this.requiredSize = requiredSize;
    this.shardSize = shardSize;
    this.otherHierarchyNodes = otherHierarchyNodes;
    this.separator = separator;
}
 
Example #6
Source File: DateHierarchyAggregator.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
public DateHierarchyAggregator(
        String name,
        AggregatorFactories factories,
        SearchContext context,
        ValuesSource.Numeric valuesSource,
        BucketOrder order,
        long minDocCount,
        BucketCountThresholds bucketCountThresholds,
        List<DateHierarchyAggregationBuilder.RoundingInfo> roundingsInfo,
        Aggregator parent,
        List<PipelineAggregator> pipelineAggregators,
        Map<String, Object> metaData
) throws IOException {
    super(name, factories, context, parent, pipelineAggregators, metaData);
    this.valuesSource = valuesSource;
    this.roundingsInfo = roundingsInfo;
    this.minDocCount = minDocCount;
    bucketOrds =  new BytesRefHash(1, context.bigArrays());
    this.order = InternalOrder.validate(order, this);
    this.bucketCountThresholds = bucketCountThresholds;
}
 
Example #7
Source File: PathHierarchyAggregator.java    From elasticsearch-aggregation-pathhierarchy with MIT License 6 votes vote down vote up
public PathHierarchyAggregator(
        String name,
        AggregatorFactories factories,
        SearchContext context,
        ValuesSource valuesSource,
        BucketOrder order,
        long minDocCount,
        BucketCountThresholds bucketCountThresholds,
        BytesRef separator,
        int minDepth,
        Aggregator parent,
        List<PipelineAggregator> pipelineAggregators,
        Map<String, Object> metaData
) throws IOException {
    super(name, factories, context, parent, pipelineAggregators, metaData);
    this.valuesSource = valuesSource;
    this.separator = separator;
    this.minDocCount = minDocCount;
    bucketOrds = new BytesRefHash(1, context.bigArrays());
    this.order = InternalOrder.validate(order, this);
    this.bucketCountThresholds = bucketCountThresholds;
    this.minDepth = minDepth;
}
 
Example #8
Source File: FacetInfo.java    From fess with Apache License 2.0 6 votes vote down vote up
public BucketOrder getBucketOrder() {
    if (StringUtil.isNotBlank(sort)) {
        final String[] values = sort.split("\\.");
        final boolean asc;
        if (values.length > 1) {
            asc = !values[1].equalsIgnoreCase("desc");
        } else {
            asc = true;
        }
        if (values.length > 0) {
            if ("term".equals(values[0]) || "key".equals(values[0])) {
                return BucketOrder.key(asc);
            } else if ("count".equals(values[0])) {
                return BucketOrder.count(asc);
            }
        }
    }
    return BucketOrder.count(false);
}
 
Example #9
Source File: ElasticSearchQueryManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
    final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
        .field("tags")
        .order(BucketOrder.count(false));

    final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
    final SearchRequest searchRequest = new SearchRequest().indices("blog")
        .source(builder);

    final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

    final Map<String, Aggregation> results = response.getAggregations()
        .asMap();
    final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");

    final List<String> keys = topTags.getBuckets()
        .stream()
        .map(MultiBucketsAggregation.Bucket::getKeyAsString)
        .collect(toList());
    assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
}
 
Example #10
Source File: AggregationHelper.java    From fast-elasticsearch-query-builder with Apache License 2.0 5 votes vote down vote up
private static void setTermsAggregation(SearchSourceBuilder searchSource, TermsAggregation aggregation, Integer size) {
    TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(aggregation.name())
            .field(aggregation.field());
    if (size > 0) {
        termsAggregation.size(Integer.min(size, aggregation.maxSize()));
    }
    if (aggregation.order().length > 0) {
        List<BucketOrder> orders = Stream.of(aggregation.order()).distinct().map(t -> {
            switch (t) {
                case COUNT_ASC:
                    return BucketOrder.count(Boolean.TRUE);
                case COUNT_DESC:
                    return BucketOrder.count(Boolean.FALSE);
                case KEY_ASC:
                    return BucketOrder.key(Boolean.TRUE);
                case KEY_DESC:
                    return BucketOrder.key(Boolean.FALSE);
                default:
                    return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        termsAggregation.order(orders);
    }
    String executionHint = aggregation.executionHint().trim();
    if (executionHint.length() > 0) {
        termsAggregation.executionHint(executionHint);
    }
    searchSource.aggregation(termsAggregation);
}
 
Example #11
Source File: PathHierarchyAggregationBuilder.java    From elasticsearch-aggregation-pathhierarchy with MIT License 5 votes vote down vote up
private PathHierarchyAggregationBuilder order(List<BucketOrder> orders) {
    if (orders == null) {
        throw new IllegalArgumentException("[orders] must not be null: [" + name + "]");
    }
    // if the list only contains one order use that to avoid inconsistent xcontent
    order(orders.size() > 1 ? BucketOrder.compound(orders) : orders.get(0));
    return this;
}
 
Example #12
Source File: DateHierarchyAggregationBuilder.java    From elasticsearch-aggregation-pathhierarchy with MIT License 5 votes vote down vote up
private DateHierarchyAggregationBuilder order(List<BucketOrder> orders) {
    if (orders == null) {
        throw new IllegalArgumentException("[orders] must not be null: [" + name + "]");
    }
    // if the list only contains one order use that to avoid inconsistent xcontent
    order(orders.size() > 1 ? BucketOrder.compound(orders) : orders.get(0));
    return this;
}
 
Example #13
Source File: AggregationQueryEs7DAO.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public List<SelectedRecord> sortMetrics(final TopNCondition condition,
                                        final String valueColumnName,
                                        final Duration duration,
                                        final List<KeyValue> additionalConditions) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

    final RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery(Metrics.TIME_BUCKET)
                                                        .lte(duration.getEndTimeBucket())
                                                        .gte(duration.getStartTimeBucket());

    boolean asc = false;
    if (condition.getOrder().equals(Order.ASC)) {
        asc = true;
    }

    if (additionalConditions != null && additionalConditions.size() > 0) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        additionalConditions.forEach(additionalCondition -> {
            boolQuery.must()
                     .add(QueryBuilders.termsQuery(additionalCondition.getKey(), additionalCondition.getValue()));
        });
        boolQuery.must().add(queryBuilder);
        sourceBuilder.query(boolQuery);
    } else {
        sourceBuilder.query(queryBuilder);
    }

    sourceBuilder.aggregation(
        AggregationBuilders.terms(Metrics.ENTITY_ID)
                           .field(Metrics.ENTITY_ID)
                           .order(BucketOrder.aggregation(valueColumnName, asc))
                           .size(condition.getTopN())
                           .subAggregation(AggregationBuilders.avg(valueColumnName).field(valueColumnName))
    );

    SearchResponse response = getClient().search(condition.getName(), sourceBuilder);

    List<SelectedRecord> topNList = new ArrayList<>();
    Terms idTerms = response.getAggregations().get(Metrics.ENTITY_ID);
    for (Terms.Bucket termsBucket : idTerms.getBuckets()) {
        SelectedRecord record = new SelectedRecord();
        record.setId(termsBucket.getKeyAsString());
        Avg value = termsBucket.getAggregations().get(valueColumnName);
        record.setValue(String.valueOf((long) value.getValue()));
        topNList.add(record);
    }

    return topNList;
}
 
Example #14
Source File: AggregationQueryEsDAO.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public List<SelectedRecord> sortMetrics(final TopNCondition condition,
                                        final String valueColumnName,
                                        final Duration duration,
                                        final List<KeyValue> additionalConditions) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
    final RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery(Metrics.TIME_BUCKET)
                                                        .lte(duration.getEndTimeBucket())
                                                        .gte(duration.getStartTimeBucket());

    boolean asc = false;
    if (condition.getOrder().equals(Order.ASC)) {
        asc = true;
    }

    if (additionalConditions != null && additionalConditions.size() > 0) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        additionalConditions.forEach(additionalCondition -> {
            boolQuery.must()
                     .add(QueryBuilders.termsQuery(additionalCondition.getKey(), additionalCondition.getValue()));
        });
        boolQuery.must().add(queryBuilder);
        sourceBuilder.query(boolQuery);
    } else {
        sourceBuilder.query(queryBuilder);
    }

    sourceBuilder.aggregation(
        AggregationBuilders.terms(Metrics.ENTITY_ID)
                           .field(Metrics.ENTITY_ID)
                           .order(BucketOrder.aggregation(valueColumnName, asc))
                           .size(condition.getTopN())
                           .subAggregation(AggregationBuilders.avg(valueColumnName).field(valueColumnName))
    );

    SearchResponse response = getClient().search(condition.getName(), sourceBuilder);

    List<SelectedRecord> topNList = new ArrayList<>();
    Terms idTerms = response.getAggregations().get(Metrics.ENTITY_ID);
    for (Terms.Bucket termsBucket : idTerms.getBuckets()) {
        SelectedRecord record = new SelectedRecord();
        record.setId(termsBucket.getKeyAsString());
        Avg value = termsBucket.getAggregations().get(valueColumnName);
        record.setValue(String.valueOf((long) value.getValue()));
        topNList.add(record);
    }

    return topNList;
}