sort clause

更新时间:
复制 MD 格式

Use a sort clause to control the order of query results. By default, results are sorted by relevance score in descending order. Override this behavior by specifying one or more fields to sort on.

Syntax

sort=<sign><field>[;<sign><field>...]
  • + sorts in ascending order.

  • - sorts in descending order.

Fields can be combined using arithmetic operators (+, -, *, /). Fields combined with an arithmetic operator must be of the same data type.

Use RANK to sort by the relevance score calculated by the sort expression.

Examples

Sort by a single field

sort=+type;-RANK

Results are sorted in ascending order by the type field. When two results have the same type value, they are sorted in descending order by RANK.

Multi-field sort priority

When you specify multiple sorting rules, the system applies them in order:

  1. Sort all results by the first rule.

  2. If two results tie on the first rule, apply the second rule.

  3. Continue until all ties are resolved.

For example, sort=+type;-RANK works as follows:

  • First, sort by type ascending.

  • For results with equal type values, sort by RANK descending.

Sort by an arithmetic expression

sort=-(hits + comments)

Results are sorted in descending order by the sum of each result's hits and comments field values.

Sort by geographic distance

sort=+distance(lon,lat,"120.34256","30.56982")

Results are sorted in ascending order by the distance from the reference location (120.34256, 30.56982). The lon and lat parameters specify the fields that store the longitude and latitude of each result.

Usage notes

  • Default behavior: If no sort clause is specified, sort=-RANK is used. Results are sorted in descending order by relevance score. If RANK is not included in a sort clause, the sort expression has no effect.

  • Attribute fields only: Fields in a sort clause must be attribute fields defined in schema.json.

  • Sort functions: Sort functions that return INT or FLOAT values can be used in a sort clause.

  • STRING field behavior: When sorting by a STRING field, letters are sorted alphabetically, numbers are sorted in descending order, and Chinese characters are sorted by ASCII value.

  • Multi-valued fields: Multi-valued fields cannot be used in a sort clause.

  • Performance: When a sort clause contains multiple sorting rules such as sort=-field1;-field2;-field3, sorting performance depends on the data in each field. For stable sorting performance, include RANK in the sorting rules.