Elasticsearch 基础教程

Elasticsearch 高级教程

Elasticsearch 插件

Elasticsearch 笔记

Elasticsearch FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/elasticsearch-count-distinct-values.html

es 获取某个字段所有值及其个数的方法

Elasticsearch 笔记 Elasticsearch 笔记


elasticsearch(es)如何获取某个字段的所有不同的值及其对应的个数?

解决方法

针对如上需求,可以使用 elasticsearch 聚合(aggs)功能中的桶聚合模块,其中提供了 Terms Aggregation 子模块,Terms Aggregation 用于词项的分组聚合。最为经典的用例是获取 X 中最频繁(top frequent)的 term filed value,其中 X 是文档中的某个字段,具体示例如下:

{
  "aggs": {
    "word_cnt terms": {
      "terms": { // terms 聚合 关键字
        "field": "word_cnt",
        "size" : 500,
        ......
      }
    }
  }
}

返回类似如下:

{
  "took": 152,
  "timed_out": false,
  "_shards": {
    "total": 8,
    "successful": 8,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 940089,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "word_cnt terms": {
      "doc_count_error_upper_bound": 25,
      "sum_other_doc_count": 22718,
      "buckets": [
        {
          "key": 0,
          "doc_count": 6723
        },
        {
          "key": 100,
          "doc_count": 4674
        },
        {
          "key": 98,
          "doc_count": 4582
        },
        {
          "key": 103,
          "doc_count": 4557
        },
        {
          "key": 90,
          "doc_count": 4511
        }
        ...
      ]
    }
  }
}      

其中,key 对应不同的值,doc_count 对应文档个数,默认情况下按照文档的个数降序,即 "order": { "_count": "asc" },如果要根据文档个数升序,示例如下:

{
  "aggs": {
    "word_cnt terms": {
      "terms": { // terms 聚合 关键字
        "field": "word_cnt",
        "size" : 500,
        "order": { "_count": "asc" }
        ......
      }
    }
  }
}