We have already learned in Chapter 2,Data Types that elements in a Redis list or set are unordered, and elements in a Redis sorted set are ordered by their scores. Sometimes we may need to get a sorted copy of a Redis list or set in some order, or sort elements in a Redis sorted set by an order other than scores. Redis provides a convenient command called SORT
for this purpose. In this recipe, we will take a look at the SORT
command and its examples.
You need to finish the installation of the Redis Server as we described in the Downloading and installing Redis recipe in Chapter 1, Getting Started with Redis.
The steps for using SORT
are as follows:
- Open a Terminal and connect to Redis with
redis-cli
. - If all elements are numeric, we can simply run the
SORT
key to sort the elements in ascending order. Suppose in Relp we store a user's favorite restaurant IDs in a Redis set:
127.0.0.1:6379> SADD "user:123:favorite_restaurant_ids" 200 365 104 455 333 (integer...