SortCommand

SORT _key_ BY _pattern_ LIMIT _start_ _end_ GET _pattern_ ASC|DESC ALPHA

Sort the elements contained in the List or Set value at key. By defaultsorting is numeric with elements being compared as double precisionfloating point numbers. This is the simplest form of SORT.
SORT mylist
Assuming mylist contains a list of numbers, the return value will bethe list of numbers ordered from the smallest to the bigger number.In order to get the sorting in reverse order use DESC:
SORT mylist DESC
ASC is also supported but it's the default so you don't really need it.If you want to sort lexicographically use ALPHA. Note that Redis isutf-8 aware assuming you set the right value for the LC_COLLATEenvironment variable.
Sort is able to limit the number of results using the LIMIT option:
SORT mylist LIMIT 0 10
In the above example SORT will return only 10 elements, starting fromthe first one (star is zero-based). Almost all the sort options canbe mixed together. For example:
SORT mylist LIMIT 0 10 ALPHA DESC
Will sort mylist lexicographically, in descending order, returning onlythe first 10 elements.
Sometimes you want to sort elements using external keys as weights tocompare instead to compare the actual List or Set elements. For examplethe list mylist may contain the elements 1, 2, 3, 4, that are justthe unique IDs of objects stored at object_1, object_2, object_3and object_4, while the keys weight_1, weight_2, weight_3 and weight_4can contain weights we want to use to sort the list of objectsidentifiers. We can use the following command:
SORT mylist BY weight_*
the BY option takes a pattern (weight_* in our example) that is usedin order to generate the key names of the weights used for sorting.Weight key names are obtained substituting the first occurrence of *with the actual value of the elements on the list (1,2,3,4 in our example).
Still our previous example will return just the sorted IDs. Often it isneeded to get the actual objects sorted (object_1, ..., object_4 in theexample). We can do it with the following command:
SORT mylist BY weight_* GET object_*
Note that GET can be used multiple times in order to get more keys forevery element of the original List or Set sorted.

Return value

Multi bulk reply, specifically a list of sorted elements.

See Also