1# Sorting by Indexed Fields 2 3As of RediSearch 0.15, it is possible to bypass the scoring function mechanism, and order search results by the value of different document properties (fields) directly - even if the sorting field is not used by the query. For example, you can search for first name and sort by last name. 4 5## Declaring Sortable Fields 6 7When creating the index with `FT.CREATE`, you can declare `TEXT` and `NUMERIC` properties to be `SORTABLE`. When a property is sortable, we can later decide to order the results by its values. For example, in the following schema: 8 9``` 10> FT.CREATE users SCHEMA first_name TEXT last_name TEXT SORTABLE age NUMERIC SORTABLE 11``` 12 13The fields `last_name` and `age` are sortable, but `first_name` isn't. This means we can search by either first and/or last name, and sort by last name or age. 14 15### Note on sortable TEXT fields 16 17In the current implementation, when declaring a sortable field, its content gets copied into a special location in the index, for fast access on sorting. This means that making long text fields sortable is very expensive, and you should be careful with it. 18 19### Normalization (UNF option) 20 21By default, text fields get normalized and lowercased in a Unicode-safe way when stored for sorting. This means that `America` and `america` are considered equal in terms of sorting. 22 23Using the argument UNF (un-normalized form) it is possible to disable the normalization and keep the original form of the value. Therefore, `America` will come before `america`. 24 25## Specifying SORTBY 26 27If an index includes sortable fields, you can add the `SORTBY` parameter to the search request (outside the query body), and order the results by it. This overrides the scoring function mechanism, and the two cannot be combined. If `WITHSCORES` is specified along with `SORTBY`, the scores returned are simply the relative position of each result in the result set. 28 29The syntax for `SORTBY` is: 30 31``` 32SORTBY {field_name} [ASC|DESC] 33``` 34 35* field_name must be a sortable field defined in the schema. 36 37* `ASC` means the order will be ascending, `DESC` that it will be descending. 38 39* The default ordering is `ASC` if not specified otherwise. 40 41## Quick example 42 43``` 44> FT.CREATE users SCHEMA first_name TEXT SORTABLE last_name TEXT age NUMERIC SORTABLE 45 46# Add some users 47> FT.ADD users user1 1.0 FIELDS first_name "alice" last_name "jones" age 35 48> FT.ADD users user2 1.0 FIELDS first_name "bob" last_name "jones" age 36 49 50# Searching while sorting 51 52# Searching by last name and sorting by first name 53> FT.SEARCH users "@last_name:jones" SORTBY first_name DESC 54 55# Searching by both first and last name, and sorting by age 56> FT.SEARCH users "alice jones" SORTBY age ASC 57 58``` 59