Search and Elasticsearch learning path Level 2 This level · 11 of 18
Medium search elasticsearch

Why do date range queries with now miss the cache, and how does rounding help?

The 30 second answer

The word now means the current millisecond, so a range like the last hour is a slightly different query every time and its result can't be reused. Elasticsearch's docs say queries with now are typically not cacheable. If I round, for example from now minus one hour rounded to the minute up to now rounded to the minute, every request in that minute is identical and the filter cache can be reused.

Could you say this in an interview?

Why caching matters here. Elasticsearch can cache the result of a frequently used filter: which documents match it. The next identical filter skips the work. But the cache only helps if the filter is truly identical.

**Why now breaks it.** "gte": "now-1h" means "one hour before this exact millisecond". A request a moment later asks for a different time window, so it's a different filter, and nothing can be reused. The docs say queries on date fields that use now are typically not cacheable, because the matching range changes all the time.

Rounding with date math. Elasticsearch date math supports rounding with /. now/m rounds to the minute, now/h to the hour and now/d to the day. With "gte": "now-1h/m" and "lte": "now/m", every request during the same minute sends the same range, so the cached result can be shared. The docs' own example rounds to the minute and points out that the window becomes slightly wider than exactly one hour. That's usually fine for users.

A trap the same guide warns about. It can be tempting to split the range into a large rounded part that can be cached and small exact parts at the edges, inside a bool query. The docs warn that this sometimes makes the query slower, because the extra bool overhead can cancel out what the cache saves. Measure before you do it. Pick the rounding unit from the business rule, and remember that coarser rounding helps the cache more but can hurt the user experience. "New in the last 24 hours" can round to the minute, while "flash sale ends at 12:00:00" can't.

GET products/_search
{ "query": { "bool": { "filter": [
  { "range": { "published_at": { "gte": "now-1h/m", "lte": "now/m" } } }
]}}}

Alternate interview scenarios

"Our 'new arrivals' page hits the cluster hard every morning."

Round its date filter (for example now-7d/d) so thousands of shoppers share one cached filter, and put the condition in filter context so it isn't scored.

"A sale must end exactly on time."

Don't round the boundary that defines the sale. Use the exact time for that filter, or check the end time in the application, and accept that this filter won't be cached.

Sources (3)
  1. Elasticsearch docs: Tune for search speed (search rounded dates)elastic.co
  2. Elasticsearch docs: Date math in range querieselastic.co
  3. Elasticsearch docs: Query and filter contextelastic.co
Previous
Next