Spring数据弹性搜索总和 - 价格,数量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring数据弹性搜索总和 - 价格,数量相关的知识,希望对你有一定的参考价值。

我想通过使用spring data elasticsearch来聚合数据。我想要汇总sum(price)sum(qty)。我应该添加到方法.addAggregation以获得特定结果以及如何获得它?

"properties": {
                        "cat": { "store": true,  "type": "long" }, 
                        "curr": { "index": "not_analyzed",  "store": true,  "type": "string" }, 
                        "end_date": { "store": true,  "type": "long" }, 
                        "price": { "store": true,  "type": "long" }, 
                        "start_date": { "store": true,  "type": "long" }, 
                        "tcat": { "store": true,  "type": "long" }, 
                        "title": { "store": true,  "type": "string" }, 
                        "uid": { "store": true,  "type": "long" }
                    }

我的服务方法如下:

final List<FilterBuilder> filters = Lists.newArrayList();
        final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery());
        Optional.ofNullable(searchParams.getCategoryId()).ifPresent(v -> filters.add(boolFilter().must(termFilter("cat", v))));
        Optional.ofNullable(searchParams.getCurrency()).ifPresent(v -> filters.add(boolFilter().must(termFilter("curr", v))));
        Optional.ofNullable(searchParams.getTreeCategoryId()).ifPresent(v -> filters.add(boolFilter().must(termFilter("tcat", v))));
        Optional.ofNullable(searchParams.getUid()).ifPresent(v -> filters.add(boolFilter().must(termFilter("uid", v))));

        //access for many uids
        if (searchParams.getUids() != null) {
            Optional.ofNullable(searchParams.getUids().split(",")).ifPresent(v -> {
                filters.add(boolFilter().must(termsFilter("uid", v)));
            });
        }

        //access for many categories
        if (searchParams.getCategories() != null) {
            Optional.ofNullable(searchParams.getCategories().split(",")).ifPresent(v -> {
                filters.add(boolFilter().must(termsFilter("cat", v)));
            });
        }

        final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (Optional.ofNullable(searchParams.getTitle()).isPresent()) {
            boolQueryBuilder.should(queryStringQuery(searchParams.getTitle()).analyzeWildcard(true).field("title"));
        }

        if (Optional.ofNullable(searchParams.getStartDateFrom()).isPresent()
                || Optional.ofNullable(searchParams.getStartDateTo()).isPresent()) {
            filters.add(rangeFilter("start_date").from(searchParams.getStartDateFrom()).to(searchParams.getStartDateTo()));
        }

        if (Optional.ofNullable(searchParams.getEndDateFrom()).isPresent()
                || Optional.ofNullable(searchParams.getEndDateTo()).isPresent()) {
            filters.add(rangeFilter("end_date").from(searchParams.getEndDateFrom()).to(searchParams.getEndDateTo()));
        }

        if (Optional.ofNullable(searchParams.getPriceFrom()).isPresent()
                || Optional.ofNullable(searchParams.getPriceTo()).isPresent()) {
            filters.add(rangeFilter("price").from(searchParams.getPriceFrom()).to(searchParams.getPriceTo()));
        }



    searchQuery.withQuery(boolQueryBuilder);

            FilterBuilder[] filterArr = new FilterBuilder[filters.size()];
            filterArr = filters.toArray(filterArr);
            searchQuery.withFilter(andFilter(filterArr));
searchQuery.addAggregation(AggregationBuilders("price").field("price"));
        Aggregations aggregations = searchTemplate.query(searchQuery.build(), new ResultsExtractor<Aggregations>(){
        @Override
            public Aggregations extract(SearchResponse response) {
                return response.getAggregations();
            }
        });
        return aggreg

ations.asMap();

为什么聚合没有聚合过滤器,bool等并返回aggs我认为所有记录?

答案

我知道现在为时已晚,但对于Spring Data,Elasticsearch以前的答案中的代码如下所示:

SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withIndices("index_name")
        .withTypes("type_name")
        .withQuery(searchQuery)
        .addAggregation(AggregationBuilders.sum("sum_of_price").field("price"))
        .addAggregation(AggregationBuilders.sum("sum_of_qty").field("qty")).build();

Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() {
  @Override
  public Aggregations extract(SearchResponse response) {
    return response.getAggregations();
  }
});

Sum aggregation = aggregations.get("sum_of_price");
double priceTotal = aggregation.getValue());
另一答案

使用此选项添加聚合并获取结果:

SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.client.prepareSearch("index_name")
            .setIndices("index_name")
            .setTypes("type_name").setQuery(searchQuery).addAggregation(AggregationBuilders.stats("sum_of_price").field("price"))
            .addAggregation(AggregationBuilders.sum("sum_of_qty").field("qty"))
    SearchResponse searchResponse = searchRequestBuilder.execute().actionGet()
    Integer priceTotal = (searchResponse.getAggregations().getAsMap().get("sum_of_price").getSum())

以上是关于Spring数据弹性搜索总和 - 价格,数量的主要内容,如果未能解决你的问题,请参考以下文章

spring boot弹性搜索-配置数据源

用html做一个购物车,能实现简单的产品数量和价格的加减就行。最后能计算出提交物品价格的总和。

显示字符串值的总和

如何使弹性搜索多匹配模糊搜索始终返回最小数量的结果

[Berkeley]弹性分布式数据集RDD的介绍(RDD: A Fault-Tolerant Abstraction for In-Memory Cluster Computing 论文翻译)(代码片

查找总和等于 k ​​的子集的数量