FiftiN
FiftiN

Reputation: 797

ElasticSearch: find item by term or ignore it if it not exist

I need filter items by several fields. Each field must be equal to value or not exist. This filter could be implemented with the following code, but it not works:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "$parentId": 1111
          }
        },
        {
          "terms": {
            "color.keyword": [
              "red",
              null
            ]
          }
        },
        {
          "terms": {
            "size.keyword": [
              "6",
              null
            ]
          }
        }
      ]
    }
  }
}

Is it possible to implement a similar working filter?

Upvotes: 0

Views: 2282

Answers (1)

Nishant
Nishant

Reputation: 7874

To check if any value exists for a field you can use exists query. Since the requirement is that field has a particular value or the field has no value (equivalent to field must not exists) the query using bool query will be as below:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "$parentId": 1111
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "color.keyword": 111
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exist": {
                      "field": "color.keyword"
                    }
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "size.keyword": 111
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exist": {
                      "field": "size.keyword"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

The idea is that should needs to have two of desired conditions - exactly meet term or field cannot exist. should query ensures that at least one condition must match from the array of queries.

Upvotes: 2

Related Questions