w3resource

Redis Lists: LINSERT

Redis LINSERT Command

Redis LINSERT command inserts value in the list stored at key either before or after the reference value pivot. It is considered an empty list and no operation are performed when the key does not exist. When key exists but does not hold a list value, an error is returned .

Here are some common uses and scenarios for the "LINSERT" command:

  • Dynamic List Updates: Insert elements at specific positions relative to existing elements.
  • Data Organization: Maintain ordered data by inserting new elements in precise locations.
  • Task Management: Prioritize tasks by inserting them before or after specific tasks in a list.
  • Configuration Management: Insert configuration settings in a list relative to existing settings.
  • Session Management: Update session data by adding attributes in specific positions within a list.

Syntax:

LINSERT KEY_NAME BEFORE EXISTING_VALUE NEW_VALUE     

Available since

2.2.0.

Return Value

Integer reply, the length of the list after the insert operation, or -1 when the value pivot was not found.

Return Value Type

Integer

Example: Redis LINSERT

127.0.0.1:6379> LPUSH mycolor1 white black red blue
(integer) 4
127.0.0.1:6379> LRANGE mycolor1 0 -1
1) "blue"
2) "red"
3) "black"
4) "white"

Example: Redis LINSERT : after a member

127.0.0.1:6379> LRANGE mycolor1 0 -1
1) "blue"
2) "red"
3) "black"
4) "white"
127.0.0.1:6379> LINSERT mycolor1 after white green
(integer) 5
127.0.0.1:6379> LRANGE mycolor1 0 -1
1) "blue"
2) "red"
3) "black"
4) "white"
5) "green"

Example: Redis LINSERT : before a member

127.0.0.1:6379> LINSERT mycolor1 after white green
(integer) 5
127.0.0.1:6379> LRANGE mycolor1 0 -1
1) "blue"
2) "red"
3) "black"
4) "white"
5) "green"
127.0.0.1:6379> LINSERT mycolor1 before red yellow
(integer) 6
127.0.0.1:6379> LRANGE mycolor1 0 -1
1) "blue"
2) "yellow"
3) "red"
4) "black"
5) "white"
6) "green"

Previous: LINDEX
Next: LLEN



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-linsert-key-before-after-pivot-value.php