How to Use LINSERT Command in Redis: Syntax and Examples
Use the
LINSERT command in Redis to insert an element before or after a specified pivot element in a list. The syntax is LINSERT key BEFORE|AFTER pivot value, where key is the list name, pivot is the existing element, and value is the new element to insert.Syntax
The LINSERT command syntax is:
- key: The name of the list where you want to insert the element.
- BEFORE|AFTER: Choose whether to insert the new element before or after the pivot element.
- pivot: The existing element in the list to find.
- value: The new element to insert relative to the pivot.
If the pivot element is not found, the list remains unchanged.
redis
LINSERT key BEFORE pivot value LINSERT key AFTER pivot value
Example
This example shows how to insert a new element before and after a pivot element in a Redis list.
redis
127.0.0.1:6379> RPUSH fruits "apple" "banana" "cherry" (integer) 3 127.0.0.1:6379> LINSERT fruits BEFORE "banana" "avocado" (integer) 4 127.0.0.1:6379> LRANGE fruits 0 -1 1) "apple" 2) "avocado" 3) "banana" 4) "cherry" 127.0.0.1:6379> LINSERT fruits AFTER "banana" "blueberry" (integer) 5 127.0.0.1:6379> LRANGE fruits 0 -1 1) "apple" 2) "avocado" 3) "banana" 4) "blueberry" 5) "cherry"
Output
1) "apple"
2) "avocado"
3) "banana"
4) "blueberry"
5) "cherry"
Common Pitfalls
- If the pivot element does not exist in the list,
LINSERTdoes nothing and returns-1. - Make sure the list key exists and is of type list; otherwise, you get an error.
- Remember that
LINSERTonly inserts relative to the first occurrence of the pivot.
redis
127.0.0.1:6379> LINSERT fruits BEFORE "orange" "grape" (integer) -1 # Pivot "orange" not found, no insertion # Correct usage: 127.0.0.1:6379> LINSERT fruits AFTER "cherry" "date" (integer) 6
Output
(integer) -1
(integer) 6
Quick Reference
| Parameter | Description |
|---|---|
| key | Name of the list |
| BEFORE|AFTER | Position relative to pivot to insert new element |
| pivot | Existing element in the list to find |
| value | New element to insert |
Key Takeaways
Use LINSERT to add an element before or after a pivot element in a Redis list.
If the pivot is not found, LINSERT returns -1 and does not change the list.
LINSERT works only on existing lists and the first occurrence of the pivot.
Always check the return value to confirm if insertion succeeded.