Sort Query Results



Order by field value

  • Use OrderBy or OrderByDescending to order the results by the specified document-field.

products = list(
    session
    # Make a dynamic query on the 'Products' collection
    .query_collection("Products")
    # Apply filtering (optional)
    .where_greater_than("units_in_stock", 10)
    # Call 'order_by'
    # Pass the document-field by which to order the results and the ordering type
    .order_by("units_in_stock", OrderingType.LONG)
)

# Results will be sorted by the 'units_in_stock' value in ascending order,
# with smaller values listed first
from "Products"
where UnitsInStock > 10
order by UnitsInStock as long

Ordering Type:

  • By default, the order_by methods will determine the OrderingType from the property path expression
    and specify that ordering type in the generated RQL that is sent to the server.

  • E.g. in the above example, ordering by x => x.units_in_stock will result in OrderingType.LONG
    because that property data type is an integer.

  • Different ordering can be forced - see Force ordering type below.

Order by score

  • When querying with some filtering conditions, a basic score is calculated for each item in the results
    by the underlying indexing engine.

  • The higher the score value the better the match.

  • Use order_by_score or order_by_score_descending to order the query results by this score.

products = list(
    session.query_collection("Products")
    # Apply filtering
    .where_less_than("units_in_stock", 5)
    .or_else()
    .where_equals("discontinued", True)
    # Call 'order_by_score'
    .order_by_score()
)

# Results will be sorted by the score value
# with best matching documents (higher score values) listed first.
from "Products"
where UnitsInStock < 5 or Discontinued == true
order by score()

Get resulting score:


The score details can be retrieved by either:

  • Request to include explanations:
    You can get the score details and see how it was calculated by requesting to include explanations in the query. Currently, this is only available when using Lucene as the underlying indexing engine.
    Learn more in Include query explanations.

  • Get score from metadata:

    • The score is available in the @index-score metadata property within each result.
      Note the following difference between the underlying indexing engines:

      • When using Lucene:
        This metadata property is always available in the results.
        Read more about Lucene scoring here.

      • When using Corax:
        In order to enhance performance, this metadata property is Not included in the results by default.
        To get this metadata property you must set the Indexing.Corax.IncludeDocumentScore configuration value to True
        Learn about the available methods for setting an indexing configuration key in this indexing-configuration article.

Order by random

  • Use RandomOrdering to randomize the order of the query results.

  • An optional seed parameter can be passed.

products = list(
    session.query_collection("Products").where_greater_than("units_in_stock", 10)
    # Call 'random_ordering'
    .random_ordering()
    # An optional seed can be passed, e.g.:
    # .random_ordering("someSeed")
)

# Results will be randomly ordered
from "Products"
where UnitsInStock > 10
order by random()
// order by random(someSeed)

Order by spatial

  • If your data contains geographical locations,
    spatial query results can be sorted based on their distance from a specific point.

  • See detailed explanation in Spatial Sorting.

Order by count (aggregation query)

  • The results of a group_by query can be sorted by the count aggregation operation used in the query.

number_of_products_per_category = list(
    session.query_collection("Products", Product)
    # Group by category
    .group_by("category").select_key("category")
    # Count the number of product documents per category
    .select_count()
    # Order by the count value
    .order_by("count", OrderingType.LONG)
)

# Results will contain the number of Product documents per category
# ordered by that count in ascending order.
from "Products"
group by Category
order by count() as long
select key() as "Category", count()

Order by sum (aggregation query)

  • The results of a group_by query can be sorted by the sum aggregation operation used in the query.

number_of_units_in_stock_per_category = list(
    session.query_collection("Products", Product)
    # Group by category
    .group_by("category").select_key("category")
    # Sum the number of units in stock per category
    .select_sum(GroupByField("units_in_stock", "sum"))
    # Order by the sum value
    .order_by("sum", OrderingType.LONG)
)

# Results will contain the total number of units in stock per category
# ordered by that number in ascending order.
from "Products"
group by Category
order by Sum as long
select key() as 'Category', sum(UnitsInStock) as Sum

Force ordering type

  • By default, the order_by methods will determine the OrderingType from the property path expression
    and specify that ordering type in the generated RQL that is sent to the server.

  • A different ordering can be forced by passing the ordering type explicitly to order_by or order_by_descending.

  • The following ordering types are available:

    • OrderingType.LONG
    • OrderingType.DOUBLE
    • OrderingType.ALPHA_NUMERIC
    • OrderingType.STRING (lexicographic ordering)
  • When using RQL directly, if no ordering type is specified, then the server defaults to lexicographic ordering.

Using alphanumeric ordering example:

  • When ordering mixed-character strings by the default lexicographical ordering
    then comparison is done character by character based on the Unicode values.
    For example, "Abc9" will come after "Abc10" since 9 is greater than 1.

  • If you want the digit characters to be ordered as numbers then use alphanumeric ordering
    where "Abc10" will result after "Abc9".

products = list(
    session.query_collection("products")
    # Call 'order_by', order by field 'quantity_per_unit'
    # Pass a second param, requesting to order the text alphanumerically
    .order_by("quantity_per_unit", OrderingType.ALPHA_NUMERIC)
)
from "Products"
order by QuantityPerUnit as alphanumeric

Chain ordering

  • It is possible to chain multiple orderings in the query.
    Any combination of secondary sorting is possible as the fields are indexed independently of one another.

  • There is no limit on the number of sorting actions that can be chained.

  • This is achieved by using the then_by (then_by_descending) and then_by_score (then_by_score_descending) methods.

products = list(
    session.query_collection("Products").where_greater_than("units_in_stock", 10)
    # Apply the primary sort by 'units_in_stock'
    .order_by_descending("units_in_stock", OrderingType.LONG)
    # Apply a secondary sort by the score
    .order_by_score()
    # Apply another sort by 'Name'
    .order_by("name")
)

#  Results will be sorted by the 'units_in_stock' value (descending),
#  then by score,
#  and then by 'name' (ascending).
from "Products"
where UnitsInStock > 10
order by UnitsInStock as long desc, score(), Name

Custom sorters

  • The Lucene indexing engine allows you to create your own custom sorters.
    Custom sorters are not supported by Corax.

  • Custom sorters can be deployed to the server by either:

  • Once the custom sorter is deployed, you can sort the query results with it.

products = list(
    session.query(object_type=Product).where_greater_than("units_in_stock", 10)
    # Order by field 'units_in_stock', pass the name of your custom sorter class
    .order_by("units_in_stock", "MySorter")
)

# Results will be sorted by the 'units_in_stock' value
# according to the logic from 'MySorter' class
from "Products"
where UnitsInStock > 10
order by custom(UnitsInStock, "MySorter")

Syntax

# order_by:
def order_by(
    self, field: str, sorter_name_or_ordering_type: Union[str, OrderingType] = OrderingType.STRING
) -> DocumentQuery[_T]: ...

# order_by_descending:
def order_by_descending(
    self, field: str, sorter_name_or_ordering_type: Union[str, OrderingType] = OrderingType.STRING
) -> DocumentQuery[_T]: ...
Parameter Type Description
field str The name of the field to sort by
sorter_name_or_ordering_type Union[str, OrderingType] The custom sorter class name
-or-
The results sorting ordering type
Can be:
OrderingType.LONG
OrderingType.DOUBLE
OrderingType.ALPHA_NUMERIC
OrderingType.STRING (default)