In Redis, we can use the LREM
command to remove one or more elements from a list. The number of elements removed depends on the arguments we pass.
Syntax
The syntax goes like this:
LREM key count element
Example
Suppose we create a list like this:
RPUSH animals Cat Dog Horse Cat Dog Cat Monkey Dog Cat Dog Buffalo
Result:
(integer) 11
Let’s take a look at the list:
LRANGE animals 0 -1
Result:
1) "Cat" 2) "Dog" 3) "Horse" 4) "Cat" 5) "Dog" 6) "Cat" 7) "Monkey" 8) "Dog" 9) "Cat" 10) "Dog" 11) "Buffalo"
Now let’s use the LREM
command to remove the first two occurrences of Cat
from the list:
LREM animals 2 "Cat"
Result:
(integer) 2
We can see that two elements were removed because the command returned an integer reply of 2
.
We can verify this by taking a look at the list again:
LRANGE animals 0 -1
Result:
1) "Dog" 2) "Horse" 3) "Dog" 4) "Cat" 5) "Monkey" 6) "Dog" 7) "Cat" 8) "Dog" 9) "Buffalo"
The first two occurrences of Cat
have been removed as expected.
Negative Positions
Specifying a negative position removes the elements from the tail of the list:
LREM animals -2 "Dog"
Result:
(integer) 2
We can see that two elements were removed because the command returned an integer reply of 2
.
When we check the list, we can see that they were removed from the tail:
LRANGE animals 0 -1
Result:
1) "Dog" 2) "Horse" 3) "Dog" 4) "Cat" 5) "Monkey" 6) "Cat" 7) "Buffalo"
Remove All Occurrences of the Element
We can use zero (0
) to remove all occurrences of the specified element:
LREM animals 0 "Dog"
Result:
(integer) 2
In this case, there were two matching elements and both were removed.
We can verify this by looking at the list’s contents:
LRANGE animals 0 -1
Result:
1) "Horse" 2) "Cat" 3) "Monkey" 4) "Cat" 5) "Buffalo"
Non-Existent Keys and Empty Lists
Non-existent keys are treated as empty lists and return 0
:
LREM nonexistentkey 3 "Cat"
Result:
(integer) 0