fempyrean
fempyrean

Reputation: 43

How to query results considering missing keys or matching values

So, I have an object called audience. This object may contain a number of keys like age, gender, job_role, etc.

Something like this:

"audience": {
        "gender": [
          "Male",
          "Female"
        ],
        "household_income": [
          "<$25,000",
          "$25,001-$50,000",
          "$50,001-$100,000"
        ]
      }

And I want to query something like "where audience.gender = 'Male' or audience.gender does not exist". I'm new to elasticsearch so I'm quite confused as to how can I achieve this.

Upvotes: 1

Views: 37

Answers (1)

EricKrg
EricKrg

Reputation: 192

You can use a simple match query for that:

{
  "query": {
    "match": {
      "audience.gender": "Male" 
    }
  }
}

In order to negate the same search query use a bool query instead with must_not

{
    "query": {
        "bool": {
            "must_not": {
                "match": {
                    "audience.gender": "Male"
                }
            }
        }
    }
}

See the docs on arrays here

And on Bool queries here

If your list entries are actual obj. have a look at the nested fieldtype

Upvotes: 2

Related Questions