elasticsearch 进行聚合+去重查询

以客户customer为例
我想查询每日的客户数。
先按照日期分桶,然后在桶内按照 姓名来去重 来计算客户数(实际会按照客户id 来区分客户)
测试数据见 文章末尾
一共是9条数据, 名字分别为:
river Lucy 1 Lucy frank tom lily lily tom tom
不同的名字是 6 个。
 

先看看 es 的 query 怎么写

{
  "size" : 0,
  "aggs" : {
      "days" : {
        "date_histogram": {
          "field": "createTime",
          "interval": "day"
        },
        "aggs": {
          "distinct_name" : {
              "cardinality" : {
                "field" : "firstName"
              }
          }
        }
      }
  }
}

查询结果为:

{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 9,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "days": {
      "buckets": [
        {
          "key_as_string": "2019-04-10 00:00:00",
          "key": 1554854400000,
          "doc_count": 9,
          "distinct_name": {
            "value": 6
          }
        }
      ]
    }
  }
}

 

posted @ 2019-06-10 19:13  炫舞风中  阅读(3597)  评论(0编辑  收藏  举报