Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting and latest records in ElasticSearch

I've two questions related to ElasticSearch.

1) Is there any way to specify that I want results with specific field sorted in descending order? An equivalt SQL query will be:

select * from table1 where a="b" order by myprimarykey desc;

2) How to get first and last(latest) record?

like image 806
Abhijeet Pathak Avatar asked Dec 27 '22 20:12

Abhijeet Pathak


1 Answers

1) Elasticsearch has quite sophisticated Sorting API that allows you to control sort order. So, in elasticsearch, an equivalent to your MySql query would look like this:

{
    "query" : {
        "term" : { "a" : "b" }
    },
    "sort" : [
        { "myprimarykey" : "desc"} }
    ]
}

Sorting can also be specified on _search URI.

2) To retrieve the first and the last records you would need to perform two searches with desc and asc sort orders and retrieve one record for each. It's possible to combine both queries using Multi Search API.

like image 174
imotov Avatar answered Jan 11 '23 23:01

imotov