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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM