# How to sort search results by date?

**URL:** <https://discuss.elastic.co/t/how-to-sort-search-results-by-date/23788>\
**Category:** Elasticsearch\
**Created:** [June 16, 2015, 9:18pm UTC](https://discuss.elastic.co/t/how-to-sort-search-results-by-date/23788 "2015-06-16T21:18:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ali\_Akhtar](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ali_akhtar/32/785_2.png) [@Ali\_Akhtar](https://discuss.elastic.co/u/Ali_Akhtar)\
**Post date:** [June 16, 2015, 9:18pm UTC](https://discuss.elastic.co/t/how-to-sort-search-results-by-date/23788/1 "2015-06-16T21:18:19Z")

</div>

Is there a way to sort the search results returned by elastic search, by a date / timestamp, e.g so newest results are on top?

Here's the code I'm using for search:

```
SearchRequestBuilder searchReq =
                elasticSearchClient.prepareSearch("my_index")
                .setTypes("my_type")
                .setSize(10)
                .setFrom(offset) //integer determined elsewhere for pagination
                .setQuery(matchQuery("_all", userSubmittedSearchQuery ))
                .setMinScore(1);

SearchResponse result = searchReq.get();   

```

How can I get the results to be sorted by a date / timestamp field, such as "lastModified"?

---

<div class="post-metadata">

**Author:** ![dantuff](https://avatars.discourse-cdn.com/v4/letter/d/e79b87/32.png) [@dantuff](https://discuss.elastic.co/u/dantuff)\
**Post date:** [June 16, 2015, 9:57pm UTC](https://discuss.elastic.co/t/how-to-sort-search-results-by-date/23788/2 "2015-06-16T21:57:02Z")

</div>

You need to use the `FieldSortBuilder` with the `order` set to `desc`.

```
FieldSortBuilder sortBuilder = SortBuilders.fieldSort("lastModified")
        .sortBuilder.missing("_last")
        .sortBuilder.order(SortOrder.DESC);

SearchRequestBuilder searchReq =
        elasticSearchClient.prepareSearch("my_index")
        .setTypes("my_type")
        .setSize(10)
        .setFrom(offset) //integer determined elsewhere for pagination
        .setQuery(matchQuery("_all", userSubmittedSearchQuery ))
        .setMinScore(1)
        .addSort(sortBuilder);

SearchResponse result = searchReq.get();
```

---

<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 6, 2017, 12:07am UTC](https://discuss.elastic.co/t/how-to-sort-search-results-by-date/23788/3 "2017-07-06T00:07:12Z")

</div>


