在ElasticSearch中聚合嵌套对象

时间:2017-12-09 21:44:34

标签: elasticsearch

假设我们有这份文件:

{
    "Article" : [
      {
        "id" : 12
        "title" : "An article title",
        "categories" : [1,3,5,7],
        "tag" : ["elasticsearch", "symfony",'Obtao'],
        "author" : [
            {
                "firstname" : "Francois",
                "surname": "francoisg",
                "id" : 18
            },
            {
                "firstname" : "Gregory",
                "surname" : "gregquat"
                "id" : "2"
            }
        ]
      }
    },
    {
        "id" : 13
        "title" : "A second article title",
        "categories" : [1,7],
        "tag" : ["elasticsearch", "symfony",'Obtao'],
        "author" : [
            {
                "firstname" : "Gregory",
                "surname" : "gregquat",
                "id" : "2"
            }
        ]
      }
}

如何通过ID查找所有唯一作者?什么是正确的查询?我需要返回所有独特的作者(“author.id”)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先,您应该为字段nested设置author类型的映射。 其次,正如@Taras_Kohut所提到的,在重新索引整个数据之后,你可以这样做:

{
  "size": 0,
  "aggregations": {
    "records": {
      "nested": {
        "path": "author"
      },
      "aggregations": {
        "ids": {
          "terms": {
            "field": "author.id"
          }
        }
      }
    }
  }
}

请参阅Nested Aggregation