我的弹性搜索文档看起来像:
{
"entityFk": 0,
"entityCode": "ADM",
"entityObj": {
"id": 0,
"code": "ADM",
"description": "ADM - FIRSTCOM"
},
"practiceFk": 54745,
"practiceObj": {
"id": 54745,
"code": "33.04.01.32",
"description": "Artrotomia ou artroscopia com tratamento de lesões articulares circunscritas ",
"practiceValue": 23.5
}
}
}
我想将所有具有entityCode.description等于“FIRST”的“practiceValue”(非null)加起来,所以我提出了这个问题:
{
"size" : 0,
"query" : {
"bool" : {
"must_not" : [
{
"missing" : { "field" : "practiceObj.practiceValue" }
}
],
"must" : [
{
"match" : { "entityObj.description" : "FIRST" }
}
]
}
},
"aggs" : {
"total" : {
"sum" : { "field" : "practiceObj.practiceValue"}
}
}
}
以下是我获得的结果:
{
"took": 26,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 11477,
"max_score": 0,
"hits": []
},
"aggregations": {
"total": {
"value": 1593598.7499999984
}
}
}
交易是:我怎样才能将值四舍五入到小数点后2位。 有人可以帮忙吗? 感谢。
编辑:
这是我的映射:
{
"index_practice_entities": {
"mappings": {
"practice_entities_search": {
"properties": {
"entityCode": {
"type": "string"
},
"entityFk": {
"type": "long"
},
"entityObj": {
"properties": {
"code": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "long"
}
}
},
"practiceFk": {
"type": "long"
},
"practiceObj": {
"properties": {
"code": {
"type": "string"
},
"description": {
"type": "string"
},
"id": {
"type": "long"
},
"practiceValue": {
"type": "double"
}
}
}
}
}
}
}
}
答案 0 :(得分:1)
请尝试下面提到的脚本,它会将聚合值四舍五入到小数位。
"aggs" : {
"total" : {
"sum" : {
"script" : "Math.round(doc['practiceObj.practiceValue'].value*100)/100.0"
}
}
}
答案 1 :(得分:0)
您可以尝试script
来实现这一目标:
"aggs" : {
"total" : {
"sum" : { "script" : "(doc['practiceObj.practiceValue'].value).round(2)" // practiceValue should be double or float
}
}
}
答案 2 :(得分:0)
我写了一篇aggs用于更精确地管理弹性浮点的总和:
{
"query":{
/* your's filters */
},
"aggs":{
"price":{
"sum":{
"field":"price",
"script":"BigDecimal.valueOf(_value).setScale(4, RoundingMode.HALF_UP)",
"missing":0
}
}
}
}
在此示例中,您可以管理将.setScale
更改为2
的比例。