Elasticsearch 中的对象聚合嵌套数组

时间:2021-07-13 09:37:07

标签: elasticsearch elasticsearch-aggregation

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 执行类似的聚合,并返回每个类别的计数总和。

在上面的例子中,聚合应该返回 猫:10, 汽车:120 和 狗:5

如果可能的话,想知道如何在 Elasticsearch 中编写此聚合查询。提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用 nestedtermssum 聚合来获得所需的结果。

添加一个带有索引映射、搜索查询和搜索结果的工作示例

索引映射:

{
  "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
            }
          }
        ]
      }
    }
  }