Skip to main content

脚本度量聚合 scripted_metric

Scripted Metric Aggregation

使用脚本执行以提供度量输出的度量聚合。

例子

POST ledger/_search?size=0
{
"query" : {
"match_all" : {}
},
"aggs": {
"profit": {
"scripted_metric": {
"init_script" : "state.transactions = []",
"map_script" : "state.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)",
"combine_script" : "double profit = 0; for (t in state.transactions) { profit += t } return profit",
"reduce_script" : "double profit = 0; for (a in states) { profit += a } return profit"
}
}
}
}

map_script是唯一必需的参数

上面的聚合演示了如何使用脚本聚合计算销售和成本交易的总利润。

上述聚合的响应:

{
"took": 218,
...
"aggregations": {
"profit": {
"value": 240.0
}
}
}

也可以使用存储的脚本指定上述示例,如下所示:

POST ledger/_search?size=0
{
"aggs": {
"profit": {
"scripted_metric": {
"init_script" : {
"id": "my_init_script"
},
"map_script" : {
"id": "my_map_script"
},
"combine_script" : {
"id": "my_combine_script"
},
"params": {
"field": "amount"
},
"reduce_script" : {
"id": "my_reduce_script"
}
}
}
}
}

init、map和combine脚本的脚本参数必须在全局params对象中指定,以便在脚本之间共享。

允许的返回类型

虽然任何有效的脚本对象都可以在单个脚本中使用,但脚本必须仅返回以下类型或将其存储在状态对象中:

  • primitive types
  • String
  • Map (仅包含此处列出的类型的键和值)
  • Array (仅包含此处列出的类型的元素)

脚本的Scope

scripted metric aggregation在其执行的4个阶段使用脚本:

  • init_script 在收集文件之前执行。允许聚合设置任何初始状态。

  • map_script 每个收集的文档执行一次。这是唯一需要的脚本。如果未指定combine_script,则需要将生成的状态存储在状态对象中。

  • combine_script 文档收集完成后,在每个shard上执行一次。允许聚合合并从每个shard返回的状态。如果未提供combine_script,则combine阶段将返回聚合变量。

  • reduce_script 在所有shard返回结果后,在协调节点上执行一次。脚本提供了对变量状态的访问,变量状态是每个shard上combine_script结果的数组。如果未提供reduce_script,reduce阶段将返回状态变量。