【问题标题】:Convert duration to total milliseconds将持续时间转换为总毫秒数
【发布时间】:2020-08-31 19:59:57
【问题描述】:

我的弹性搜索中有一个字符串字段,其持续时间格式为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 对象阅读的内容来看,字段是如何访问的。

【问题讨论】:

    标签: elasticsearch elasticsearch-painless


    【解决方案1】:

    您可能想尝试使用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
    

    【讨论】:

    • 你的 ES 服务器在哪里运行?
    • 我不太确定。它由我公司主办。我真的无权访问。如果我使用硬编码值进行测试而不是从doc 中提取,那么我展示的上述代码确实可以在不使用拆分的情况下工作。我真正的问题是doc['app.duration'] 不返回任何内容并导致错误。我认为拆分不会解决这个问题。 keyword 是做什么的?
    • 你能显示app.duration字段的映射吗?可能某些文档对该字段没有任何价值。这可能吗?
    • 您也可以在catch 块Debug.explain(e) 中添加它并用结果更新您的问题吗?
    • 添加Debug.explain(e) 导致返回一个空数组[]。看起来区别在于 doc['app.duration'].value 不起作用和 doc['app.duration.keyword'].value 起作用。我真的不知道 keyword 部分是什么意思,但这似乎是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多