kolurbo
kolurbo

Reputation: 538

Aggregate nested objects in ElasticSearch

Let's say we have this document:

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

How can I find all unique authors by id? What is the proper query? I need to return all unique authors ("author.id")

Thanks for help.

Upvotes: 0

Views: 54

Answers (1)

Eli
Eli

Reputation: 4926

First, you should set your mapping with nested type for the field author. Second, as @Taras_Kohut mentioned, and after you re-indexed the entire data, you can do:

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

See Nested Aggregation

Upvotes: 1

Related Questions