All Products
Search
Document Center

OpenSearch:sort clause

Last Updated:Feb 28, 2024

Overview

You can specify a sort clause to sort query results in ascending order or descending order based on the specified fields.

Syntax

Parameters and usage notes:

  • expression: field

    • field: the field based on which the system sorts query results.

    • You can join fields by using basic arithmetic operators, such as the addition operator (+), subtraction operator (-), multiplication operator (*), and division operator (/). The fields that you join by using an operator must be of the same data type.

    • You can specify RANK as a sorting rule in a sort clause. RANK specifies the relevance scores that are calculated by using the sort expression that you specify.

  • The order parameter specifies the ascending or descending order in which query results are sorted based on the values of the specified fields. Valid values: asc and desc. Default value: desc.

  • OpenSearch allows you to specify multiple sorting rules in a sort clause. The system first sorts query results based on the first sorting rule in the sort clause. For the query results whose relevance scores obtained during the first sorting are the same, the system sorts these query results based on the second sorting rule. The process continues until all the query results are properly sorted.

Example:

{
  "sort" : [
    {
      "expression"  : "price*10",
      "order" : "desc"
    },
    {
      "expression"  : "RANK",
      "order" : "asc"
    }
  ]
}

A sort clause is optional. You can define sort expressions to sort query results in ascending or descending order.

Usage notes

  • A sort clause is optional. If you do not include a sort clause in a query statement, RANK is used as a sorting rule by default. The system sorts query results in descending order based on the relevance scores that are calculated by using the sort expression that you specify. If you include a sort clause in a query statement but do not specify RANK as a sorting rule, the sort expression that you specify does not take effect.

  • The fields that you specify in a sort clause must be the attribute fields that you specify in the schema.json file.

  • You can also use sort functions that return values of the INT type or FLOAT type in a sort clause.

  • If you specify a field of the STRING type in a sort clause, the system sorts letters in alphabetical order, sorts numbers in ascending or descending order, and sorts Chinese characters based on their ASCII values.

  • You cannot specify multi-value fields in a sort clause.

  • If a sort clause contains multiple sorting rules, the sorting performance varies based on the data in each field that is specified in the sorting rules. To ensure stable sorting performance, we recommend that you specify sort expressions.