暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Elastic实战:script脚本中求两日期之差

Elastic之家 2022-07-20
637

0. 引言

在不少项目统计需求中,我们需要计算周期或者持续时间,这就需要我们计算两个日期之差。所以今天我们就来探讨在es的script脚本中使用painless语法如何计算量日期之差

1. 解决

本次演示环境基于elasticsearch7.13.0

首先我们来看直接相减会发生什么

结果:我们可以看到报错了,原因是JodaCompatibleZonedDateTime
类型的数据不能应用减号操作符 这里的JodaCompatibleZonedDateTime
类型就是es中的日期类型

那不能用减号,我们该怎么计算呢?


首先要知道的是,我们是在painless语法中进行计算的,painless是类java的语法,回想一下java中是如何计算两日期之差的呢?

是不是要先把两个日期转换为毫秒数、秒数或者分钟数,这时这些数值就可以通过减法来计算差值了

painless也一样,但是我们怎么知道painless中的日期类型怎么转换为秒数呢?这就要借助painless官方文档[1]

找到Shared API[2],并在其中搜索JodaCompatibleZonedDateTime
,我们就可以找到关于该类的相关方法介绍了

点击进入JodaCompatibleZonedDateTime[3],会发现里面提供了一系列的方法


因为我这里的需求是求两日期相差的分钟数,我们利用getMillis()
来将日期转换为毫秒数,然后计算毫秒数之差,将结果除以1000*60=60000就可以转换为分钟了

示例如下


查询结果

Elastic  


~



References

[1]
 painless官方文档: https://www.elastic.co/guide/en/elasticsearch/painless/7.13/index.html
[2]
 Shared API: https://www.elastic.co/guide/en/elasticsearch/painless/7.13/painless-api-reference-shared.html
[3]
 JodaCompatibleZonedDateTime: https://www.elastic.co/guide/en/elasticsearch/painless/7.13/painless-api-reference-shared-org-elasticsearch-script.html#painless-api-reference-shared-JodaCompatibleZonedDateTime

文章转载自Elastic之家,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论