elasticsearch - Elasticsearch 中的对象聚合嵌套数组
问题描述
Elasticsearch 中的文档是这样编入索引的
文件 1
{
"task_completed": 10
"tagged_object": [
{
"category": "cat",
"count": 10
},
{
"category": "cars",
"count": 20
}
]
}
文件 2
{
"task_completed": 50
"tagged_object": [
{
"category": "cars",
"count": 100
},
{
"category": "dog",
"count": 5
}
]
}
如您所见,类别键的值本质上是动态的。我想在 SQL 中执行类似的聚合,按类别分组并返回每个类别的计数总和。
在上面的例子中,聚合应该返回 cat: 10, cars: 120 和 dog: 5
如果可能的话,想知道如何在 Elasticsearch 中编写这个聚合查询。提前致谢。
解决方案
您可以使用nested、terms和sum聚合来获得所需的结果。
添加具有索引映射、搜索查询和搜索结果的工作示例
索引映射:
{
"mappings": {
"properties": {
"tagged_object": {
"type": "nested"
}
}
}
}
搜索查询:
{
"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"
}
}
}
}
}
}
}
}
搜索结果:
"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
}
}
]
}
}
}
推荐阅读
- android - 如何在 Android 布局文件中获得两个带有下拉菜单的选项?
- netbeans - NetBeans -- 不代表有效的 javafx Scene Builder 安装
- flutter - Flutter,TextFormField 的内容填充无法正常工作?
- c - C语言中两个数字的32位加法
- javascript - 根据其他单选按钮的值更改单选按钮
- c - 用 C 编写的代码的递归到迭代转换
- html - 响应式网格
- python - 如果洗牌,这个 5-d numpy 数组几乎不占用 RAM
- c++ - 如何使用代码块在 C++ 中连接实时数据库
- date - 将水晶报表中的日期时间字段转换为日期字段