对象数组的聚合

Aggregation on an array of objects

我的 elastic 中有以下数据。

{
...someData,
languages: [
{
language:{_id: 1, name:"English"}
},
{
language:{_id: 2, name:"Arabic"}
}
]
}

但是当我使用这个查询聚合数据时

    aggs: {

languages: {
            terms: {
                field: "languages.language._id.keyword",
                size: 50
            },
            aggs: {
                value: {
                    terms: {
                        field: "languages.language.name.keyword"
                    }
                }
            }
        }
}

我将获得带有 2 个阿拉伯语和英语桶的英语 ID 阿拉伯语 ID 也一样,因为从技术上讲它包含在那里。

有没有办法return只计算我需要的对象的数量?

谢谢

你试过这个吗:


    aggs: {

languages: {
            terms: {
                field: "languages.language._id.keyword",
                size: 50
            },
      }
 
}

您不需要其他聚合。您可以使用 doc_count

访问

您需要将 languages 字段定义为嵌套,以便对数组的单个元素应用聚合。

配置的嵌套字段:

PUT index0
{
  "mappings": {
    "properties": {
      "languages":{
        "type": "nested"
      }
    }
  }
}

示例文档索引:

POST index0/_doc
{
  "languages": [
    {
      "language": {
        "_id": 1,
        "name": "English"
      }
    },
    {
      "language": {
        "_id": 2,
        "name": "Arabic"
      }
    }
  ]
}

聚合查询示例:

{
  "size": 0,
  "aggs": {
    "languages": {
      "nested": {
        "path": "languages"
      },
      "aggs": {
        "id": {
          "terms": {
            "field": "languages.language._id",
            "size": 10
          },
          "aggs": {
            "name": {
              "terms": {
                "field": "languages.language.name.keyword",
                "size": 10
              }
            }
          }
        }
      }
    }
  }
}

结果:

"aggregations" : {
    "languages" : {
      "doc_count" : 2,
      "id" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : 1,
            "doc_count" : 1,
            "name" : {
              "doc_count_error_upper_bound" : 0,
              "sum_other_doc_count" : 0,
              "buckets" : [
                {
                  "key" : "English",
                  "doc_count" : 1
                }
              ]
            }
          },
          {
            "key" : 2,
            "doc_count" : 1,
            "name" : {
              "doc_count_error_upper_bound" : 0,
              "sum_other_doc_count" : 0,
              "buckets" : [
                {
                  "key" : "Arabic",
                  "doc_count" : 1
                }
              ]
            }
          }
        ]
      }
    }
  }