redis数据库操作(3)
set类型
添加元素到无序集合:
sadd KEY VALUE1 VALUE2 VALUE3 例:( sadd my_set1 a b c d d c s a )
获取无序集合的元素:
smembers KEY 例:( smembers my_set1 )
结果:
1) "c"
2) "s"
3) "a"
4) "d"
5) "b"
删除无序集合中指定元素:
srem KEY VALUE 例:( srem my_set1 a )
通过smembers my_set1查询结果:
1) "c"
2) "s"
3) "d"
4) "b"
删除无序集合中随机元素:
spop KEY VALUE 例:( spop my_set1 )
通过smembers my_set1查询结果:
1) "c"
2) "s"
3) "b"
移动一个集合的元素到另一个集合:
smove SRC_KEY DST_KEY VALUE 例:( smove my_set1 my_set2 s )
通过smembers my_set1查询结果:
1) "c"
2) "b"
通过smembers my_set2查询结果:
1) "s"
判断集合是否存在某个元素:
sismember KEY VALUE 例:( sismember my_set1 b )
交集:
sinter KEY1 KEY2
例:
sadd my_set1 a b c d e
sadd my_set2 c d e f g
sinter my_set1 my_set2
结果:
1) "c"
2) "d"
3) "e"
把 KEY1 KEY2的交集合并到 KEY3:
sinterstore KEY3 KEY1 KEY2
例:
sinterstore my_set3 my_set1 my_set2
通过smembers my_set3查询结果:
1) "d"
2) "c"
3) "e"
并集:
sunion KEY1 KEY2
例:
sunion my_set1 my_set2
结果:
1) "g"
2) "c"
3) "s"
4) "d"
5) "a"
6) "f"
7) "e"
8) "b"
把 KEY1 KEY2的并集合并到 KEY3:
sunionstore KEY3 KEY1 KEY2
例:
sunionstore my_set3 my_set1 my_set2
通过smembers my_set3查询结果:
1) "g"
2) "c"
3) "s"
4) "d"
5) "a"
6) "f"
7) "e"
8) "b"
差集:(在集合1中,去除集合2中有的元素,留下集合2中没有,只在集合1中有的元素)
sdiff KEY1 KEY2
例:
sdiff my_set1 my_set2
结果:
1) "a"
2) "b"
把 KEY1 KEY2的差集合并到 KEY3:
sdiffstore KEY3 KEY1 KEY2
例:
sdiffstore my_set3 my_set2 my_set1
通过smembers my_set3查询结果:
1) "g"
2) "f"
3) "s"
获取集合中元素个数:
scard KEY
例:
scard my_set1
集合中随机返回一个元素:
srandmember KEY
例:
srandmember my_set1
zset类型
添加元素到有序集合:
zadd KEY SCORE VALUE
例:
zadd my_zset 1 'one'
zadd my_zset 2 'two'
zadd my_zset 3 'three'
zadd my_zset 4 'four'
zadd my_zset 5 'five'
正序获取有序集合中的元素:
zrange KEY START STOP (withscores)
例:
zrange my_zset 0 -1
结果:
1) "one"
2) "two"
3) "three"
4) "four"
5) "five"
例:
zrange my_zset 0 3 withscores
结果:
1) "one"
2) "1"
3) "two"
4) "2"
5) "three"
6) "3"
7) "four"
8) "4"
倒序获取有序集合中的元素:
zrevrange KEY START STOP (withscores)
例:
zrevrange my_zset 1 3
结果:
1) "four"
2) "three"
3) "two"
例:
zrevrange my_zset 1 -1 withscores
1) "four"
2) "4"
3) "three"
4) "3"
5) "two"
6) "2"
7) "one"
8) "1"
删除有序集合中的元素:
zrem KEY VALUE
例:
zrem my_zset two
通过zrange my_zset 0 -1查看结果:
1) "one"
2) "three"
3) "four"
4) "five"
在正序中查找有序集合中元素的位置:
zrank KEY VALUE
例:
zrank my_zset five
结果:
3
在反序中查找有序集合中元素的位置:
zrevrank KEY VALUE
例:
zrevrank my_zset five
结果:
0
查看有序集合元素数:
zcard KEY
例:
zcard my_set
返回集合中 SCORE 在给定区间的元素:
zrangebyscore KEY SCORE_MIN SCORE_MAX (withscores)
例:
zrangebyscore my_zset 1 4
结果:
1) "one"
2) "three"
3) "four"
例:
zrangebyscore my_zset 1 4 withscores
结果:
1) "one"
2) "1"
3) "three"
4) "3"
5) "four"
6) "4"
返回集合中 SCORE 在给定区间的元素的数量:
zcount KEY SCORE_MIN SCORE_MAX
例:
zcount my_zset 1 4
查看元素的 SCORE 值:
zscore KEY VALUE
例:
zscore my_zset five
删除集合中排名在给定区间的元素(正向):
zremrangebyrank KEY START STOP
例:
zremrangebyrank my_zset 0 2
删除集合中 score 在给定区间的元素:
zremrangebyscore KEY SCORE_MIN SCORE_MAX
例:
zremrangebyscore my_zset 4 5