James
James

Reputation: 553

Filter on field value or not exists

I'm trying to filter a field for a specific value OR that it does not exist.

I have the part for the specific value

{
  "query": {
    "match": {
      "app.serviceType": {
        "query": "MY_VALUE",
        "type": "phrase"
      }
    }
  }
}

I'd also like to add to this any case where the field serviceType doesn't exist at all.

Essentially I'd like the equivalent of this:

serviceType == "MY_VALUE" || string.IsNullOrEmpty(serviceType)

Upvotes: 0

Views: 3165

Answers (2)

YLR
YLR

Reputation: 1540

This request must match with your use case :

 {
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "serviceType"
                }
              },
              {
                "match_phrase": {
                    "serviceType": "MY_VALUE"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "serviceType"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Upvotes: 1

James
James

Reputation: 553

Based on the previous answer (which didn't work but got me close) I was able to get it to work.

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "app.serviceType"
                }
              },
              {
                "match_phrase": {
                  "app.serviceType": "MY_VALUE"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "app.serviceType"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions