[ElasticSearch] scripted_metric 去重求和脚本计算高效率解决问题

232 阅读1分钟

init_script 定义
map_script 操作 判断
combine_script 操作返回记录
reduce_script 返回sum值

{

"size": 0,

"query": {

"bool": {

"must": [

{

"range": {

"purchase_date": {

"from": "2019-08-12 00:00:00",

"to": "2019-08-18 23:59:59",

"include_lower": true,

"include_upper": true,

"format": "yyyy-MM-dd HH:mm:ss",

"boost": 1

}

}

}

],

"adjust_pure_negative": true,

"boost": 1

}

},

"aggregations": {

"total_purchase_amount": {

"sum": {

"field": "total_purchase_amount",

"format": "0.000"

}

},

"purchase_quantity": {

"sum": {

"field": "purchase_quantity",

"format": "0"

}

},

"freight": {

"scripted_metric": {

"init_script": {

"source": "params._agg.list= new ArrayList();params._agg.map = new HashMap();",

"lang": "painless"

},

"map_script": {

"source": "if(!params._agg.map.containsKey(doc['purchase_order_no.keyword'].value)){params._agg.map.put(doc['purchase_order_no.keyword'].value,doc['freight'].value)}",

"lang": "painless"

},

"combine_script": {

"source": "double profit = 0; for (t in params._agg.map.values()) { profit += t } return profit",

"lang": "painless"

},

"reduce_script": {

"source": "double profit = 0; for (a in params._aggs) { profit += a } return profit",

"lang": "painless"

}

}

}

}

}