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.2 Lists in Redis

    Redis List
    Figure 1.2An example of a LIST with three items under the key, list-key. Note that item can be in the list more than once.

    In the world of key-value stores, Redis is unique in that it supports a linked-list structure. LISTs in Redis store an ordered sequence of strings, and like STRINGs, I represent figures of LISTs as a labeled box with list items inside. An example of a LIST can be seen in figure 1.2.

    The operations that can be performed on LISTs are typical of what we find in almost any programming language. We can push items to the front and the back of the LIST with LPUSH/RPUSH; we can pop items from the front and back of the list with LPOP/RPOP; we can fetch an item at a given position with LINDEX; and we can fetch a range of items with LRANGE. Let’s continue our Redis client interactions by following along with interactions on LISTs, as shown in listing 1.2. Table 1.4 gives a brief description of the commands we can use on lists.

    Table 1.4 Commands used on LIST values
    Command What it does
    RPUSH Pushes the value onto the right end of the list
    LRANGE Fetches a range of values from the list
    LINDEX Fetches an item at a given position in the list
    LPOP Pops the value from the left end of the list and returns it
    Listing 1.2
    The RPUSH, LRANGE, LINDEX, and LPOP commands in Redis
    redis> rpush list-key item
    (integer) 1
    redis> rpush list-key item2
    (integer) 2
    redis> rpush list-key item
    (integer) 3

    When we push items onto a LIST, the command returns the current length of the list.

    redis> lrange list-key 0 -1
    1) "item"
    2) "item2"
    3) "item"

    We can fetch the entire list by passing a range of 0 for the start index and -1 for the last index.

    redis> lindex list-key 1

    We can fetch individual items from the list with LINDEX.

    redis> lpop list-key
    redis> lrange list-key 0 -1
    1) "item2"
    2) "item"

    Popping an item from the list makes it no longer available.


    Even if that was all that we could do with LISTs, Redis would already be a useful platform for solving a variety of problems. But we can also remove items, insert items in the middle, trim the list to be a particular size (discarding items from one or both ends), and more. We’ll talk about many of those commands in chapter 3, but for now let’s keep going to see what SETs can offer us.