Get sum of occurrence of an item in an array in an aggregation query

I have documents of below structure

{
user_id: 'user_id',
tags: ['tag_1', 'tag_2', 'tag_3', 'tag_1'],
time: 123 // timestamp
}

I used below query to get all users which has a list of tags

{
  "query": {
    "bool": {
      "must": [],
      "filter": {
        "terms": {
          "tags": [
            "tag_1",
            "tag_6"
          ]
        }
      }
    }
  },
  "aggs": {
    "users": {
      "terms": {
        "field": "user_id",
        "size": 100
      }
    }
  }
}

This query return user_id with total document count as below

{
  "aggregations": {
    "users": {
      "doc_count_error_upper_bound": 9882,
      "sum_other_doc_count": 435400587,
      "buckets": [
        {
          "key": 34611, // user_id
          "doc_count": 1026
        }
      ]
    }
  }
}

Actually I need to get sum of items actually occurred in the documents as below

{
  "aggregations": {
    "users": {
      "doc_count_error_upper_bound": 9882,
      "sum_other_doc_count": 435400587,
      "buckets": [
        {
          "key": 34611, // user_id
          "sum": 9897 // in total 9897 times tag_1 and tag_6 from 1026 documents
        }
      ]
    }
  }
}

I can't find solution for this query. Can anyone help me in this.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.