Skip to content

[DOCS] Added sort order explanation #125182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion docs/reference/elasticsearch/rest-apis/sort-search-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,27 @@ GET /my-index-000001/_search
{
"sort" : [
{ "post_date" : {"order" : "asc", "format": "strict_date_optional_time_nanos"}},
"user",
{ "name" : "desc" },
{ "age" : "desc" },
"user",
"_score"
],
"query" : {
"term" : { "user" : "kimchy" }
}
}
```
Order matters when defining multiple sort fields, because {{es}} attempts to sort on the first field in the array. Each subsequent field in the array is only used if the previous fields result in a tie. If documents have identical values across all specified sort fields, {{es}} uses the document ID as the final tie-breaker.

Here's how the example query attempts to sort results:

- First by `post_date`
- If `post_date` values are identical, sorts by `name`
- If both `post_date` and `name` are identical, sorts by `age`
- If the first three fields are identical, sorts by `user`
- If all previous fields are identical, sorts by `_score`

By default, Elasticsearch sorts `numeric` fields in descending order and `string` fields in ascending order unless you explicitly specify otherwise. All three formats shown in the example above are valid. Some make the sort order explicit, while others rely on Elasticsearch’s default behavior.

::::{note}
`_doc` has no real use-case besides being the most efficient sort order. So if you don’t care about the order in which documents are returned, then you should sort by `_doc`. This especially helps when [scrolling](/reference/elasticsearch/rest-apis/paginate-search-results.md#scroll-search-results).
Expand Down
Loading