Elasticsearch Scripted Metric Aggregation 自定义聚合

1、首先创建所以:

PUT test_date

{
  "settings":{
      "number_of_shards":2,
      "number_of_replicas":0
  }
}



2、创建索引结构
PUT test_date/tag_type/_mapping 
{
    "tag_type": {
        "dynamic": "false",
            "_all": {  
                "enabled": false  
            },
       "properties": {
        "sex":{
            "type": "string",
            "fielddata":true
        },
        "date0": {
          "type": "string",
            "fielddata":true
        },
        "days":{
             "type": "integer"
        }
      }
}

}



3、添加数据结构如下

PUT test_date/tag_type/18
{
    "sex":"男",
    "date0": "20170101",
    "days": 1
}







4、具体的查询语句
POST test_date/tag_type/_search
{
    "size":0,
    "aggs" : {
        "tt":{
            "terms":{
                "field":"sex"
            },
            "aggs":{
        "date_rpt":{
            "scripted_metric":{
            "init_script":"params._agg.dates = []",
            "map_script":"Map tmp = new HashMap();tmp.put('date',doc.date0.value); tmp.put('cnt',doc.days.value); params._agg.dates.add(tmp);",
            "combine_script":"Map combineMap = new HashMap();for(item in params._agg.dates){String key = item.get('date'); long cnt = item.get('cnt');  if(combineMap.containsKey(key)){combineMap.put(key,combineMap.get(key)+cnt)}else{combineMap.put(key,cnt)}} return combineMap",
            "reduce_script":"Map map = new HashMap();for(m in params._aggs){ Set keys = m.keySet();for(key in keys){if(map.containsKey(key)){map.put(key,map.get(key)+m.get(key))}else{map.put(key,m.get(key))}}} return map"
            }
        }}
        }
    }
}

此处要注意 参数为 params._agg  而 reduce中为 params._aggs 

init_script、map_script、combine_script 之间是用过初始化的参数进行联通,不知道还有没有其他的方式,欢迎大家指出。




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值