Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch sort by a field and use another field if its null

I have Post model with lastRepliedTime and createdTime attributes. How can I sort this Post by lastRepliedTime, but when its value is null, I use createdTime as sort value?

For example, I have this data:

ID  createdTime          lastRepliedTime
1   2015-05-27 13:48:10  2015-06-04 16:34:43
2   2015-06-09 05:23:38  2015-06-24 00:30:06
3   2015-06-09 17:34:56  NULL

If I sort by ascending order, I want the sort result to be like this:

ID  createdTime          lastRepliedTime
1   2015-05-27 13:48:10  2015-06-04 16:34:43
3   2015-06-09 17:34:56  NULL
2   2015-06-09 05:23:38  2015-06-24 00:30:06

I've found the solution using MySQL in here. But is there any way to sort it using Elasticsearch?

like image 423
rap13 Avatar asked Apr 13 '16 11:04

rap13


1 Answers

Have you try ?

{
    "sort": [
        { "lastRepliedTime": { "order": "asc" }},
        { "createdTime": { "order": "asc" }}
    ],
    "query" : {
       "match_all" : { }
    }
}
like image 98
Erms Avatar answered Oct 24 '22 09:10

Erms