假设我有一个相对简单的索引,包含以下字段......
"testdata": {
"properties": {
"code": {
"type": "integer"
},
"name": {
"type": "string"
},
"year": {
"type": "integer"
},
"value": {
"type": "integer"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以编写一个查询来获取由code类似聚合的值的总和,这样:
{
"from":0,
"size":0,
"aggs": {
"by_code": {
"terms": {
"field": "code"
},
"aggs": {
"total_value": {
"sum": {
"field": "value"
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将返回以下(删节)结果:
"aggregations": {
"by_code": {
"doc_count_error_upper_bound": 478,
"sum_other_doc_count": 328116,
"buckets": [
{
"key": 236948,
"doc_count": 739,
"total_value": {
"value": 12537
}
},
Run Code Online (Sandbox Code Playgroud)
但是,此数据正在馈送到Web前端,在此前端需要显示代码和名称.那么,问题是,是否有可能以某种方式修改查询以返回结果中的name字段和code字段?
因此,例如,结果可能看起来像这样:
"aggregations": {
"by_code": {
"doc_count_error_upper_bound": 478,
"sum_other_doc_count": 328116,
"buckets": [
{
"key": 236948,
"code": 236948,
"name": "Test Name",
"doc_count": 739,
"total_value": {
"value": 12537
}
},
Run Code Online (Sandbox Code Playgroud)
我已经阅读了子聚合,但在这种情况下,code和之间存在一对一的关系name(因此,对于相同的密钥,您不会有不同的名称).另外,在我的实际案例中,还有其他5个字段,比如description我想要返回,所以我想知道是否还有其他方法可以做到.
在SQL中(此数据在交换到ElasticSearch之前最初来自此)我将编写以下查询
SELECT Code, Name, SUM(Value) AS Total_Value
FROM [TestData]
GROUP BY Code, Name
Run Code Online (Sandbox Code Playgroud)
Val*_*Val 10
您可以使用脚本来实现此目的,即您可以指定字段组合,而不是指定字段:
{
"from":0,
"size":0,
"aggs": {
"by_code": {
"terms": {
"script": "[doc.code.value, doc.name.value].join('-')"
},
"aggs": {
"total_value": {
"sum": {
"field": "value"
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您需要确保启用动态脚本以使其正常工作
| 归档时间: |
|
| 查看次数: |
3316 次 |
| 最近记录: |