elasticsearch中多个字段聚合两种方法介绍

两种方式

1、大桶套小桶,通过terms一层层聚合
这个方法适用于需要统计每一项的数据,比如a中有多少种b

2、函数扩展(script)聚合
这个方法适用于直接统计有多少种组合

下面是方法2的具体实现:

统计:

GET ****_20190926/_search
{
  "size": 0,
  "aggs": {
    "pre": {
      "terms": {
        "script": "doc['inChannel'].values +'####'+doc['resCode'].values",
        "size": 5
      }
    }
  }
}

结果:

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 18,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "pre": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "[7220101]####[0]",
          "doc_count": 13
        },
        {
          "key": "[]####[]",
          "doc_count": 2
        },
        {
          "key": "[1020201]####[]",
          "doc_count": 1
        },
        {
          "key": "[10202]####[]",
          "doc_count": 1
        },
        {
          "key": "[7220101]####[]",
          "doc_count": 1
        }
      ]
    }
  }
}

java代码参考:

Script script = new Script("doc['inChannel'].values +'####'+ doc['resCode'].values");

//用于统计每一项详细数据
TermsAggregationBuilder app = AggregationBuilders.terms("app").script(script).size(10000);

//用于统计有多少项
CardinalityAggregationBuilder app = AggregationBuilders.cardinality("app").script(script).precisionThreshold(10000);

参考:https://www.cnblogs.com/end-emptiness/p/10315133.html

原文地址:https://www.cnblogs.com/libin2015/p/11661703.html