Redis lists are lists of strings, sorted by insertion order. It’s possible to add elements to a Redis list by pushing items to the front and back of the list with LPUSH/RPUSH and can pop items from the front and back of the list with LPOP/RPOP.
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.
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 |
redis 127.0.0.1:6379> rpush list-key item (integer) 1 redis 127.0.0.1:6379> rpush list-key item2 (integer) 2 redis 127.0.0.1:6379> rpush list-key item (integer) 3
When we push items onto a LIST, the command returns the current length of the list.
redis 127.0.0.1:6379> 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 127.0.0.1:6379> lindex list-key 1 "item2"
We can fetch individual items from the list with LINDEX.
redis 127.0.0.1:6379> lpop list-key "item" redis 127.0.0.1:6379> lrange list-key 0 -1 1) "item2" 2) "item"
Popping an item from the list makes it no longer available.
redis 127.0.0.1:6379>
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.