Having ElasticSearch ignore filter when field does not exist

Hi all,

I am running a query against an alias that is currently pointing to a dozen of indexes. Not all documents have the same structure across these indexes, so I am trying to run a filtered query:

GET /thiago/_search
  {
  "query" : {
     "filtered" : { 
           "filter" : {
              "bool" : {
                "should" : { 
                    "term" : { "channel" : "24" }
                 }
             }
           }
        }
     }
  }

ElasticSearch is filtering all documents that have channel 24, but I would also want all the other document that do not have the attribute channel. For example, my query should bring all actors (doc doesnt have property channel), movies (doc doesnt have property channel), genres (doc doesnt have property channel) and tv shows (doc has property channel) that air on channel 24.

Is there a way to do that without involving filter script?

Maybe something like this:

GET /thiago/_search
  {
  "query" : {
     "filtered" : { 
           "filter" : {
              "bool" : {
                "should" : { 
                    "term" : { "channel" : "24" },
                    "missing": { "field": "channel" }
                 }
             }
           }
        }
     }
  }
1 Like

It works. Thank you @jpountz