Elasticsearch 6.2:如何用Painless内联脚本将Epoch日期字段转yyyymm格式
Got it, let's break this down. In Elasticsearch 6.2, we're still using Joda Time under the hood for date handling, so we can leverage Joda's built-in formatting directly in Painless scripts to convert your epoch-second timestamps to the yyyyMM string format you need.
Step-by-Step Implementation
First, know that when you access doc["start_ts"].value or doc["end_ts"].value in a Painless script, you're getting a org.joda.time.DateTime object. This class has a handy toString() method that accepts a Joda date pattern string—perfect for our use case.
Basic Conversion Code
For each timestamp field, you can convert it like this:
// Convert start_ts to yyyyMM format String startMonth = doc["start_ts"].value.toString("yyyyMM"); // Convert end_ts to yyyyMM format String endMonth = doc["end_ts"].value.toString("yyyyMM");
yyyy: 4-digit year (e.g., 2024)MM: 2-digit month (01 for January, 12 for December)
Note: Use uppercase
MMfor month—lowercasemmwould represent minutes, which isn't what you want here.
Handle Null/Missing Fields
If there's a chance the fields might be missing or null, add a check to avoid runtime errors:
String startMonth = doc["start_ts"].size() > 0 ? doc["start_ts"].value.toString("yyyyMM") : "N/A"; String endMonth = doc["end_ts"].size() > 0 ? doc["end_ts"].value.toString("yyyyMM") : "N/A";
Example Use Cases
Here are a couple of practical examples of how you might use this in Elasticsearch:
1. Scripted Terms Aggregation
Group documents by the start_ts converted to yyyyMM:
GET /your_index/_search { "size": 0, "aggs": { "start_month_groups": { "terms": { "script": { "source": "doc['start_ts'].value.toString('yyyyMM')" } } } } }
2. Update Script to Add Formatted Fields
Persist the formatted strings as new fields in your documents:
POST /your_index/_update_by_query { "script": { "source": """ if (doc['start_ts'].size() > 0) { ctx._source.start_yyyymm = doc['start_ts'].value.toString('yyyyMM'); } if (doc['end_ts'].size() > 0) { ctx._source.end_yyyymm = doc['end_ts'].value.toString('yyyyMM'); } """ }, "query": { "match_all": {} } }
This approach works because Elasticsearch 6.2's Painless runtime allows direct invocation of valid Joda Time methods, and the toString(pattern) method is fully supported for DateTime objects.
内容的提问来源于stack exchange,提问作者JVK

