Use the sort clause to sort search results in ascending or descending order by one or more fields.
Description
The sort clause uses the following syntax: +Field1;-Field2
The
+prefix sorts results by the field in ascending order. The-prefix sorts results in descending order.Fields can be combined using arithmetic operators: addition (
+), subtraction (-), multiplication (*), and division (/). Fields connected by an operator must share the same data type.OpenSearch supports multi-dimension sorting. Separate multiple sorting rules with semicolons (
;). The system applies sorting rules in order: results are first sorted by the first rule, then ties are broken by the second rule, and so on until all results are ordered.RANKis a special sorting rule that represents relevance scores calculated from the sort expression you specified.
Usage notes
The sort clause is optional. When omitted, the default
sort=-RANKapplies — results are sorted by relevance score in descending order. If you include a sort clause but omitRANK, the sort expression you configured has no effect.Fields used in the sort clause must be attribute fields defined in the schema.json file.
Functionality functions that return an INT or FLOAT value can be used as sort fields.
For LITERAL fields, the sort order is: letters sorted alphabetically, numbers sorted in descending order, and Chinese characters sorted by ASCII value.
ARRAY fields are not supported in the sort clause in most cases.
When the sort clause contains multiple rules (for example,
sort=-field1;-field2;-field3), sorting performance depends on the data distribution of each field. For stable performance, useRANKwith a fine sort expression. For example:normalize(field1)100+normalize(field2)10+normalize(field3)+first_phase_score*10000, wherefirst_phase_scoreis the score from the rough sort stage. For details, see Fine sort functions.
Supported functionality functions
distance: Returns the spherical distance between two points. Commonly used for location-based service (LBS) distance sorting.
Example: Sort restaurant search results by distance in ascending order:
query=default:'Restaurant name'&&sort=+distance(lon,lat,"120.34256","30.56982")
tag_match: Matches search query keywords against document tags and scores documents based on matched tag weights. For details, see the link above.
Example:
sort=-tag_match("user_options", options, "mul", "sum", "false", "true", 100).
Example
-
Sort results for the query "Zhejiang University" by type in ascending order. When two documents share the same type, break ties by text relevance. For details on configuring RANK-based tie-breaking, see Configure sort expressions.
query=default:'Zhejiang University'&&sort=+type;-RANK // The fine sort expression can contain text_relevance(field). -
Sort results for the query "Zhejiang University" by the combined score of hits and comments in descending order:
query=default:'Zhejiang University'&&sort=-(hits+comments)