对数组中的每个元素运行操作

编辑

对数组中的每个元素运行操作

编辑

您可以在操作中使用 foreach 字段,以便针对该数组中的每个元素触发已配置的操作。

为了防止长时间运行的 watch,您可以使用 max_iterations 字段来限制每个 watch 执行的最大运行次数。如果达到此限制,则会优雅地停止执行。如果未设置,则此字段默认为一百。

resp = client.watcher.put_watch(
    id="log_event_watch",
    trigger={
        "schedule": {
            "interval": "5m"
        }
    },
    input={
        "search": {
            "request": {
                "indices": "log-events",
                "body": {
                    "query": {
                        "match": {
                            "status": "error"
                        }
                    }
                }
            }
        }
    },
    condition={
        "compare": {
            "ctx.payload.hits.total": {
                "gt": 0
            }
        }
    },
    actions={
        "log_hits": {
            "foreach": "ctx.payload.hits.hits",
            "max_iterations": 500,
            "logging": {
                "text": "Found id {{ctx.payload._id}} with field {{ctx.payload._source.my_field}}"
            }
        }
    },
)
print(resp)
const response = await client.watcher.putWatch({
  id: "log_event_watch",
  trigger: {
    schedule: {
      interval: "5m",
    },
  },
  input: {
    search: {
      request: {
        indices: "log-events",
        body: {
          query: {
            match: {
              status: "error",
            },
          },
        },
      },
    },
  },
  condition: {
    compare: {
      "ctx.payload.hits.total": {
        gt: 0,
      },
    },
  },
  actions: {
    log_hits: {
      foreach: "ctx.payload.hits.hits",
      max_iterations: 500,
      logging: {
        text: "Found id {{ctx.payload._id}} with field {{ctx.payload._source.my_field}}",
      },
    },
  },
});
console.log(response);
PUT _watcher/watch/log_event_watch
{
  "trigger" : {
    "schedule" : { "interval" : "5m" }
  },
  "input" : {
    "search" : {
      "request" : {
        "indices" : "log-events",
        "body" : {
          "query" : { "match" : { "status" : "error" } }
        }
      }
    }
  },
  "condition" : {
    "compare" : { "ctx.payload.hits.total" : { "gt" : 0 } }
  },
  "actions" : {
    "log_hits" : {
      "foreach" : "ctx.payload.hits.hits", 
      "max_iterations" : 500,
      "logging" : {
        "text" : "Found id {{ctx.payload._id}} with field {{ctx.payload._source.my_field}}"
      }
    }
  }
}

对于返回的每个搜索命中,都会执行日志记录语句。