1. List1.1 插入:LPUSH 、RPUSH 1.2 移除:lpop 、rpop 1.3 获取下表值:lindex 1.4 返回列表的长度:llen 1.5 移除指定个数的值:lrem 1.6 通过下标截取指定长度:LTRIM 1.7 移除列表最后一个元素,移动到新的列表:RPOPLPUSH 1.8 将列表指定下表的值替换为另一个值,更新操作:lset 1.9 在列表指定位置插入值:LINSERT 1.10
1. List
List命令前面都有一个
L
1.1 插入:LPUSH 、RPUSH
# 添加值将一个值或多个值插入头部(左) 127.0.0.1:6379[3]> LPUSH list one (integer) 1 127.0.0.1:6379[3]> LPUSH list two (integer) 2 127.0.0.1:6379[3]> LPUSH list three (integer) 3 # 获取所有值 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "three" 2) "two" 3) "one" # 获取值,倒叙获取 127.0.0.1:6379[3]> LRANGE list 0 1 1) "three" 2) "two" # 添加值将一个值或多个值插入尾部(右) 127.0.0.1:6379[3]> RPUSH list zero (integer) 4 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "three" 2) "two" 3) "one" 4) "zero"
1.2 移除:lpop 、rpop
# 移除list第一个 127.0.0.1:6379[3]> lpop list "three" # 移除list最后一个 127.0.0.1:6379[3]> rpop list "zero" 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "two" 2) "one"
1.3 获取下表值:lindex
127.0.0.1:6379[3]> lindex list 0 "two"
1.4 返回列表的长度:llen
127.0.0.1:6379[3]> llen list (integer) 2
1.5 移除指定个数的值:lrem
127.0.0.1:6379[3]> lrem list 1 one (integer) 1
1.6 通过下标截取指定长度:LTRIM
127.0.0.1:6379[3]> LRANGE mylist 0 -1 1) "hello1" 2) "hello2" 3) "hello3" 127.0.0.1:6379[3]> LTRIM mylist 1 2 OK 127.0.0.1:6379[3]> LRANGE mylist 0 -1 1) "hello2" 2) "hello3" 127.0.0.1:6379[3]>
1.7 移除列表最后一个元素,移动到新的列表:RPOPLPUSH
127.0.0.1:6379[3]> LRANGE mylist 0 -1 1) "hello2" 2) "hello3" 3) "hello1" 127.0.0.1:6379[3]> RPOPLPUSH mylist mylist2 "hello1" 127.0.0.1:6379[3]> LRANGE mylist 0 -1 1) "hello2" 2) "hello3" 127.0.0.1:6379[3]> LRANGE mylist2 0 -1 1) "hello1" 127.0.0.1:6379[3]>
1.8 将列表指定下表的值替换为另一个值,更新操作:lset
# 判断列表是否存在 127.0.0.1:6379[3]> EXISTS list (integer) 0 # 如果不存在列表,更新会报错 127.0.0.1:6379[3]> lset list 0 value0 (error) ERR no such key 127.0.0.1:6379[3]> lpush list value1 (integer) 1 # 如果存在,更新当前下表的值 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "value1" 127.0.0.1:6379[3]> lset list 0 value2 OK 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "value2"
1.9 在列表指定位置插入值:LINSERT
127.0.0.1:6379[3]> RPUSH list "hello" (integer) 1 127.0.0.1:6379[3]> RPUSH list "world" (integer) 2 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "hello" 2) "world" 127.0.0.1:6379[3]> LINSERT list before "world" other (integer) 3 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "hello" 2) "other" 3) "world" 127.0.0.1:6379[3]> LINSERT list after "world" redis (integer) 4 127.0.0.1:6379[3]> LRANGE list 0 -1 1) "hello" 2) "other" 3) "world" 4) "redis"