1

This is a part of my search query template:

"query": {
    "bool": {
      "must": [
        {
          "terms": {
            "platform_id": [
              "{{#platform_ids}}",
              "{{.}}",
              "{{/platform_ids}}"
            ]
          }
        }
      ], 

This solution was taken from the elasticsearch official website.

I have this query:

GET _render/template
{
  "id": "fddf", 
  "params": {
    "query_string": "tinders",
    "platform_ids": [1, 2]
  }
}

And this results with this:

"terms" : {
  "platform_id" : [
    "",
    "1",
    "",
    "2",
    ""
  ]
}

But I need this:

"terms" : {
  "platform_id" : [
    1, 2
  ]
}

Couldn't find a solution for this.

Flying Kitty
  • 59
  • 1
  • 6
  • What language are you using to render the mustache templates? If you are using something like python/javascript, there are probably easier ways of accomplishing this. – IanGabes May 18 '21 at 16:59

2 Answers2

2

Request:

GET _render/template
{
  "source": "{ \"query\": { \"terms\": {{#toJson}}bids{{/toJson}} }}",
  "params": {
    "bids":[1,2]
  }
}

Response:

{
  "template_output" : {
    "query" : {
      "terms" : [
        1,
        2
      ]
    }
  }
}

Try below:

"query": {
"bool": {
  "must": [
    {
      "terms": {
        "platform_id": {{#toJson}}platform_id{{/toJson}}
      }
    }
  ], 
Sahil Gupta
  • 2,028
  • 15
  • 22
  • All the problem was in fact that I pass source template as json, not a string containing json. This method also works, thank you! – Flying Kitty May 19 '21 at 07:12
1

You need to modify your template as shown below

GET _render/template
{
  "source": "{\"query\":{\"bool\":{\"must\":[{\"terms\":{\"platform_id\":[{{#platform_id}}{{value}}{{#comma}},{{/comma}}{{/platform_id}}]}}]}}}",
  "params": {
    "platform_id": [
      {
        "value": 1,
        "comma": true
      },
      {
        "value": 2
      }
    ]
  }
}

Result would be

    {
  "template_output": {
    "query": {
      "bool": {
        "must": [
          {
            "terms": {
              "platform_id": [
                1,
                2
              ]
            }
          }
        ]
      }
    }
  }
}

Refer to this SO answer to get a detailed explanation

ESCoder
  • 15,431
  • 2
  • 19
  • 42
  • 1
    Thank you, that worked after I realized that I have to pass source template as string completely. I was trying all these methods with source being a json, not a string that contains json and mustache templates. – Flying Kitty May 19 '21 at 07:10