Toni Oriol
Toni Oriol

Reputation: 75

Filter by array item or empty array

I'm trying to filter by an array that must be either empty or contain the item 1.

{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must": [
            {
              "terms": {
                "memberOrganizationFamilyIds": [
                  1
                ]
              }
            }
          ],
          "must_not": [
            {
              "exists": {
                "field": "memberOrganizationFamilyIds"
              }
            }
          ]
        }
      }
    }
  }
}

According to the docs this is how it should be but it isn't working.

If we apply the first filter it works.

{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must": [
            {
              "terms": {
                "memberOrganizationFamilyIds": [
                  1
                ]
              }
            }
          ]
        }
      }
    }
  }
}

If we apply the second filter it also works.

{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must_not": [
            {
              "exists": {
                "field": "memberOrganizationFamilyIds"
              }
            }
          ]
        }
      }
    }
  }
}

But not together.

Upvotes: 0

Views: 58

Answers (1)

Assael Azran
Assael Azran

Reputation: 2993

I'm trying to filter by an array that must be either empty or contain the item 1

Try this you should add should (meaning) or

{
"query": {
    "bool": {
      "filter": {
        "bool": {
          "should": [
            {
              "terms": {
                "memberOrganizationFamilyIds": [
                  1
                ]
              }
            },
            {
              "bool": {
                "must_not": [
                  {
                    "exists": {
                      "field": "memberOrganizationFamilyIds"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 1

Related Questions