Elasticsearch查询所有出生日期为每月5号的人员方法咨询
Got it, let's work through this. Your persons index has the dob field mapped as a date with yyyy-MM-dd format, and you need to find everyone born on the 5th day of any month—regardless of year or month. Here are two solid approaches:
1. Script Query (Quick, Ad-Hoc Solution)
If you need a one-off or temporary query, you can use a script to extract the day component from the dob date field and check if it equals 5. Here's the full Elasticsearch DSL:
GET persons/_search { "query": { "script": { "script": { "source": "doc['dob'].value.getDayOfMonth() == 5", "lang": "painless" } } } }
How this works:
doc['dob'].valueaccesses the date value stored in thedobfield.getDayOfMonth()is a Painless method that returns the day of the month (1-31) for the date.- We simply check if that value equals 5.
Note: Script queries are flexible but can be slower on large datasets compared to standard term queries, since they run logic per document.
2. Add a Derived Field (Performance-Optimized for Repeated Queries)
If you'll be running this query frequently, it's better to add a dedicated field that stores just the day of the month. This lets you use a fast term query instead of a script.
Step 1: Update the index mapping
First, add a new dob_day integer field to store the day component:
PUT persons/_mapping { "properties": { "dob_day": { "type": "integer" } } }
Step 2: Populate the new field
Use _update_by_query to backfill the dob_day field for existing documents:
POST persons/_update_by_query { "script": { "source": "ctx._source.dob_day = doc['dob'].value.getDayOfMonth()" } }
Step 3: Query with the new field
Now you can use a high-performance term query to find everyone born on the 5th:
GET persons/_search { "query": { "term": { "dob_day": 5 } } }
This approach is much faster for large indices because Elasticsearch can leverage inverted indexes for the dob_day field, avoiding per-document script execution.
内容的提问来源于stack exchange,提问作者Gautam Vysyaraju

