Skip to content

Commit 4fca8e1

Browse files
georgewallacethekofimensahleemthompo
authored
[DOCS] Added sort order explanation (elastic#125182) (elastic#126759)
* Added explanation of sort order and default behavior * Update docs/reference/elasticsearch/rest-apis/sort-search-results.md --------- Co-authored-by: Kofi B <[email protected]> Co-authored-by: Liam Thompson <[email protected]>
1 parent 4b2750e commit 4fca8e1

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

docs/reference/elasticsearch/rest-apis/sort-search-results.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,27 @@ GET /my-index-000001/_search
3636
{
3737
"sort" : [
3838
{ "post_date" : {"order" : "asc", "format": "strict_date_optional_time_nanos"}},
39-
"user",
4039
{ "name" : "desc" },
4140
{ "age" : "desc" },
41+
"user",
4242
"_score"
4343
],
4444
"query" : {
4545
"term" : { "user" : "kimchy" }
4646
}
4747
}
4848
```
49+
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.
50+
51+
Here's how the example query attempts to sort results:
52+
53+
- First by `post_date`
54+
- If `post_date` values are identical, sorts by `name`
55+
- If both `post_date` and `name` are identical, sorts by `age`
56+
- If the first three fields are identical, sorts by `user`
57+
- If all previous fields are identical, sorts by `_score`
58+
59+
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.
4960

5061
::::{note}
5162
`_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).

0 commit comments

Comments
 (0)