sort clause

更新时间:
复制 MD 格式

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

ParameterDescriptionDefault
expressionThe field or arithmetic expression to sort by. Use RANK to sort by relevance score.
orderThe 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:

  1. Sort by price*10 in descending order.

  2. 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 RANK in descending order by default.

  • If you include a sort clause but do not include RANK as 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

LimitationDetails
Supported field typesOnly attribute fields defined in schema.json are supported.
Multi-value fieldsCannot be used in a sort clause.
STRING type sortingLetters sort alphabetically; numbers sort in ascending or descending order; Chinese characters sort by ASCII value.
Sort functionsSupported as sort expressions, provided they return an INT or FLOAT value.