Thiago
Thiago

Reputation: 4832

Having ElasticSearch ignore filter when field does not exist

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:

     "filter" : {
        "bool" : {
          "must" : [ { 
              "term" : { "channel" : "24" }
            },
            {
              "range" : {
                "startTime" : { "gt" : "now" }
              }
           }]
       }
     }

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 properties channel and startTime), movies (doc doesnt have properties channel and startTime), genres (doc doesnt have properties channel and startTime) and tv shows/programs (doc has properties channel and startTime) that air on channel 24.

Is there a way to do that without involving filter script? I could achieve this using script but then the performance of the query would be really bad.

Thank you Thiago

Upvotes: 1

Views: 2154

Answers (1)

Sloan Ahrens
Sloan Ahrens

Reputation: 8718

Try this:

POST /test_index/_search
{
   "filter": {
      "bool": {
         "should": [
            {
               "bool": {
                  "must": [
                     {
                        "term": {
                           "channel": "24"
                        }
                     },
                     {
                        "range": {
                           "startTime": {
                              "gt": "now"
                           }
                        }
                     }
                  ]
               }
            },
            {
               "bool": {
                  "must_not": [
                     {
                        "exists": {
                           "field": "channel"
                        }
                     },
                     {
                        "exists": {
                           "field": "startTime"
                        }
                     }
                  ]
               }
            }
         ]
      }
   }
}

Upvotes: 2

Related Questions