3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elasticsearchに登録した生年月日から現在の年齢を算出する.

Posted at

Elasticsearchに登録した生年月日をscript(Painless)で計算させて、年齢を取得します。

使用するmapping定義

{
  "xxxxxxxxx": {
    "mappings": {
      "xxxxxxxxx": {
        "properties": {
          "birthday": {
            "type": "date"
          }
        }
      }
    }
  }
}

データ

{
  "birthday": "1996-09-29T09:00:00.000Z"
}

登録する生年月日は、ElasticsearchのTimeZoneにあわせて、UTCで登録しています。

query

{
  "query": {
    "match_all": {}
    }
  , "script_fields": {
    "age": {
      "script": {
        "lang": "painless",
        "inline": "Date n = new Date(); Date b = new Date(doc['birthday'].value); DateFormat f = new SimpleDateFormat('yyyy-MM-dd'); return Period.between(LocalDate.parse(f.format(b)), LocalDate.parse(f.format(n))).getYears();"
      }
    }
  },
  "_source":  [
    "birthday"
  ]
}

Painless Scriptでは、new Date()で現在日時を取得して、登録されている生年月日との差をPeriod.between()で取得しています。

query実行結果

{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "xxxxxxxxx",
        "_type": "xxxxxx",
        "_id": "xxxxx",
        "_score": 1,
        "_source": {
          "birthday": "1996-09-29T09:00:00.000Z"
        },
        "fields": {
          "age": [
            21
          ]
        }
      }
    ]
  }
}

painlessで利用できるJava APIは、以下。
https://www.elastic.co/guide/en/elasticsearch/reference/5.0/modules-scripting-painless.html#painless-api

なお、Elasticsearchでは、 Joda-Time も日時処理に利用できます。

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?