Redis provides a couple of commands that allow us to sort the elements in a list, set, or sorted set.
The SORT
command is probably the most obvious, and does exactly what its namesake promises. However, there’s also a SORT_RO
command, which is a read-only variant of the SORT
command.
Example
If you just want to do a sort operation without storing the result, you can use either command – SORT
or SORT_RO
. However, bear in mind that there may be implications when using the SORT
command (see “The Difference Between SORT
and SORT_RO
” below).
Here’s an example of using SORT_RO
:
SORT_RO animals ALPHA
Result:
1) "Bird" 2) "Cat" 3) "Cow" 4) "Dog" 5) "Horse" 6) "Zebra"
Here, I included the ALPHA
modifier, which is used to sort string values. In this case, the animals
key contains a set, and that set contains string values.
We can get the same result with the SORT
command:
SORT animals ALPHA
Result:
1) "Bird" 2) "Cat" 3) "Cow" 4) "Dog" 5) "Horse" 6) "Zebra"
As mentioned, there could be implications with using SORT
over SORT_RO
(see below).
The Difference Between SORT
and SORT_RO
The main difference between SORT
and SORT_RO
is that SORT
provides a STORE
option. This enables us to store the sorted list/set/sorted set in a new key:
SORT animals DESC ALPHA STORE animals_desc
Result:
(integer) 6
Here, I sorted the list in descending order, then stored it in a key called animals_desc
.
Let’s check the contents of the new key:
LRANGE animals_desc 0 -1
Result:
1) "Zebra" 2) "Horse" 3) "Dog" 4) "Cow" 5) "Cat" 6) "Bird"
We used the LRANGE
command because the SORT
command stores the result as a list, and LRANGE
returns the elements of a list.
Note that because of the STORE
option, SORT
is technically flagged as a writing command in the Redis command table. This means that read-only replicas in a Redis Cluster will redirect it to the master instance even if the connection is in read-only mode.
Therefore, if this is a concern for you, you can use SORT_RO
command in place of the SORT
command. The SORT_RO
variant was introduced in order to allow SORT
behaviour in read-only replicas without breaking compatibility on command flags.