e-Book - Redis in Action

This book covers the use of Redis, an in-memory database/data structure server.
  • Foreword
  • Preface
  • Acknowledgments
  • About this Book
  • About the Cover Illustration
  • Part 1: Getting Started
  • Part 2: Core concepts
  • Part 3: Next steps
  • Appendix A
  • Appendix B
  • Buy the paperback

    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


    What it does


    Adds member with the given score to the ZSET


    Fetches the items in the ZSET from their positions in sorted order


    Fetches items in the ZSET based on a range of scores


    Removes the item from the ZSET, if it exists

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

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

    redis> 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> zrangebyscore zset-key 0 800 withscores
    1) "member1"
    2) "728"

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

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

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

    redis> 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.