# Date\_histogram and top\_hits from unique values only

**URL:** <https://discuss.elastic.co/t/date-histogram-and-top-hits-from-unique-values-only/197363>\
**Category:** Elasticsearch\
**Created:** [August 29, 2019, 2:32pm UTC](https://discuss.elastic.co/t/date-histogram-and-top-hits-from-unique-values-only/197363 "2019-08-29T14:32:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tzn01](https://avatars.discourse-cdn.com/v4/letter/t/7bcc69/32.png) [@tzn01](https://discuss.elastic.co/u/tzn01)\
**Post date:** [August 29, 2019, 2:32pm UTC](https://discuss.elastic.co/t/date-histogram-and-top-hits-from-unique-values-only/197363/1 "2019-08-29T14:32:13Z")

</div>

Hi,

I am trying to do a date\_histogram aggregation to show a sum of Duration for each hour.

I have the following documents:  
{  
"EntryTimestamp": 1567029600000,  
"Username": "johndoe",  
"UpdateTimestamp": 1567029600000,  
"Duration": 10,  
"EntryID": "ASDF1234"  
}

The following works very well but my problem is that sometimes multiple documents appear with the same EntryID. So ideally I would need to add a top\_hits somehow, and order by the UpdateTimestamp as I need the last updated document for each unique EntryID. But not sure how to add this to my query.

```
{
	"size": 0,
	"query": {
		"bool": {
			"filter": [{
					"range": {
						"EntryTimestamp": {
							"gte": "1567029600000",
							"lte": "1567065599999",
							"format": "epoch_millis"
						}
					}
				}, {
					"query_string": {
						"analyze_wildcard": true,
						"query": "Username.keyword=johndoe"
					}
				}
			]
		}
	},
	"aggs": {
		"2": {
			"date_histogram": {
				"interval": "1h",
				"field": "EntryTimestamp",
				"min_doc_count": 0,
				"extended_bounds": {
					"min": "1567029600000",
					"max": "1567065599999"
				},
				"format": "epoch_millis"
			},
		    "aggs": {
			    "1": {
				    "sum": {
					    "field": "Duration"
			    	}
			    }
		    }
		}
	}
}
```

---

<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:** [September 26, 2019, 2:32pm UTC](https://discuss.elastic.co/t/date-histogram-and-top-hits-from-unique-values-only/197363/2 "2019-09-26T14:32:14Z")

</div>

Closed on September 26, 2019, 2:32pm UTC

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