Elasticsearch – Count occurrences of elements in nested field

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top