【问题标题】:Elasticsearch painless returns wrong long valuesElasticsearch 无痛返回错误的长值
【发布时间】:2021-06-19 03:10:21
【问题描述】:

当我尝试从时间戳中获取毫秒时,Elasticsearch 返回舍入值(使用 docker.elastic.co/elasticsearch/elasticsearch:7.11.0 图像)。

我的映射:

{
    "mappings": {
        "properties": {
         ...
            "updated_at": {
                "type": "date"
            }
         ...
        }
    }
}

我的脚本查询:

{
    "query": {
        "script_score": {
            "query": {
                "match_all": {}
            },
            "script": {
                "source": "doc['updated_at'].value.millis"
            }
        }
    }
}

结果:

{
    ...
    "hits": {
        ...
        "max_score": 1616185130000,
        "hits": [
            {
                ...
                "_score": 1616185130000,    <---- wrong value
                "_source": {
                    ...
                    "updated_at": 1616185148409    <---- should be this
                }
            },
            {
                ...
                "_score": 1616185130000,    <---- same wrong value even if updated_at is different
                "_source": {
                    ...
                    "updated_at": 1616185148408    <---- should be this
                }
            }
            ...

还尝试使用长类型的映射:

{
    "mappings": {
        "properties": {
         ...
            "updated_at": {
                "type": "long"
            }
         ...
        }
    }
}

查询:

{
    "query": {
        "script_score": {
            "query": {
                "match_all": {}
            },
            "script": {
                "source": "doc['updated_at'].value"
            }
        }
    }
}

得到了同样的结果。

我不能使用排序,因为我们需要通过公式来提升,我坚持这个问题。

【问题讨论】:

  • 您能否显示您在_source 文档中的updated_at 值?
  • @Val 它们出现在结果中:1616185148408, 1616185148409
  • 我只是想确保您索引这些确切的值,而不是日期字符串,对吧?
  • @Val 是的,你是对的,我把数字放在了索引中

标签: elasticsearch elasticsearch-painless


【解决方案1】:

原因是因为每个文档的_scoretype float

Java 中的 long 值具有 64 位精度,而 float 具有 32 位精度,因此尝试将 long 放入浮点数会使您失去一些精度。

试试这个:

long test = 1616185148409L;
System.out.println("Value as long: " + value);
System.out.println("Value as float: " + (float)value);

结果:

Value as long: 1616185148409
Value as float: 1.61618513E12

这与您所看到的一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 2017-10-26
    • 2012-04-17
    • 2021-03-04
    • 1970-01-01
    • 2018-07-09
    • 2017-03-09
    • 2017-11-14
    相关资源
    最近更新 更多