本文内容为 http://www.redis.io/commands/linsert 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
LINSERT key BEFORE|AFTER pivot value

在键 key 对应的列表(List)中的参照值 pivot 之前(Before)或之后(After)插入新值 value

Inserts value in the list stored at key either before or after the reference value pivot.

当键 key 不存在时,当前命令被认为执行于一个空列表。

When key does not exist, it is considered an empty list and no operation is performed.

当键 key 存在,但对应的值不为列表时,将会返回一个错误。

An error is returned when key exists but does not hold a list value.
  • 返回在进行插入操作后,列表的长度。

    如果参照值 pivot 未找到,将返回 -1

    Integer reply: the length of the list after the insert operation, or -1 when the value pivot was not found.
  • redis> RPUSH mylist "Hello"
    (integer) 1
    redis> RPUSH mylist "World"
    (integer) 2
    redis> LINSERT mylist BEFORE "World" "There"
    (integer) 3
    redis> LRANGE mylist 0 -1
    1) "Hello"
    2) "There"
    3) "World"
  • 版本支持

    2.2.0+

    时间复杂度(Time complexity)

    O(N)N 为所需遍历的元素个数。

    O(N) where N is the number of elements to traverse before seeing the value pivot. This means that inserting somewhere on the left end on the list (head) can be considered O(1) and inserting somewhere on the right end (tail) is O(N).