download & runRedis Labs Enterprise Cluster

Learn more

free download

Connect & useRedis Cloud





By creating your account, you agree to our Terms of Use

Forgot your password?

Not Registered?

Forgot your password?

Enter your email address below to have your password reset. We'll send you an email with a link to change your password.

Your IP address will be logged and monitored for this request.

Cancel

Your password has reset!

We have sent you an email with a link to change your password.

OK

eBook

Redis in Action

1.2.2 Lists in Redis

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