Home > Enterprise >  Elasticsearch search keyword ignoring empty query values
Elasticsearch search keyword ignoring empty query values

Time:11-27

Elasticsearch version:

we would like to build a query like the following

......
......
bool: {
 must: [
   match : {
      myfield.myfield2.keyword : {
         query: "myvalue"
      }
   }
 ]
}
......
......

How can we modify the above one in a way that:

  • "myvalue" is an empty string: we would like that elasticsearch ignores it instead of searching for empty string
  • "myvalue" not empty. We should get the exact match

CodePudding user response:

You should do this check in your application code while building the query, if myvalue is empty or null, you don't add the query.

If that's not possible for any reason, there's a way to do this in Elasticsearch using search templates which are built using the Mustache templating language.

Basically, your query would look like this, where the match query is only added if myvalue has a non-null, non-false, non-empty value:

POST _scripts/my-query
{
  "script": {
    "lang": "mustache",
    "source": """
    {
      "query": {
        "bool": {
          "must": [
            {{#myvalue}}
            {
              "match" : {
                "myfield.myfield2.keyword" : {
                  "query": "myvalue"
                }
              }
            }
            {{/myvalue}}
          ]
        }
      }
    }
    """
  }
}

If you call this search template with a null, false, empty value, then the match query is not added

POST _render/template
{
  "id": "my-query",
  "params": {
    "myvalue": ""
  }
}

=>

  {
    "query" : {
      "bool" : {
        "must" : [ ]
      }
    }
  }

Whereas if you call it with a non-null, non-false, non-empty value, the match query is added:

POST _render/template
{
  "id": "my-query",
  "params": {
    "myvalue": "test"
  }
}

=>

  {
    "query" : {
      "bool" : {
        "must" : [
          {
            "match" : {
              "myfield.myfield2.keyword" : {
                "query" : "myvalue"
              }
            }
          }
        ]
      }
    }
  }
  • Related