org.elasticsearch.search.aggregations.AbstractAggregationBuilder Java Examples

The following examples show how to use org.elasticsearch.search.aggregations.AbstractAggregationBuilder. 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: GroupConditionBuilder.java    From search-spring-boot-starter with Apache License 2.0 7 votes vote down vote up
public AbstractAggregationBuilder getAggregationFunction(FunctionCondition functionCondition) {
    final String field = functionCondition.getField();
    final SqlFunctionEnum sqlFunction = functionCondition.getFunction();
    final String functionName = functionCondition.getFunctionName();
    AbstractAggregationBuilder aggregation;
    switch (sqlFunction) {
        case AVG:
            aggregation = AggregationBuilders.avg(functionName).field(field);
            break;
        case MAX:
            aggregation = AggregationBuilders.max(functionName).field(field);
            break;
        case MIN:
            aggregation = AggregationBuilders.min(functionName).field(field);
            break;
        case SUM:
            aggregation = AggregationBuilders.sum(functionName).field(field);
            break;
        case COUNT:
            aggregation = AggregationBuilders.count(functionName).field(field);
            break;
        default:
            throw new RuntimeException("不支持的聚合类型");
    }
    return aggregation;
}
 
Example #2
Source File: GroupConditionBuilder.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 封装查询请求的聚合条件
 *
 * @param rootTermsBuilder     聚合根
 * @param termsBuilder         当前聚合
 * @param functions            聚合函数集
 * @param searchRequestBuilder 聚合功能查询请求
 */
private void aggregationFunction(AggregationBuilder rootTermsBuilder, AggregationBuilder termsBuilder,
                                 final List<FunctionCondition> functions,
                                 final SearchRequestBuilder searchRequestBuilder) {

    for (FunctionCondition functionCondition : functions) {

        AbstractAggregationBuilder aggregation = getAggregationFunction(functionCondition);

        if (termsBuilder != null) {
            termsBuilder.subAggregation(aggregation);
        } else {
            searchRequestBuilder.addAggregation(aggregation);
        }
    }
    if (termsBuilder != null) {
        searchRequestBuilder.addAggregation(rootTermsBuilder);
    }
}
 
Example #3
Source File: ProfileThreadSnapshotQueryEsDAO.java    From skywalking with Apache License 2.0 6 votes vote down vote up
protected int querySequenceWithAgg(AbstractAggregationBuilder aggregationBuilder, String segmentId, long start, long end) throws IOException {
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    sourceBuilder.query(boolQueryBuilder);
    List<QueryBuilder> mustQueryList = boolQueryBuilder.must();

    mustQueryList.add(QueryBuilders.termQuery(ProfileThreadSnapshotRecord.SEGMENT_ID, segmentId));
    mustQueryList.add(QueryBuilders.rangeQuery(ProfileThreadSnapshotRecord.DUMP_TIME).gte(start).lte(end));
    sourceBuilder.size(0);

    sourceBuilder.aggregation(aggregationBuilder);
    SearchResponse response = getClient().search(ProfileThreadSnapshotRecord.INDEX_NAME, sourceBuilder);
    NumericMetricsAggregation.SingleValue agg = response.getAggregations().get(ProfileThreadSnapshotRecord.SEQUENCE);

    return (int) agg.value();
}
 
Example #4
Source File: StatsTrendAction.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder getRequestBuilder(StatsTrendRequest parameter) {
    SearchRequestBuilder searchRequestBuilder;
    try {
        final String table = parameter.getTable();
        AbstractAggregationBuilder aggregation = buildAggregation(parameter, table);
        searchRequestBuilder = getConnection().getClient()
                .prepareSearch(ElasticsearchUtils.getIndices(table, parameter))
                .setTypes(ElasticsearchUtils.DOCUMENT_TYPE_NAME)
                .setIndicesOptions(Utils.indicesOptions())
                .setQuery(new ElasticSearchQueryGenerator().genFilter(parameter.getFilters()))
                .setSize(0)
                .addAggregation(aggregation);
    }
    catch (Exception e) {
        throw FoxtrotExceptions.queryCreationException(parameter, e);
    }
    return searchRequestBuilder;
}
 
Example #5
Source File: GroupAction.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder getRequestBuilder(GroupRequest parameter) {
    SearchRequestBuilder query;
    try {
        query = getConnection().getClient()
                .prepareSearch(ElasticsearchUtils.getIndices(parameter.getTable(), parameter))
                .setIndicesOptions(Utils.indicesOptions());
        AbstractAggregationBuilder aggregation = buildAggregation(parameter);
        query.setQuery(new ElasticSearchQueryGenerator().genFilter(parameter.getFilters()))
                .setSize(QUERY_SIZE)
                .addAggregation(aggregation);
    }
    catch (Exception e) {
        throw FoxtrotExceptions.queryCreationException(parameter, e);
    }
    return query;
}
 
Example #6
Source File: HistogramAction.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder getRequestBuilder(HistogramRequest parameter) {
    SearchRequestBuilder searchRequestBuilder;
    AbstractAggregationBuilder aggregationBuilder = buildAggregation(parameter);
    try {
        searchRequestBuilder = getConnection().getClient()
                .prepareSearch(ElasticsearchUtils.getIndices(parameter.getTable(), parameter))
                .setTypes(ElasticsearchUtils.DOCUMENT_TYPE_NAME)
                .setIndicesOptions(Utils.indicesOptions())
                .setQuery(new ElasticSearchQueryGenerator().genFilter(parameter.getFilters()))
                .setSize(QUERY_SIZE)
                .addAggregation(aggregationBuilder);
    }
    catch (Exception e) {
        throw FoxtrotExceptions.queryCreationException(parameter, e);
    }
    return searchRequestBuilder;
}
 
Example #7
Source File: TrendAction.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder getRequestBuilder(TrendRequest parameter) {
    SearchRequestBuilder searchRequestBuilder;
    try {
        AbstractAggregationBuilder aggregationBuilder = buildAggregation(parameter);
        searchRequestBuilder = getConnection().getClient()
                .prepareSearch(ElasticsearchUtils.getIndices(parameter.getTable(), parameter))
                .setIndicesOptions(Utils.indicesOptions())
                .setQuery(new ElasticSearchQueryGenerator().genFilter(parameter.getFilters()))
                .setSize(QUERY_SIZE)
                .addAggregation(aggregationBuilder);
    } catch (Exception e) {
        throw FoxtrotExceptions.queryCreationException(parameter, e);
    }
    return searchRequestBuilder;
}
 
Example #8
Source File: TrendAction.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private AbstractAggregationBuilder buildAggregation(TrendRequest request) {
    DateHistogramInterval interval = Utils.getHistogramInterval(request.getPeriod());
    String field = request.getField();

    DateHistogramAggregationBuilder histogramBuilder = Utils.buildDateHistogramAggregation(request.getTimestamp(), interval);
    if(!CollectionUtils.isNullOrEmpty(getParameter().getUniqueCountOn())) {
        histogramBuilder.subAggregation(Utils.buildCardinalityAggregation(
                getParameter().getUniqueCountOn(), request.accept(new CountPrecisionThresholdVisitorAdapter(
                        elasticsearchTuningConfig.getPrecisionThreshold()))));
    }
    return Utils.buildTermsAggregation(Lists.newArrayList(new ResultSort(field, ResultSort.Order.asc)),
            Sets.newHashSet(histogramBuilder), elasticsearchTuningConfig.getAggregationSize());
}
 
Example #9
Source File: HistogramAction.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private AbstractAggregationBuilder buildAggregation(HistogramRequest parameter) {
    DateHistogramInterval interval = Utils.getHistogramInterval(getParameter().getPeriod());
    DateHistogramAggregationBuilder histogramBuilder = Utils.buildDateHistogramAggregation(getParameter().getField(),
                                                                                           interval);
    if (!CollectionUtils.isNullOrEmpty(getParameter().getUniqueCountOn())) {
        histogramBuilder.subAggregation(Utils.buildCardinalityAggregation(
                getParameter().getUniqueCountOn(), parameter.accept(new CountPrecisionThresholdVisitorAdapter(
                        elasticsearchTuningConfig.getPrecisionThreshold()))));
    }
    return histogramBuilder;
}
 
Example #10
Source File: EsAbstractConditionAggregation.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void regA(AbstractAggregationBuilder<?> builder) {
    assertObjectNotNull("builder", builder);
    if (aggregationAggregationBuilderList == null) {
        aggregationAggregationBuilderList = new ArrayList<>();
    }
    aggregationAggregationBuilderList.add(builder);
}
 
Example #11
Source File: GroupAction.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private AbstractAggregationBuilder buildAggregation(GroupRequest parameter) {
    return Utils.buildTermsAggregation(getParameter().getNesting()
                                               .stream()
                                               .map(x -> new ResultSort(x, ResultSort.Order.asc))
                                               .collect(Collectors.toList()),
                                       !CollectionUtils.isNullOrEmpty(getParameter().getUniqueCountOn())
                                       ? Sets.newHashSet(
                                               Utils.buildCardinalityAggregation(getParameter().getUniqueCountOn(),
                                                                                 parameter.accept(new CountPrecisionThresholdVisitorAdapter(
                                                                                         elasticsearchTuningConfig.getPrecisionThreshold()))))
                                       : Sets.newHashSet(), elasticsearchTuningConfig.getAggregationSize());

}
 
Example #12
Source File: EsAbstractConditionAggregation.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void regA(AbstractAggregationBuilder<?> builder) {
    assertObjectNotNull("builder", builder);
    if (aggregationAggregationBuilderList == null) {
        aggregationAggregationBuilderList = new ArrayList<>();
    }
    aggregationAggregationBuilderList.add(builder);
}
 
Example #13
Source File: StatsTrendAction.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private AbstractAggregationBuilder buildAggregation(StatsTrendRequest request, String table) {
    final String field = request.getField();
    DateHistogramInterval interval = Utils.getHistogramInterval(request.getPeriod());
    AbstractAggregationBuilder dateHistogramBuilder = Utils.buildDateHistogramAggregation(request.getTimestamp(),
                                                                                          interval);
    boolean isNumericField = Utils.isNumericField(getTableMetadataManager(), table, field);
    if (isNumericField) {
        dateHistogramBuilder
                .subAggregation(Utils.buildStatsAggregation(field, getParameter().getStats()));
        if (!AnalyticsRequestFlags.hasFlag(request.getFlags(), AnalyticsRequestFlags.STATS_SKIP_PERCENTILES)) {
            dateHistogramBuilder.subAggregation(Utils.buildPercentileAggregation(
                    field, request.getPercentiles(), request.getCompression()));
        }
    }
    else {
        dateHistogramBuilder
                .subAggregation(Utils.buildStatsAggregation(field, Collections.singleton(Stat.COUNT)));
    }

    if (CollectionUtils.isNullOrEmpty(getParameter().getNesting())) {
        return dateHistogramBuilder;
    }
    return Utils.buildTermsAggregation(getParameter().getNesting()
                                               .stream()
                                               .map(x -> new ResultSort(x, ResultSort.Order.asc))
                                               .collect(Collectors.toList()), Sets.newHashSet(dateHistogramBuilder),
                                       elasticsearchTuningConfig.getAggregationSize());
}
 
Example #14
Source File: EsProductServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
                    .subAggregation(AggregationBuilders.terms("attrIds")
                            .field("attrValueList.productAttributeId")
                            .subAggregation(AggregationBuilders.terms("attrValues")
                                    .field("attrValueList.value"))
                            .subAggregation(AggregationBuilders.terms("attrNames")
                                    .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example #15
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newCard(Function func) {
	CardinalityBuilder max;
	if (func.fieldtype == Field.SCRIPT)
		max = AggregationBuilders.cardinality(Function.genStatField(func))
				.script(func.field);
	else
		max = AggregationBuilders.cardinality(Function.genStatField(func))
				.field(func.field);
	return max;
}
 
Example #16
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newMax(Function func) {
	MaxBuilder max;
	if (func.fieldtype == Field.SCRIPT)
		max = AggregationBuilders.max(Function.genStatField(func))
				.script(func.field);
	else
		max = AggregationBuilders.max(Function.genStatField(func))
				.field(func.field);
	return max;
}
 
Example #17
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newMin(Function func) {
	MinBuilder min;
	if (func.fieldtype == Field.SCRIPT)
		min = AggregationBuilders.min(Function.genStatField(func))
				.script(func.field);
	else
		min = AggregationBuilders.min(Function.genStatField(func))
				.field(func.field);		
	return min;
}
 
Example #18
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newAvg(Function func) {
	AvgBuilder avg;
	if (func.fieldtype == Field.SCRIPT)
		avg = AggregationBuilders.avg(Function.genStatField(func))
				.script(func.field);
	else
		avg = AggregationBuilders.avg(Function.genStatField(func))
				.field(func.field);

	return avg;
}
 
Example #19
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newSum(Function func) {
	SumBuilder sum;
	if (func.fieldtype == Field.SCRIPT)
		sum = AggregationBuilders.sum(Function.genStatField(func))
				.script(func.field);
	else
		sum = AggregationBuilders.sum(Function.genStatField(func))
				.field(func.field);

	return sum;
}
 
Example #20
Source File: AST_Stats.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static AbstractAggregationBuilder newCount(Function func) {
	ValueCountBuilder count;
	count = AggregationBuilders.count(Function.genStatField(func))
				.field(func.field);

	return count;
}
 
Example #21
Source File: AggMaker.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
/**
 * TOPHITS查询
 *
 * @param field
 * @return
 */
private AbstractAggregationBuilder makeTopHitsAgg(MethodField field) {
    String alias = gettAggNameFromParamsOrAlias(field);
    TopHitsAggregationBuilder topHits = AggregationBuilders.topHits(alias);
    List<KVValue> params = field.getParams();
    String[] include = null;
    String[] exclude = null;
    for (KVValue kv : params) {
        switch (kv.key) {
            case "from":
                topHits.from((int) kv.value);
                break;
            case "size":
                topHits.size((int) kv.value);
                break;
            case "include":
                include = kv.value.toString().split(",");
                break;
            case "exclude":
                exclude = kv.value.toString().split(",");
                break;
            case "alias":
            case "nested":
            case "reverse_nested":
            case "children":
                break;
            default:
                topHits.sort(kv.key, SortOrder.valueOf(kv.value.toString().toUpperCase()));
                break;
        }
    }
    if (include != null || exclude != null) {
        topHits.fetchSource(include, exclude);
    }
    return topHits;
}
 
Example #22
Source File: EsAbstractConditionAggregation.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void regA(AbstractAggregationBuilder<?> builder) {
    assertObjectNotNull("builder", builder);
    if (aggregationAggregationBuilderList == null) {
        aggregationAggregationBuilderList = new ArrayList<>();
    }
    aggregationAggregationBuilderList.add(builder);
}
 
Example #23
Source File: SimpleSearchQueryBuilder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public SimpleSearchQueryBuilder forceClearAggregations(){
	List<AbstractAggregationBuilder> aggregationBuilders = (List<AbstractAggregationBuilder>)ReflectUtils.getFieldValue(searchQueryBuilder, "aggregationBuilders");
	if(aggregationBuilders!=null){
		aggregationBuilders.clear();
	}
	return this;
}
 
Example #24
Source File: EsProductServiceImpl.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example #25
Source File: EsProductServiceImpl.java    From macrozheng with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example #26
Source File: EsProductServiceImpl.java    From mall with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
                    .subAggregation(AggregationBuilders.terms("attrIds")
                            .field("attrValueList.productAttributeId")
                            .subAggregation(AggregationBuilders.terms("attrValues")
                                    .field("attrValueList.value"))
                            .subAggregation(AggregationBuilders.terms("attrNames")
                                    .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example #27
Source File: EsProductServiceImpl.java    From macrozheng-mall with MIT License 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues")
            .path("attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs")
            .filter(QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example #28
Source File: PercolateSourceBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Add an aggregation definition.
 */
public PercolateSourceBuilder addAggregation(AbstractAggregationBuilder aggregationBuilder) {
    if (aggregations == null) {
        aggregations = new ArrayList<>();
    }
    aggregations.add(aggregationBuilder);
    return this;
}
 
Example #29
Source File: PercolateSourceBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    if (docBuilder != null) {
        docBuilder.toXContent(builder, params);
    }
    if (queryBuilder != null) {
        builder.field("query");
        queryBuilder.toXContent(builder, params);
    }
    if (size != null) {
        builder.field("size", size);
    }
    if (sorts != null) {
        builder.startArray("sort");
        for (SortBuilder sort : sorts) {
            builder.startObject();
            sort.toXContent(builder, params);
            builder.endObject();
        }
        builder.endArray();
    }
    if (trackScores != null) {
        builder.field("track_scores", trackScores);
    }
    if (highlightBuilder != null) {
        highlightBuilder.toXContent(builder, params);
    }
    if (aggregations != null) {
        builder.field("aggregations");
        builder.startObject();
        for (AbstractAggregationBuilder aggregation : aggregations) {
            aggregation.toXContent(builder, params);
        }
        builder.endObject();
    }
    builder.endObject();
    return builder;
}
 
Example #30
Source File: ElasticsearchSearchQueryBase.java    From vertexium with Apache License 2.0 5 votes vote down vote up
protected List<AbstractAggregationBuilder> getElasticsearchStatisticsAggregations(StatisticsAggregation agg) {
    List<AbstractAggregationBuilder> aggs = new ArrayList<>();
    for (String propertyName : getPropertyNames(agg.getFieldName())) {
        String visibilityHash = getSearchIndex().getPropertyVisibilityHashFromPropertyName(propertyName);
        String aggName = createAggregationName(agg.getAggregationName(), visibilityHash);
        ExtendedStatsAggregationBuilder statsAgg = AggregationBuilders.extendedStats(aggName);
        statsAgg.field(propertyName);
        aggs.add(statsAgg);
    }
    return aggs;
}