Elasticsearch 中嵌套的对象聚合数组
Nested array of objects aggregation in 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 的类似聚合,按类别分组,return 每个类别的计数总和。
在上面的例子中,聚合应该return
猫:10,
汽车:120和
狗:5
想知道如何在 Elasticsearch 中编写此聚合查询(如果可能)。提前致谢。
您可以使用 nested, terms, and 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
}
}
]
}
}
}
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 的类似聚合,按类别分组,return 每个类别的计数总和。
在上面的例子中,聚合应该return 猫:10, 汽车:120和 狗:5
想知道如何在 Elasticsearch 中编写此聚合查询(如果可能)。提前致谢。
您可以使用 nested, terms, and 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
}
}
]
}
}
}