Elasticsearch排序结果异常:float字段sort值与实际值不符求助
Elasticsearch排序异常:float字段排序值与源数据不符
问题说明
number_2字段定义为float类型,执行降序排序查询时,发现源数据中number_2: 20164279的文档,返回结果的sort字段值为20164280,导致排序逻辑混乱。删除并重建索引后问题仍然存在。
查询DSL
{ "from": 0, "size": 50, "timeout": "60s", "query": { "bool": { "must": [ { "match_all": { "boost": 1 } }, { "bool": { "must": [ { "term": { "item": { "value": "project_online_1.1002", "boost": 1 } } } ], "adjust_pure_negative": true, "boost": 1 } } ], "adjust_pure_negative": true, "boost": 1 } }, "sort": [ { "number_2": { "order": "desc" } } ] }
异常结果示例
{ "_index": "blue_0", "_type": "_doc", "_id": "project_online_1_1002_20164279", "_score": null, "_source": { "project": "project_online_1", "item": "project_online_1.1002", "text_0": "emp3", "bool_0": false, "number_2": 20164279, "bool_1": false, "bool_2": false, "text_4": "3xs7vovx", "bool_3": false, "number_4": 0, "datetime_6": "2023-08-09T10:15:30.281Z", "datetime_7": "2023-08-09T10:16:06.751Z", "number_8": null, "text_8": "KeDUkyqM0OjJ7ZlIdDNMe9.png", "number_12": 2026, "text_18": null, "number_30": 188, "text_22": "4f4becdd-88b1-4b60-ad44-de90510fcb54", "text_1": "free", "text_2": null, "bool_4": true, "bool_5": false, "bool_6": false, "bool_7": false, "bool_8": true, "number_31": null, "text_23": null }, "sort": [ 20164280 ] }, { "_index": "blue_0", "_type": "_doc", "_id": "project_online_1_1002_20164278", "_score": null, "_source": { "project": "project_online_1", "item": "project_online_1.1002", "text_0": "0809_app_setting_test_test_2", "bool_0": false, "number_2": 20164278, "bool_1": false, "bool_2": false, "text_4": "rotcqizm", "bool_3": false, "number_4": 0, "datetime_6": "2023-08-09T10:15:15.459Z", "datetime_7": "2023-08-10T10:04:06.839Z", "number_8": null, "text_8": "vMx5AqClFbKPc0Nov0PHV.png", "number_12": 2026, "text_18": null, "number_30": 227, "text_22": "277a7ae7-9cd3-40a4-82f8-fda0ea500742", "text_1": "free", "text_2": null, "bool_4": true, "bool_5": false, "bool_6": false, "bool_7": false, "bool_8": true, "number_31": null, "text_23": null }, "sort": [ 20164278 ] }
原因分析
这是单精度float类型的精度限制导致的:
- float类型的有效十进制精度仅为6-7位,而20164279是8位整数,超出了float的精确存储范围。
- Elasticsearch在索引时会将该值转换为float类型存储,此时无法精确表示20164279,会被舍入到最近的可表示的float值(即20164280)。
_source中保留的是原始输入的数值,但排序是基于索引中存储的近似float值执行的,因此出现了sort值与源数据不一致的情况。
解决方案
- 改用整数类型:如果number_2字段存储的都是整数,将字段类型修改为
integer或long,这类类型可以精确存储该范围内的数值。 - 改用double类型:如果必须使用浮点类型,替换为
double类型,double的有效精度为15-17位,能够精确存储该范围内的整数。
内容的提问来源于stack exchange,提问作者freedom
相关产品推荐
相关产品推荐

