# Sort with dedupe?

**URL:** <https://discuss.elastic.co/t/sort-with-dedupe/29717>\
**Category:** Elasticsearch\
**Created:** [September 21, 2015, 4:02pm UTC](https://discuss.elastic.co/t/sort-with-dedupe/29717 "2015-09-21T16:02:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dunnlow](https://avatars.discourse-cdn.com/v4/letter/d/8797f3/32.png) [@dunnlow](https://discuss.elastic.co/u/dunnlow)\
**Post date:** [September 21, 2015, 4:02pm UTC](https://discuss.elastic.co/t/sort-with-dedupe/29717/1 "2015-09-21T16:02:23Z")

</div>

I'd like to return a user-defined number of hits ordered by date (desc) and deduped.

If I don't dedupe, my query works fine. However, when I use the aggregator with top-hits subaggregation my resulting buckets are NOT a deduped version of my results hits. Can someone tell me what I'm doing wrong (or the best way to do this)?

```
SearchRequestBuilder srb = client.prepareSearch()
   .setIndices("indexA")
   .setScroll(new TimeValue(60000))
   .setQuery(builder)
   .addAggregation(AggregationBuilders.terms("docs")
         .field("dedupId")
         .subAggregation(AggregationBuilders
               .topHits("top_hits")
               .setSize(1)
               .addSort("orderDTS",sortOrder.DESC)))
    .addSort("orderDTS", SortOrder.DESC)
    .setFrom(0)
    .setSize(maxNumResults);
```

---

<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:** [July 5, 2017, 11:49pm UTC](https://discuss.elastic.co/t/sort-with-dedupe/29717/2 "2017-07-05T23:49:01Z")

</div>


