# Unique values with sort request

**URL:** <https://discuss.elastic.co/t/unique-values-with-sort-request/127563>\
**Category:** Elasticsearch\
**Created:** [April 11, 2018, 2:59am UTC](https://discuss.elastic.co/t/unique-values-with-sort-request/127563 "2018-04-11T02:59:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mrbushid0](https://avatars.discourse-cdn.com/v4/letter/m/a87d85/32.png) [@mrbushid0](https://discuss.elastic.co/u/mrbushid0)\
**Post date:** [April 11, 2018, 2:59am UTC](https://discuss.elastic.co/t/unique-values-with-sort-request/127563/1 "2018-04-11T02:59:45Z")

</div>

Hi everyone,

I currently have a query with the purpose being to only retrieve documents with a unique "Object ID"

And then order the documents by the date they were created

It'd be the equivalent to "SELECT DISTINCT id, DateCreated, Cat FROM table GROUP BY ObjectID ORDER BY DateCreated DESC" in SQL

However, the sort does not seem to work, I'm not sure if this even possible / defeats the purpose of top hits, or if I need to add another aggregation ?

Elasticsearch version: 5.6.5

> ```
> {
> "aggs": {
> "agg1": {
> "terms": {
> "field": "ObjectID"
> },
> "aggs": {
> "top_docs": {
> "top_hits": {
> "sort": [
> {
> "DateCreated": {
> "order": "asc"
> }
> }
> ],
> "_source": {
> "includes": [
> "id", "DateCreated", "Cat", "Name"
> ]
> },
> "size" : 1
> }
> }
> }
> }
> }
> }
> 
> ```

Any assistance would be greatly appreciated

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [April 18, 2018, 6:54am UTC](https://discuss.elastic.co/t/unique-values-with-sort-request/127563/2 "2018-04-18T06:54:22Z")

</div>

Instead of using the aggregation you may want to try the [field collapsing API](https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-collapse.html)

---

<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:** [May 16, 2018, 6:58am UTC](https://discuss.elastic.co/t/unique-values-with-sort-request/127563/3 "2018-05-16T06:58:44Z")

</div>

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