Home > Blockchain >  Elastic template if else conditions
Elastic template if else conditions

Time:08-10

I'm building a search template in Elastic and depending on the value of the parameter the search query should perform differently.

The documentation says the syntax should look like

{{#condition}}if content{{/condition}} {{^condition}}else content{{/condition}}

This is my template:

POST _scripts/my-search-template 
{
"script": {
"lang": "mustache",
"source": """
{
  "track_total_hits":true,
  "query": {
    "bool": {
      "filter": [
       {{#radio}}
       if ({{radio}} == "ANY") {
         {"exists": { "field": "radio" }},
        }
        {{/radio}} 
        {{^radio}}
       else {
           {"match": { "radio": "{{radio}}" }},
          }
       {{/radio}}
       ]
     }
   }
 }"""
}
    

But when execute the command:

GET anlage/_search/template
{
 "id": "my-search-template",
 "params": {
  "radio": "ANY"
 }
}

I get the error:

Unrecognized token 'if': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false

How do I build a template with an if else condition properly?

CodePudding user response:

You don't have to mention if/else explicitly and also you cannot compare the field against a specific value. You need to do it like this instead:

POST _scripts/my-search-template 
{
"script": {
"lang": "mustache",
"source": """
{
  "track_total_hits":true,
  "query": {
    "bool": {
      "filter": [
        {{#radio}}
          {"match": { "radio": "{{radio}}" }}
        {{/radio}} 
        {{^radio}}
         {"exists": { "field": "radio" }}
        {{/radio}}
       ]
     }
   }
 }"""
}

I realize that the logic above is different than the one you need, but mustache is just a templating language, not a programming language. This means that you need to think in terms of signals (if parameter is present and has a value), not in terms of logic (if parameter has a specifc value)

  • Related