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

**URL:** <https://discuss.elastic.co/t/get-sum-of-occurrence-of-an-item-in-an-array-in-an-aggregation-query/167239>\
**Category:** Elasticsearch\
**Created:** [February 6, 2019, 8:14am UTC](https://discuss.elastic.co/t/get-sum-of-occurrence-of-an-item-in-an-array-in-an-aggregation-query/167239 "2019-02-06T08:14:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ijas\_ahamed](https://avatars.discourse-cdn.com/v4/letter/i/c89c15/32.png) [@Ijas\_ahamed](https://discuss.elastic.co/u/Ijas_ahamed)\
**Post date:** [February 6, 2019, 8:14am UTC](https://discuss.elastic.co/t/get-sum-of-occurrence-of-an-item-in-an-array-in-an-aggregation-query/167239/1 "2019-02-06T08:14:58Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 6, 2019, 8:15am UTC](https://discuss.elastic.co/t/get-sum-of-occurrence-of-an-item-in-an-array-in-an-aggregation-query/167239/2 "2019-03-06T08:15:03Z")

</div>

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