Redis LREM – How to delete multiple occurrences of an element from a list

4 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to delete one or more occurrences of specific element from a list value stored at a key. For this we will use a COMMAND – LREM in redis-cli. 

This command, removes first count occurrences of specified element from a list value stored at a key. The count argument passed in the LREM command influences the operation in the following ways :-

  1. count > 0 :- Removes count occurrences of specified element moving from head (start) to tail (end).
  2. count < 0 :- Removes count occurrences of specified element moving from tail (tail) to head (start).
  3. count = 0 :- Removes all occurrences of specified element.

A non-existing key is interpreted as an empty list, so command will always return 0.

If key exist but value stored at the key is not of list datatype, error is returned. The syntax of redis LREM command is as follows :- 

Syntax :-

redis host:post> LREM <keyname> <count> <element>

Output :- 

- (integer) reply, representing number of elements deleted from the list.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis LREM

References :-

  1. LREM Command Docs

That’s all for how to delete one or more occurrences of specific element from a list value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.