Multiple ways to provide sort order corresponding to a field name?

Hi all,

In case of querying the data, while going through the documentation, I found two references to specify the sort order corresponding to a field.

  1. Option 1

    From https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html

    GET /bank/_search { "query": { "match_all": {} }, "sort": [ { "account_number": "asc" } ] }

  2. Option 2

    From https://www.elastic.co/guide/en/elasticsearch/reference/current/_introducing_the_query_language.html

    GET /bank/_search { "query": { "match_all": {} }, "sort": { "balance": { "order": "desc" } } }

In first option, the sort order was provided as a value to the field name. However in case of second option, the sorting details to a specific field name was provided as a document with static key as "order" and the value corresponding to the sort order.

In case both the options are correct, I want to know when should we use the second option compared to the first.

Please help and suggest.

Regards,
Amit Saxena

Option 1 is just shorter and should be used when nothing else than the sort order is specified. If you need to specify more options (missing, ...) then you have option 2.
You also have a third option when you want to specify a field name and that the default options are fine for your use case:

GET /bank/_search { "query": { "match_all": {} }, "sort": ["balance"] }

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#search-request-sort

Hi Jimferenczi,

Thanks for the details, it helped a lot.

Regards,
Amit Saxena

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.