How to sort search results by date?


(Ali Akhtar) #1

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"?


(Dan Tuffery) #2

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();

(system) #3