Running an action for each element in an array
The Elastic Stack includes Elastic's core products such as Elasticsearch, Kibana, Logstash, and Beats. Availability This functionality is generally available and ready for production usage. Unless stated otherwise on the page, this functionality is available when your Elastic Stack is deployed on Elastic Cloud Hosted, Elastic Cloud Enterprise, Elastic Cloud on Kubernetes, and self-managed environments. This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes.
Stack
Generally available
You can use the foreach field in an action to trigger the configured action for every element within that array.
In order to protect from long running watches, you can use the max_iterations field to limit the maximum amount of runs that each watch executes. If this limit is reached, the execution is gracefully stopped. If not set, this field defaults to one hundred.
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}}" } } } }
- The logging statement will be executed for each of the returned search hits.
If you are running a script payload transform, the transform needs to be included prior to the actions section to ensure the output is available to the foreach loop.