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

裁剪(Trim)键 key 对应的列表(List),使得它只包含指定范围的元素。

Trim an existing list so that it will contain only the specified range of elements specified. 

偏移值 start 及 stop 都是基于 0(Zero-based),即 0 为列表中的第一个元素,1 为第二个元素,以此类推。

Both start and stop are zero-based indexes, where 0 is the first element of the list (the head), 1 the next element and so on.

比如:LTRIM foobar 0 2 该命令只保留列表 foobar 中的前三个元素。

偏移值 start 及 stop 也可以为负值,表明偏移从列表末尾开始计算,-1 为最后一个元素,-2 为倒数第二个元素,以此类推。

start and end can also be negative numbers indicating offsets from the end of the list, where -1 is the last element of the list, -2 the penultimate element and so on.

当索引超出范围时将会返回错误。如果 start 比列表末尾索引还要大,或 start > stop,将返回一个空列表(此时键 key 被整个删除)。如果 stop 比列表末尾索引还要大,Redis 将会把它视为指向最后一个元素。

Out of range indexes will not produce an error: if start is larger than the end of the list, or start > end, the result will be an empty list (which causes key to be removed). If end is larger than the end of the list, Redis will treat it like the last element of the list.

命令 LTRIM 的一种常见使用方式是与命令 LPUSH / RPUSH 一起使用,例如:

LPUSH mylist someelement
LTRIM mylist 0 99

该对命令将会向列表中压进一个新的元素,但又同时保证当前列表中的元素数量不超过 100。这种使用方式非常有用,比如,使用 Redis 来存储日志。需要注意的是,当以这种方式使用命令 LTRIM 时,它的实际时间复杂度为 O(1),因为平均起来,每次操作最多删除一个元素。

A common use of LTRIM is together with LPUSH / RPUSH. For example:

LPUSH mylist someelement
LTRIM mylist 0 99

This pair of commands will push a new element on the list, while making sure that the list will not grow larger than 100 elements. This is very useful when using Redis to store logs for example. It is important to note that when used in this way LTRIM is an O(1) operation because in the average case just one element is removed from the tail of the list.

  • 简单字符串响应。

    Simple string reply
  • redis> RPUSH mylist "one"
    (integer) 1
    redis> RPUSH mylist "two"
    (integer) 2
    redis> RPUSH mylist "three"
    (integer) 3
    redis> LTRIM mylist 1 -1
    OK
    redis> LRANGE mylist 0 -1
    1) "two"
    2) "three"
  • 版本支持

    1.0.0+

    时间复杂度(Time complexity)

    O(N)N 当前操作删除的元素个数。

    O(N) where N is the number of elements to be removed by the operation.