Elasticsearch日期范围查询:如何基于固定起始日计算15天后的结束日
Perfect, this is a common use case that Elasticsearch handles natively with its date math functionality—no need to pre-calculate the end date outside the query!
Here's how you can adjust your query to automatically set the end date as 15 days after your fixed start date (2019-01-01):
{ "size": 0, "_source": ["dateCreated"], "query": { "bool": { "must": { "range": { "date_published": { "from": "2019-01-01", "to": "2019-01-01||+15d", "include_lower": true, "include_upper": true } } } } } }
Breakdown of the date math expression:
2019-01-01: Your fixed start date (the base date for the calculation)||: Separates the base date from the math expression (required to tell Elasticsearch you're using date math)+15d: Adds 15 days to the base date (dstands for days; you can also use other units likehfor hours,Mfor months, etc.)
This will automatically resolve to 2019-01-16 (since 2019-01-01 plus 15 days is January 16th). The include_lower and include_upper parameters are optional here (they default to true), but I included them for clarity—they ensure both the start and end dates are included in the range.
If you ever need to adjust the offset (like +30 days or -7 days), just modify the number and unit in the to field, and Elasticsearch will handle the calculation for you!
内容的提问来源于stack exchange,提问作者Asha

