如何解决将持续时间转换为总毫秒数
我的Elastic Search中有一个字符串字段,其持续时间格式为00:00:00.000000
。我想将其转换为数字字段,即毫秒总数。
编辑:
我考虑过使用脚本字段,但是它不起作用。
try{
String duration = doc['app.duration'].value;
String[] durationParts = new String[3];
int firstIdx = duration.indexOf(":");
int secondIdx = duration.indexOf(":",firstIdx+1);
durationParts[1] = duration.substring(firstIdx+1,secondIdx);
durationParts[2] = duration.substring(secondIdx+1);
long minutes = Long.parseLong(durationParts[1]) * 60000;
float seconds = Float.parseFloat(durationParts[2]) * 1000;
long mAndS = Math.round(minutes + seconds);
return mAndS;
}
catch(Exception e) {
return -1;
}
上面的内容在第一行String duration = doc['app.duration'].value;
上失败,我得到-1。但是,如果我将第一行更改为String duration = "00:00:01.5250000";
之类的硬编码值,那么我就会得到期望的1525
。
我不确定自己在做什么错。根据我使用doc
对象读取的内容,了解如何访问字段。
解决方法
您可能想尝试使用keyword
子字段,因为它包含您添加到源中的确切原始字符串值(即00:00:00.000000
),而app.duration
字段包含所分析的文本值,这可能不是您期望的值,具体取决于您设置的分析仪。
doc['app.duration.keyword'].value
否则,下面是一个更简单的脚本来获取您想要的内容:0和1525:
def parts = /:/.split(doc['app.duration'].value);
def total = 0;
total += Long.parseLong(parts[0]) * 24 * 60 * 1000;
total += Long.parseLong(parts[1]) * 60 * 1000;
total += Float.parseFloat(parts[2]) * 1000;
return total;
请注意,您需要将以下行添加到elasticsearch.yml
配置文件中,以启用正则表达式引擎。
script.painless.regex.enabled: true
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。