EBOOK – REDIS IN ACTION

This book covers the use of Redis, an in-memory database/data structure server.

open all | close all

1.2.5 Sorted sets in Redis

Figure 1.5An example of a ZSET with two members/scores under the key zset-key

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.

Table 1.7Commands used on ZSET values

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

Listing 1.5
The ZADD, ZRANGE, ZRANGEBYSCORE, and ZREM commands in Redis
redis 127.0.0.1:6379> zadd zset-key 728 member1
(integer) 1
redis 127.0.0.1:6379> zadd zset-key 982 member0
(integer) 1
redis 127.0.0.1:6379> zadd zset-key 982 member0
(integer) 0

When we add items to a ZSET, the command returns the number of new items.

redis 127.0.0.1:6379> zrange zset-key 0 -1 withscores
1) "member1"
2) "728"
3) "member0"
4) "982"

We can fetch all of the items in the ZSET, which are ordered by the scores, and scores are turned into floats in Python.

redis 127.0.0.1:6379> zrangebyscore zset-key 0 800 withscores
1) "member1"
2) "728"

We can also fetch a subsequence of items based on their scores.

redis 127.0.0.1:6379> zrem zset-key member1
(integer) 1
redis 127.0.0.1:6379> zrem zset-key member1
(integer) 0

When we remove items, we again find the number of items that were removed.

redis 127.0.0.1:6379> zrange zset-key 0 -1 withscores
1) "member0"
2) "982"


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.