国际化时区-ElasticSearch时区处理

一、存储格式

JSON 本身没有date类型,Elasticsearch将设置了时区的date转换为UTC时间,将没有设置时区的date直接设置为UTC时间,以long型时间戳存储。

官网文档《Date datatype文档》内容如下

Date datatype

JSON doesn’t have a date datatype, so dates in Elasticsearch can either be:

    strings containing formatted dates, e.g. "2015-01-01" or "2015/01/01 12:10:30". a long number representing milliseconds-since-the-epoch. an integer representing seconds-since-the-epoch.

Internally, dates are converted to UTC (if the time-zone is specified) and stored as a long number representing milliseconds-since-the-epoch

二、查询统计

    date类型查询,将date转换为long型时间戳查询; date类型聚合,返回结果格式化date字符串; ElasticSearch查询、存储,将date类型转换为UTC long型时间戳。 相同格式存储、查询(同是时间戳或同是格式化字符串),查询时间一致;查询、存储格式不一致,相差8个小时(GMT+08:00与UTC之间相差8小时)

聚合查询

聚合查询

POST date_index/_search { "size": 0, "aggs": { "by_day": { "date_histogram": { "field": "date", "interval": "day", "time_zone": "+08:00" } } } }

三、使用建议

使用日期类型时推荐不修改日期格式时区,所有数据都用UTC时区,这样时间统一才不容易出问题,查询时指定时区,如:{ "field": "date", "interval": "day", "time_zone": "+08:00" },同时程序内部进行date_format时也要指定时区,和查询语句中的保持一致

参考资料

  1. 《Date datatype文档》
  2. 博客《Elasticsearch中的date与时区问题》
  3. 《关于 Elasticsearch 时区的小知识》
  4. 《Elasticsearch时区问题》
  5. 《ELASTICSEARCH DATE及TIMEZONE总结》
  6. 《Elasticsearch 的一些常见疑问(持续更新中)》
经验分享 程序员 微信小程序 职场和发展