1

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

1 Answer 1

1

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
          }
        ]
      }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.