float类型存储在es中会有精度损失

Elasticsearch | 作者 ferraborghini | 发布于2018年08月24日 | 阅读数:9648

mapping中设置字段为fvalue:float。导入数据是用的1.01。结果查询出来的结果就变成了1.0099999904632568。请教一下,这种问题怎么解决。
已邀请:

kennywu76 - Wood

赞同来自: rochy lbx6z laoyang360 exceptions cccthought

你应该是从doc里读取的数据,如果从_source里读取就没这个问题。 不太清楚doc_values为什么对float类型会有精度损失,不过测试了一下,如果用double,则doc value里读取出来的精度和source里的一样,没有这个问题。
PUT testme
{
  "settings": {},
  "mappings": {
    "doc": {
      "properties": {
        "id": {
          "type": "double"
        }
      }
    }
  }
}

POST testme/doc
{
  "id": 1.01
}

POST testme/_search
{
  "docvalue_fields": [
    "id"
  ]
}

{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "testme",
        "_type": "doc",
        "_id": "eKQxamUBsQ3QCcRZRbR5",
        "_score": 1,
        "_source": {
          "id": 1.01
        },
        "fields": {
          "id": [
            1.01
          ]
        }
      }
    ]
  }
}

 
 
或者觉得doulbe精度过高,浪费存储空间的话,也可以用scaled_float,看起来也是OK的
PUT testme
{
"settings": {},
"mappings": {
"doc": {
"properties": {
"id": {
"type": "scaled_float",
"scaling_factor": 100
}
}
}
}
}

POST testme/doc
{
"id": 1.01
}

POST testme/_search
{
"docvalue_fields": [
"id"
]
}

{
"took": 0,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testme",
"_type": "doc",
"_id": "R6QwamUBsQ3QCcRZyrQK",
"_score": 1,
"_source": {
"id": 1.01
},
"fields": {
"id": [
1.01
]
}
}
]
}
}

zqc0512 - andy zhou

赞同来自:

keyword
 

wjx1015

赞同来自:

mysql  字段price  定义的是 float        在创建索引的时候 直接这样定义这个字段的mapping? 
 如 "price": {
            "type": "keyword"
          }
是这样的么?  我测试貌似没有生效

要回复问题请先登录注册