举个栗子说明elasticsearch 的 scripted metric aggregation

说明scripted metric aggregation 的用法。

POST /dd/doc/_bulk?refresh
{"index":{"_id":1}}
{"name": "productA", "price": 1}
{"index":{"_id":2}}
{"name": "productA", "price": 2}
{"index":{"_id":3}}
{"name": "productB", "price": 3}
{"index":{"_id":4}}
{"name": "productB", "price": 4}
{"index":{"_id":5}}
{"name": "productC", "price": 5}
{"index":{"_id":6}}
{"name": "productC", "price": 6}

POST dd/_search?size=0
{
    "size": 0, 
    "query" : {
        "match_all" : {}
    },
    "aggs": {
        "profit": {
            "scripted_metric": {
                "init_script" : "params._agg.transactions = []",
                "map_script" : "params._agg.transactions.add(doc.price.value == -1 ? 0 : 2 * doc.price.value)", 
                "combine_script" : "double profit = 0; for (t in params._agg.transactions) { profit += t } return profit",
                "reduce_script" : "double profit = 0; for (a in params._aggs) { profit += a } return profit"
            }
        }
    }
}
## 说明, 以上脚本作用,类似于sum . 
脚本里面的语句语法是grovvy 语法, 
init_script:  定义参数: 参数名字必须是 params.agg 开头然后跟着参数名字。 此处定义了一个数组变量transactions 

map_script: 对每个分片中的每条数据,进行一样的操作。 操作在每个分片中进行。上面是在每个分片上,初始化数组。 

combine_script: 同样是在每个分片中操作, 统计每个分片中,数组的和。 

reduce_script: 最后把各个分片中统计的结果进行返回一个节点,然后进行求和,返回的结果,保存在params._aggs 中。

```shell

# 其余例子:
PUT /transactions/stock/_bulk?refresh
{"index":{"_id":1}}
{"type": "sale","amount": 80}
{"index":{"_id":2}}
{"type": "cost","amount": 10}
{"index":{"_id":3}}
{"type": "cost","amount": 30}
{"index":{"_id":4}}
{"type": "sale","amount": 130}

如下是求盈利的总和。 
cost 是成本
sale 是销售价格


POST ledger/_search?size=0
{
    "query" : {
        "match_all" : {}
    },
    "aggs": {
        "profit": {
            "scripted_metric": {
                "init_script" : "params._agg.transactions = []",
                "map_script" : "params._agg.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)", 
                "combine_script" : "double profit = 0; for (t in params._agg.transactions) { profit += t } return profit",
                "reduce_script" : "double profit = 0; for (a in params._aggs) { profit += a } return profit"
            }
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值