Link Search Menu Expand Document Documentation Menu

脚本化指标聚合

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

脚本有四个阶段:初始化阶段、映射阶段、组合阶段和规约阶段。

  • init_script:(可选)设置初始状态,并在收集任何文档之前执行。
  • map_script:检查 type 字段的值,并在收集到的文档上执行聚合。
  • combine_script:聚合每个分片返回的状态。聚合值将返回给协调节点。
  • reduce_script:提供对变量状态的访问;此变量将每个分片上 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
    }
  }
 }
}
剩余 350 字符

有问题?

想贡献吗?