有时需要统计一段时间内,订单的总金额。类似于sql的sum,针对某一字段求和。这就涉及到es的聚合查询,来看看用spring-data-elasticSearch怎么写:

  1.  
    QueryBuilder queryBuilder = QueryBuilders.boolQuery()
  2.  
    .must(QueryBuilders.rangeQuery("orderTime").gte(from).lte(to));
  3.  
    // 聚合查询。goodsSales是要统计的字段,sum_sales是自定义的别名
  4.  
    SumAggregationBuilder sumBuilder = AggregationBuilders.sum("sum_sales").field("goodsSales");
  5.  
     
  6.  
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
  7.  
    .withQuery(queryBuilder)
  8.  
    .addAggregation(sumBuilder)
  9.  
    .build();
  10.  
     
  11.  
    double saleAmount = elasticsearchTemplate.query(searchQuery, response -> {
  12.  
    InternalSum sum = (InternalSum)response.getAggregations().asList().get(0);
  13.  
    return sum.getValue();
  14.  
    });

对应es查询语句:

  1.  
    {
  2.  
    "query": {
  3.  
    "bool": {
  4.  
    "must": [
  5.  
    {
  6.  
    "range": {
  7.  
    "orderTime": {
  8.  
    "gte": 20180313,
  9.  
    "lte": 20180314
  10.  
    }
  11.  
    }
  12.  
    },
  13.  
    {
  14.  
    "match": {
  15.  
    "skuNo": "888"
  16.  
    }
  17.  
    }
  18.  
    ]
  19.  
    }
  20.  
    },
  21.  
    "aggs": {
  22.  
    "sum_value": {
  23.  
    "sum_sales": {
  24.  
    "field": "goodsSales"
  25.  
    }
  26.  
    }
  27.  
    }
  28.  
    }

以下还有一些常用聚合查询(参考http://blog.csdn.net/u010454030/article/details/63266035):

    1.  
      (1)统计某个字段的数量
    2.  
      ValueCountBuilder vcb= AggregationBuilders.count("count_uid").field("uid");
    3.  
      (2)去重统计某个字段的数量(有少量误差)
    4.  
      CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");
    5.  
      (3)聚合过滤
    6.  
      FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));
    7.  
      (4)按某个字段分组
    8.  
      TermsBuilder tb= AggregationBuilders.terms("group_name").field("name");
    9.  
      (5)求和
    10.  
      SumBuilder sumBuilder=AggregationBuilders.sum("sum_price").field("price");
    11.  
      (6)求平均
    12.  
      AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");
    13.  
      (7)求最大值
    14.  
      MaxBuilder mb= AggregationBuilders.max("max_price").field("price");
    15.  
      (8)求最小值
    16.  
      MinBuilder min=AggregationBuilders.min("min_price").field("price");
    17.  
      (9)按日期间隔分组
    18.  
      DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");
    19.  
      (10)获取聚合里面的结果
    20.  
      TopHitsBuilder thb= AggregationBuilders.topHits("top_result");
    21.  
      (11)嵌套的聚合
    22.  
      NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");
    23.  
      (12)反转嵌套
    24.  
      AggregationBuilders.reverseNested("res_negsted").path("kps ");
05-25 11:06