1.2.5 Sorted sets in Redis
Like Redis HASHes, ZSETs also hold a type of key and value. The keys (called members) are unique, and the values (called scores) are limited to floating-point numbers. ZSETs have the unique property in Redis of being able to be accessed by member (like a HASH), but items can also be accessed by the sorted order and values of the scores. Figure 1.5 shows an example ZSET with two items.
As is the case with all of the other structures, we need to be able to add, remove, and fetch items from ZSETs. Listing 1.5 offers add, remove, and fetching commands for ZSETs similar to those for the other structures, and table 1.7 describes the commands that we’ll use.
|Command||What it does|
|ZADD||Adds member with the given score to the ZSET|
|ZRANGE||Fetches the items in the ZSET from their positions in sorted order|
|ZRANGEBYSCORE||Fetches items in the ZSET based on a range of scores|
|ZREM||Removes the item from the ZSET, if it exists|
Now that you’ve seen ZSETs and a little of what they can do, you’ve learned the basics of what structures are available in Redis. In the next section, we’ll combine the data storage ability of HASHes with the built-in sorting ability of ZSETs to solve a common problem.