脚本化指标聚合

scripted_metric 指标是一种多值指标聚合,它返回根据指定脚本计算得出的指标。

一个脚本包含四个阶段:初始阶段、映射阶段、合并阶段和归约阶段。

  • init_script:(可选)设置初始状态,并在收集任何文档之前执行。

  • map_script:检查 type 字段的值,并对收集到的文档执行聚合。

  • combine_script:聚合从每个分片返回的状态。聚合后的值被返回给协调节点。

  • reduce_script:提供对变量 states 的访问;此变量将每个分片上 combine_script 的结果合并成一个数组。

以下示例聚合了 Web 日志数据中不同的 HTTP 响应类型:

GET opensearch_dashboards_sample_data_logs/_search
{
  "size": 0,
  "aggregations": {
    "responses.counts": {
      "scripted_metric": {
        "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]",
        "map_script": """
              def code = doc['response.keyword'].value;
                 if (code.startsWith('5') || code.startsWith('4')) {
                  state.responses.error += 1 ;
                  } else if(code.startsWith('2')) {
                   state.responses.success += 1;
                  } else {
                  state.responses.other += 1;
                }
             """,
        "combine_script": "state.responses",
        "reduce_script": """
            def counts = ['error': 0L, 'success': 0L, 'other': 0L];
                for (responses in states) {
                 counts.error += responses['error'];
                  counts.success += responses['success'];
                counts.other += responses['other'];
        }
        return counts;
        """
      }
    }
  }
}

示例响应

...
"aggregations" : {
  "responses.counts" : {
    "value" : {
      "other" : 0,
      "success" : 12832,
      "error" : 1242
    }
  }
 }
}