如果您将Elasticsearch 5.5
与动态字段映射一起使用
并使用双精度值。当我签入映射时,这些值正在获取浮点类型。使用聚合时,存储桶中的键将失去精度。值0.62
类似于0.6200000047683716
。
代码片段
"aggregations": {
"float_numbers": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 0.6200000047683716,
"doc_count": 1
}
]
}
}
这里是描述的相同问题。 link
我之所以发布此问题,是因为我找到了一个尚未见过的适当解决方案,但对我有很大帮助。
解决方案是将浮点数加倍。这可以通过动态模板来实现。
示例解决方案:
在索引中添加dynamic_templates
尚无项目。
PUT term-test
{
"mappings": {
"demo_typ": {
"dynamic_templates": [
{
"all_to_double": {
"match_mapping_type": "double",
"mapping": {
"type": "double"
}
}
}
]
}
}
}
添加数据
POST term-test/demo_typ
{
"numeric_field": 0.62,
"long_filed": 44
}
检查映射
GET term-test/_mapping
进行汇总
GET term-test/_search
{
"query": {
"match_all": {}
},
"aggs": {
"float_numbers": {
"terms": {
"field": "numeric_field"
}
}
}
}
在Java Api中,您可以执行以下操作
1:首先创建索引
elasticClient.admin()
.indices()
.prepareCreate(indexName)
.execute()
.actionGet();
2:更新映射
JSON
{
"dynamic_templates": [
{
"all_to_double": {
"match_mapping_type": "double",
"mapping": {
"type": "double"
}
}
}
]
}
Json到XContentBuilder,我从link获得了代码
public XContentBuilder getXContentBuilderFromJson(final String json) {
try {
Map<String, Object> map = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>() {});
return XContentFactory.jsonBuilder().map(map);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
更新映射
elasticClient.admin().indices()
.preparePutMapping(indexName)
.setType(yourType)
.setSource(getXContentBuilderFromJson(json))
.execute()
.actionGet();
3:插入数据