You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch查询所有出生日期为每月5号的人员方法咨询

Solution for Querying Persons Born on the 5th of Any Month

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'].value accesses the date value stored in the dob field.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:35:26