use*_*206 3 elasticsearch elasticsearch-aggregation
Elasticsearch 中的文档是这样索引的
文件1
{
"task_completed": 10
"tagged_object": [
{
"category": "cat",
"count": 10
},
{
"category": "cars",
"count": 20
}
]
}
Run Code Online (Sandbox Code Playgroud)
文件2
{
"task_completed": 50
"tagged_object": [
{
"category": "cars",
"count": 100
},
{
"category": "dog",
"count": 5
}
]
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,类别键的值本质上是动态的。我想执行类似于 SQL 中的按类别分组的聚合,并返回每个类别的计数总和。
在上面的示例中,聚合应返回cat: 10、cars: 120 和dog: 5
想知道如何在 Elasticsearch 中编写这个聚合查询(如果可能的话)。提前致谢。
您可以使用nested、terms和sum聚合来获得所需的结果。
添加带有索引映射、搜索查询和搜索结果的工作示例
索引映射:
{
"mappings": {
"properties": {
"tagged_object": {
"type": "nested"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
搜索查询:
{
"size": 0,
"aggs": {
"resellers": {
"nested": {
"path": "tagged_object"
},
"aggs": {
"books": {
"terms": {
"field": "tagged_object.category.keyword"
},
"aggs":{
"sum_of_count":{
"sum":{
"field":"tagged_object.count"
}
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
搜索结果:
"aggregations": {
"resellers": {
"doc_count": 4,
"books": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "cars",
"doc_count": 2,
"sum_of_count": {
"value": 120.0
}
},
{
"key": "cat",
"doc_count": 1,
"sum_of_count": {
"value": 10.0
}
},
{
"key": "dog",
"doc_count": 1,
"sum_of_count": {
"value": 5.0
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |