# Double aggregation with unique documents

**URL:** <https://discuss.elastic.co/t/double-aggregation-with-unique-documents/105183>\
**Category:** Elasticsearch\
**Created:** [October 25, 2017, 7:37am UTC](https://discuss.elastic.co/t/double-aggregation-with-unique-documents/105183 "2017-10-25T07:37:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ruben\_Fanjul](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ruben_fanjul/32/23387_2.png) [@Ruben\_Fanjul](https://discuss.elastic.co/u/Ruben_Fanjul)\
**Post date:** [October 25, 2017, 7:37am UTC](https://discuss.elastic.co/t/double-aggregation-with-unique-documents/105183/1 "2017-10-25T07:37:25Z")

</div>

Tables

```
Orders
  orderstate
  time_reserved
  user_id
  product_id

Product
  id
  refid

```

This query hit 76 documents.

```
select * from Orders
	inner join Products on Orders.productid = Products.id 
	where Products.`refid` = 9
	and orderstate like "confirmed"
    group by userid; 

```

With the list of all unique users and I would like to group that with time\_reserved to know the list of unique users first and then group this list by "day" counting the users in this day.

My ElasticSearch query is:

```
{
	"aggs": {
		"group_by_date": {
			"date_histogram": {
				"field": "time_reserved",
				"interval": "day",
				"format": "yyyy-MM-dd"
			},
			"aggs": {
				"amount": {
					"cardinality": {
						"field": "user_id"
					}
				}
			}
		}
	},
	"query": {
		"bool": {
			"filter": [{
				"term": {
					"dealid": "9"
				}
			}],
			"must": [{
				"terms": {
					"orderstate": ["confirmed"]
				}
			}]
		}
	}
}

```

Which works but it hits 144 documents, that is because it is not doing the cardinality in the second aggregation and it is returning duplicate user\_id documents and match with the result of the same query above but without group by:

```
select * from Orders
  inner join Products on Orders.productid = Products.id 
  where Products.`refid` = 9
  and orderstate like "confirmed"; 

```

There is a simple way to have to group by ?

---

<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:** [November 22, 2017, 7:37am UTC](https://discuss.elastic.co/t/double-aggregation-with-unique-documents/105183/2 "2017-11-22T07:37:54Z")

</div>

Closed on November 22, 2017, 7:37am UTC

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