Pass a list to Elasticsearch query template

Hi everyone!
I am trying to pass a list of parameters to a search query (filter by terms) in Elasticsearch. It works when it's not in a template, just in a query:

"terms": {
      "speaker": ["HAMLET", "KING HENRY IV"]
      }

I've put it into the template like this:

"terms": {
            "{{filter1}}": "{{filter1_val}}"}
        }

And then call it like this:

GET shakespeare/_search/template
{
  "id":"template",
  "params": {
    "filter1": "speaker",
    "filter_value1": ["HAMLET", "KING HENRY IV"]
  }
}

And I get the following error:

{
  "error": {
    "root_cause": [
      {
        "type": "parsing_exception",
        "reason": "[terms] query does not support [speaker]",
        "line": 1,
        "col": 98
      }
    ],
    "type": "parsing_exception",
    "reason": "[terms] query does not support [speaker]",
    "line": 1,
    "col": 98
  },
  "status": 400
}

I have tried adding brackets to the template itself like "{{filter1}}": [{{filter1_val}}] and adding quotes and deleting them, and passing a parameters in the form of "["HAMLET", "KING HENRY IV"]", but none of this worked.

The last thing I tried was from the mustache manual (https://mustache.github.io/mustache.5.html, section on Non-Empty Lists).
The template:

"terms": {"speaker": ["{{#filters}}{{filter}}{{/filters}}"]}

And to call it like this"

{
  "id": "test3",
  "params": {
    "filters": [
      {"filter": "HAMLET,"},  
      {"filter": "KING HENRY IV"}
      ]
  }
}

It's supposed to render like "HAMLET, KING HENRY IV", but in reality the results return empty list. If you leave only one line then it works...

What am I doing wrong? What is the right way to do this?
Is there any way to see how the template is actually rendered to see the mistakes?

Any suggestions are welcome.

Thank you!

1 Like

Found the solution here:
https://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-template.html#_passing_an_array_of_strings

Passing an array of strings

GET /_search/template
{
  "template": {
    "query": {
      "terms": {
        "status": [
          "{{#status}}",
          "{{.}}",
          "{{/status}}"
        ]
      }
    }
  },
  "params": {
    "status": [ "pending", "published" ]
  }
}
which is rendered as:

{
"query": {
  "terms": {
    "status": [ "pending", "published" ]
  }
}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.