说明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"
}
}
}
}
脚本里面的语句语法是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"
}
}
}
}