Elasticsearch - Count occurrences of elements in nested field

I have an elasticsearch index with this simplified structure:

{
    "id": "group1",
    "users": [
        {
            "user_id": "user1"
        },
        {
            "user_id": "user2"
        }
    ]
},
{
    "id": "group2",
    "users": [
        {
            "user_id": "user1"
        },
        {
            "user_id": "user3"
        },
    ]
},
{
    "id": "group3",
    "users": [
        {
            "user_id": "user1"
        },
        {
            "user_id": "user3"
        },
    ]
}

I need to get the number of documents where each user appears. Something like this:

[
    {
        "key": "user1",
        "doc_count": 3
    },
    {
        "key": "user2",
        "doc_count": 1
    },
    {
        "key": "user3",
        "doc_count: 2
    }
]

Upvotes: 1

Views: 175

Answers (1)

Bhavya
Bhavya

Reputation: 16172

You need to use nested aggregation with the terms aggregation

Adding a working example with index mapping, search query, and search result

Index Mapping:

{
  "mappings":{
    "properties":{
      "users":{
        "type":"nested"
      }
    }
  }
}

Search Query:

{
 "size":0,
  "aggs": {
    "resellers": {
      "nested": {
        "path": "users"
      },
      "aggs": {
        "unique_user": {
          "terms": {
            "field": "users.user_id.keyword"
          }
        }
      }
    }
  }
}

Search Result:

"aggregations": {
    "resellers": {
      "doc_count": 6,
      "unique_user": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "user1",
            "doc_count": 3
          },
          {
            "key": "user3",
            "doc_count": 2
          },
          {
            "key": "user2",
            "doc_count": 1
          }
        ]
      }
    }
  }

Upvotes: 1

Related Questions