timouwerkerk
timouwerkerk

Reputation: 137

Elasticsearch bool must only when field exists in document

I want to filter my documents if the publish date is in the future, and i do this with

{
"size": 8,
"query": {
    "filtered": {
        "filter": {
            "bool": {
                "must": [{
                    "range": {
                        "meta.publish_date.date": {
                            "lte": "now"
                        }
                    }
                }]
            }
        }
    }
},
"from": 0
}

My problem now is that it only finds the documents which have the field 'publish_date' and is in the past. But i also want to find all the documents which not have this field.

How do I make such a query?

Thanks in advance.

Upvotes: 0

Views: 473

Answers (1)

Val
Val

Reputation: 217294

You can also include documents in the response which don't have the date field, like this:

{
  "from": 0,
  "size": 8,
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "minimum_should_match": 1,
          "should": [
            {
              "range": {
                "meta.publish_date.date": {
                  "lte": "now"
                }
              }
            },
            {
              "missing": {
                "field": "meta.publish_date.date"
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 2

Related Questions