对于scripted metric aggregation,在文档中显示的示例中,Combine脚本返回一个数字。
而是在这里,我可以传递数组或哈希吗?
我尝试这样做,尽管它没有返回任何错误,但我无法从reduce脚本访问那些值。
在减少每个分片的脚本中,当转换为字符串时,我得到一个实例,读为'Script2 $ _run_closure1 @ 52ef3bd9'
请告诉我,是否可以通过任何方式实现。
最佳答案
至少对于Elasticsearch
1.5.1版,您可以这样做。
例如,我们可以修改Elasticsearch
示例(scripted metric aggregation)以获取平均利润(利润除以交易次数):
{
"query": {
"match_all": {}
},
"aggs": {
"avg_profit": {
"scripted_metric": {
"init_script": "_agg['transactions'] = []",
"map_script": "if (doc['type'].value == \"sale\") { _agg.transactions.add(doc['amount'].value) } else { _agg.transactions.add(-1 * doc['amount'].value) }",
"combine_script": "profit = 0; num_of_transactions = 0; for (t in _agg.transactions) { profit += t; num_of_transactions += 1 }; return [profit, num_of_transactions]",
"reduce_script": "profit = 0; num_of_transactions = 0; for (a in _aggs) { profit += a[0] as int; num_of_transactions += a[1] as int }; return profit / num_of_transactions as float"
}
}
}
}
注意:这只是组合脚本中数组的演示,您可以轻松计算平均值而无需使用任何数组。
响应如下所示:
"aggregations" : {
"avg_profit" : {
"value" : 42.5
}
}
关于elasticsearch - 从合并返回脚本的度量聚合的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775395/