LoginSignup
2
3

More than 5 years have passed since last update.

Elasticsearchのindexに、@timestampに基づいた日本時刻の曜日フィールドを追加する方法

Last updated at Posted at 2017-01-30

日本のしがらみ

UTCであれば、ScriptedFieldに
doc['@timestamp'].date.dayOfWeek
を設定するだけで取れるんですが、今回欲しいのはJSTの曜日。

Let's Painless

そこで、下記のようなPainlessスクリプトを書いてTimeZone変換してみました。

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, doc['@timestamp'].date.year);
cal.set(Calendar.MONTH, doc['@timestamp'].date.monthOfYear - 1);
cal.set(Calendar.DAY_OF_MONTH, doc['@timestamp'].date.dayOfMonth);
cal.set(Calendar.HOUR_OF_DAY, doc['@timestamp'].date.hourOfDay);
cal.set(Calendar.MINUTE, doc['@timestamp'].date.minuteOfHour);
cal.set(Calendar.SECOND, doc['@timestamp'].date.secondOfMinute);
cal.set(Calendar.MILLISECOND, doc['@timestamp'].date.millisOfSecond);
cal.getTime();

cal.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
return cal.get(Calendar.DAY_OF_WEEK);

これをScriptedFieldに設定してやれば、曜日フィールドとして使えます。
曜日ごとの集計とかしたいときに便利。

しかしながら

取れたものの、曜日取るくらい1行で書けないもんか。
何かElasticsearchの設定をうまいことやってやれば、スクリプト側で頑張らなくても良いんでしょうか・・・

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3