How to filter elasticsearch by date field with date modification

Viewed 56

To filter by date, I use the following queries:

'body'  => [
    'query' => [
        'bool' => [
             'filter' => [
                  'range' => [
                      'expire_at' => [
                          'gte' => now()
                      ]
                 ]
             ]
         ]
    ]
]

UPD: All records have another date field - last_checked. The question is how to select records in which, for example, (expire_at - 7 days) > last_checked?

2 Answers

use this code

"expire_at" => array(
    "lt" => "now+7d/d"
)

Check the range query documentation: you can use date math in the range parameters. E.g., expire_at - 7 days < now() means that the expiration will be within the next 7 days. Then you can do:

"range": {
  "expire_at": {
    "lt": "now+7d/d"
  }
}

Note that this will include also already expired items. If you want to avoid that, you can add the condition that the expiration date is not met yet:

"range": {
  "expire_at": {
    "lt": "now+7d/d",
    "gte": "now/d"
  }
}
Related