将持续时间转换为总毫秒数

Convert duration to total milliseconds

我的 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 sub-field,因为它包含您添加到源中的确切原始字符串值(即 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