A sort clause controls the order of query results by ranking them against one or more fields. Without a sort clause, results are ranked by relevance score (RANK) in descending order.
Prerequisites
Before you use a sort clause, declare the target fields as attribute fields in your schema.json file. Fields not configured as attribute fields are not supported in sort clauses.
Syntax
{
"sort": [
{
"expression": "<field or expression>",
"order": "asc | desc"
}
]
}Parameters
| Parameter | Description | Default |
|---|---|---|
expression | The field or arithmetic expression to sort by. Use RANK to sort by relevance score. | — |
order | The sort direction. Valid values: asc (ascending), desc (descending). | desc |
Arithmetic expressions: Combine fields using +, -, *, or /. All fields in an expression must share the same data type.
Sort by a single field
Sort results by price in descending order:
{
"sort": [
{
"expression": "price",
"order": "desc"
}
]
}Sort by multiple fields
Specify multiple sorting rules to handle ties. When two results have the same value for the first rule, the second rule determines their order—and so on down the list.
{
"sort": [
{
"expression": "price*10",
"order": "desc"
},
{
"expression": "RANK",
"order": "asc"
}
]
}OpenSearch applies the rules in this example as follows:
Sort by
price*10in descending order.If two results have the same computed price value, sort by relevance score (
RANK) in ascending order.
Note: For stable sorting performance across multiple rules, use sort expressions rather than plain field references.
Use RANK in a sort clause
RANK represents the relevance score calculated by the sort expression. Two behaviors to keep in mind:
If you omit the sort clause entirely, OpenSearch sorts by
RANKin descending order by default.If you include a sort clause but do not include
RANKas one of the rules, the sort expression does not take effect.
To combine field-based sorting with relevance ranking, include RANK explicitly as one of the rules (as shown in the multi-field example above).
Limitations
| Limitation | Details |
|---|---|
| Supported field types | Only attribute fields defined in schema.json are supported. |
| Multi-value fields | Cannot be used in a sort clause. |
| STRING type sorting | Letters sort alphabetically; numbers sort in ascending or descending order; Chinese characters sort by ASCII value. |
| Sort functions | Supported as sort expressions, provided they return an INT or FLOAT value. |