# How do I first do a timerange filter on date field then extract distinct elements of another field?

**URL:** <https://discuss.elastic.co/t/how-do-i-first-do-a-timerange-filter-on-date-field-then-extract-distinct-elements-of-another-field/179531>\
**Category:** Elasticsearch\
**Created:** [May 3, 2019, 12:04pm UTC](https://discuss.elastic.co/t/how-do-i-first-do-a-timerange-filter-on-date-field-then-extract-distinct-elements-of-another-field/179531 "2019-05-03T12:04:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![siddharthiyer](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/siddharthiyer/32/99818_2.png) [@siddharthiyer](https://discuss.elastic.co/u/siddharthiyer)\
**Post date:** [May 3, 2019, 12:04pm UTC](https://discuss.elastic.co/t/how-do-i-first-do-a-timerange-filter-on-date-field-then-extract-distinct-elements-of-another-field/179531/1 "2019-05-03T12:04:04Z")

</div>

I have a field `cid` that I need to get the distinct elements of. But I need the distinct elements based on when they were added to the database. I want to first do a timestamp range filter, then get the term aggregation of `cid`. I have tried this approach:

```auto
{
	"aggs": {
		"daterange": {
			"range": {
				"field": "@timestamp",
				"ranges": [
						{"from": "2019-05-02", "to": "2019-05-03"}
					]
			},
			"aggs": {
				"result": {
					"terms": {
						"field": "chat_id.keyword"
					}
				}
			}
		}
	},
	"_source":"chat_id"
}

```

But it doesnt aggregate on `cid`.

---

<div class="post-metadata">

**Author:** ![polyfractal](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/polyfractal/32/48162_2.png) [@polyfractal](https://discuss.elastic.co/u/polyfractal)\
**Post date:** [May 6, 2019, 4:49pm UTC](https://discuss.elastic.co/t/how-do-i-first-do-a-timerange-filter-on-date-field-then-extract-distinct-elements-of-another-field/179531/2 "2019-05-06T16:49:20Z")

</div>

What's not working?

I'd move that `range` aggregation into a [`range` query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html) instead, it will be more efficient and give a nicer response format.

You could also use a `date_histogram` aggregation instead, which will generate a bucket-per-time interval.

Otherwise your aggregation looks fine, it should be returning a bucket for each `chat_id.keyword` value.

---

<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:** [June 3, 2019, 4:49pm UTC](https://discuss.elastic.co/t/how-do-i-first-do-a-timerange-filter-on-date-field-then-extract-distinct-elements-of-another-field/179531/3 "2019-06-03T16:49:24Z")

</div>

Closed on June 3, 2019, 4:49pm UTC

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