Watcher error using 'terms' query with metadata array input

Hi everyone,

I'm trying to use an array from the watch metadata in a terms query for one of my watchers. I want to use a Mustache search template-style query as described here:
:link: https://www.elastic.co/docs/solutions/search/search-templates#search-template-convert-json

Here's the Watch I'm trying to execute:

POST _watcher/watch/_execute
{
  "watch": {
    "metadata": {
      "contact_group_names": [
        "Unix-Apps Admin"
      ]
    },
    "input": {
      "search": {
        "request": {
          "indices": [
            "infra-on-call"
          ],
          "body": {
            "source": """
              {
                "query": {
                  "terms": {
                    "Group": {{#toJson}}{{ctx.metadata.contact_group_names}}{{/toJson}}
                  }
                }
              }
            """
          }
        }
      }
    },
    "trigger": {
      "schedule": {
        "interval": "1h"
      }
    },
    "condition": {
      "always": {}
    },
    "actions": {
      "log_results": {
        "logging": {
          "text": "Search returned {{ctx.payload.hits.total}} hits"
        }
      }
    }
  }
}

When I execute this, I get the following error:

"error": {
          "root_cause": [
            {
              "type": "parsing_exception",
              "reason": "Unknown key for a VALUE_STRING in [source].",
              "line": 1,
              "col": 11
            }
          ],
          "type": "parsing_exception",
          "reason": "Unknown key for a VALUE_STRING in [source].",
          "line": 1,
          "col": 11
        },

I suspect it's something to do with the way I'm trying to use source and toJson, but I'm not sure how to structure this correctly inside the Watcher's search input.

Would be grateful for any help or guidance on what I'm doing wrong!

Thanks in advance.

I managed to figure out the solution, I needed to use template instead of body, leaving the solution here in case someone needs to refer in the future:

POST _watcher/watch/_execute
{
  "watch": {
    "metadata": {
      "contact_group_names": [
        "Unix-Apps Admin"
      ]
    },
    "input": {
      "search": {
        "request": {
          "indices": [
            "infra-on-call"
          ],
          "template": {
            "source": """
              {
                "query": {
                  "terms": {
                    "Group": {{#toJson}}ctx.metadata.contact_group_names{{/toJson}}
                  }
                }
              }
            """
          }
        }
      }
    },
    "trigger": {
      "schedule": {
        "interval": "1h"
      }
    },
    "condition": {
      "always": {}
    },
    "actions": {
      "log_results": {
        "logging": {
          "text": "Search returned {{ctx.payload.hits.total}} hits"
        }
      }
    }
  }
}
1 Like