evitaDB - Fast e-commerce database
logo
page-background

Comparable ordering

Natural ordering on comparable data types is the most common type of ordering. It allows you to sort entities by their attributes in their natural order (numerical, alphabetical, temporal, etc.).

Attribute natural

argument:string!

a mandatory name of a sortable attribute

argument:enum(ASC|DESC)
the ordering direction (ascending or descending), default value is ASC
The constraint allows output entities to be sorted by their attributes in their natural order (numeric, alphabetical, temporal). It requires specification of a single attribute and the direction of the ordering.

To sort products by the number of their sales (the best-selling products first), we can use the following query:

If you want to sort products by their name, which is a localized attribute, you need to specify the entityLocaleEquals constraint in the filterBy part of the query:
The correct is used to order the localized attribute string, so that the order is consistent with the national customs of the language.
The sorting mechanism of evitaDB is somewhat different from what you might be used to. If you sort entities by two attributes in an orderBy clause of the query, evitaDB sorts them first by the first attribute (if present) and then by the second (but only those where the first attribute is missing). If two entities have the same value of the first attribute, they are not sorted by the second attribute, but by the primary key (in ascending order).
If we want to use fast "pre-sorted" indexes, there is no other way to do it, because the secondary order would not be known until a query time. If you want to sort by multiple attributes in the conventional way, you need to define the sortable attribute compound in advance and use its name instead of the default attribute name. The sortable attribute compound will cover multiple attributes and prepares a special sort index for this particular combination of attributes, respecting the predefined order and NULL values behaviour. In the query, you can then use the compound name instead of the default attribute name and achieve the expected results.

Primary key natural

argument:enum(ASC|DESC)
the ordering direction (ascending or descending), default value is ASC
If no ordering constraint is specified in the query, the entities are sorted by their primary key in ascending order. If you want to sort them in descending order, you can use the primaryKeyNatural constraint with the DESC argument. Although the constraint also accepts the ASC argument, it doesn't make sense to use it because this is the default ordering behavior.

To sort products by their primary key in descending order, we can use the following query:

Author: Ing. Jan Novotný

Date updated: 25.6.2023

Documentation Source