Storing Lists in Redis: Modification Commands
Let’s see how we can modify the data in a List in Redis.
We'll cover the following
In the previous lesson, we looked at a few commands used to insert lists into the Redis database. In this lesson, we will look at how we can modify a List present in the database.
LLEN
command
The LLEN
command is used to find the length of the list, as shown below.
LLEN key
LINDEX
command
The LINDEX
command is used to find the element at a particular index in the list.
LINDEX key index
In the index below, we are fetching the value at index 1.
Please note that the index starts at 0.
LSET
command
The LSET
command is used to update the value at a given index.
In the example below, we have bmw at the index. We will change it to mercedes using the lset command.
LSET key index value
LPUSHX
command
The lpushx
command adds an element to the head of the list if the list exists.
LPUSHX key value
In the example below, we will use the lpushx
command for a key that does not exist, i.e., toyota. It will do nothing.
LINSERT
command
This command is useful if we need to insert an element before a particular element. Let’s say, we need to add the first ten natural numbers in a list. We added them but forgot to add number 6, as shown below:
We have forgotten to add 6, which we need to add before 5. Remember: the elements are added in reverse order in the list since we are inserting at the head.
linsert key before/after pivot value
The pivot is the value before which we need to insert the number.
We will use this command to insert 6 in the list.
Get hands-on with 1400+ tech skills courses.