elasticsearch中多个字段聚合及java实现

引言

  假设需要将a,b,c三个字段进行聚合(做笛卡儿积)的话,有两种方法:

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

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

  博主新人一个,只谈方法不深入,将来有研究再更新

  es版本5.6

参考

  https://blog.csdn.net/qq_28988969/article/details/84337405

  https://blog.csdn.net/weixin_41279060/article/details/78852704

es查询语句

{
  "query": {
    "match_all": {}
  },
  "size": 0,
  "aggs": {
    "app": {
      "terms": {
     //聚合的key用####分隔
        "script": "doc['appInfo.appName'].values +'####'+doc['appInfo.appVersion'].values+'####'+doc['device'].values",
        "size": 5
      }
    }
  }
}

结果

   

代码版:

{
    "took": 5,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 650,
        "max_score": 0,
        "hits": [ ]
    },
    "aggregations": {
        "app": {
            "doc_count_error_upper_bound": 5,
            "sum_other_doc_count": 190,
            "buckets": [
            {
                "key": "[sdklib]####[1.0]####[Android]",
                "doc_count": 173
            }
            ,
            {
                "key": "[开源中国]####[2.4]####[Android]",
                "doc_count": 150
            }
            ,
            {
                "key": "[sss]####[1.0]####[Android]",
                "doc_count": 77
            }
            ,
            {
                "key": "[ProguardTest]####[1.0]####[Android]",
                "doc_count": 34
            }
            ,
            {
                "key": "[My Application]####[1.0]####[Android]",
                "doc_count": 26
            }
            ]
        }
    }
}
View Code

JavaAPI

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

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

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

 

posted @ 2019-01-24 16:18  二律背反GG  阅读(13578)  评论(0编辑  收藏  举报