How to Create and Manipulate a List in Redis
We have already covered in another tutorial how to create keys in redis with
redis-cli. You can find that tutorial here. In this tutorial, we will be looking at how to create lists.
How to create a new list in redis
To create your first list, run the below command:
redis-cli lpush myList "one"
If you are already in redis-cli, you don't need to write it. Simply write
lpush myList "one". Above, we create a list with one item called "myList."
How to add to your list in redis
To add a new element to the start of your list, use
lpush. For example, to add another item to the start of "myList", run the following:
lpush myList "two"
To add a new element to the end of your list, use
rpush myList "three"
To add more than one element when using
lpush, separate them with spaces:
lpush myList "four" "five" "six"
Viewing a list with redis
To view a list, run
lrange, with your list name and the start and end point you want to retrieve data for. For example, the below will show the first 6 values from our list:
lrange myList 0 5
Similarly, we can start later in the list. The below selects the 3 elements from the 2nd to 5th in our list:
lrange myList 2 4
Removing an item from a list in redis
To remove an item, use
lrem to remove counting from the left or
rrem from the right. The below removes the first two instances of the list item "one", from the left.
lrem myList 2 "one"
If you simply want to remove the first or last element, use
lpop for removing the first, or
rpop for removing the last.
More Tips and Tricks for Redis
- How to delete all keys and everything in Redis
- How to Create and Manipulate a List in Redis
- Getting Started with Redis and Node.JS
- Make your SSR site Lightning Fast with Redis Cache
- A Complete Guide to Redis Hashes
- How to create key value pairs with Redis
- How to Install Redis
- How to get all keys in Redis