ZRANGE && ZREVRANGE
2020-04-21 本文已影响0人
NotFoundW
ZRANGE && ZREVRANGE
- 返回有序集中,指定区间内的成员。其中成员的位置按分数值递增(从小到大/从大到小)来排序。
- 使用ZRANGE时,具有相同分数值的成员按字典序(lexicographical order)来排列。
- 使用ZREVRANGE时,具有相同分数值的成员按字典序的逆序(reverse lexicographical order)来排列。
Command
$ redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> zrange s2 0 -1
(empty list or set)
127.0.0.1:6379> ZADD fruit 1 cherry 2 plum 2 pear 3 grape
(integer) 4
127.0.0.1:6379> ZRANGE fruit 0 -1 WITHSCORES
1) "cherry"
2) "1"
3) "pear"
4) "2"
5) "plum"
6) "2"
7) "grape"
8) "3"
127.0.0.1:6379> ZREVRANGE fruit 0 -1 WITHSCORES
1) "grape"
2) "3"
3) "plum"
4) "2"
5) "pear"
6) "2"
7) "cherry"
8) "1"
Code
ZREVRANGE就只是ZRANGE相反,此处便不用代码示例
func zrange(c redis.Conn) {
defer c.Do("DEL", "fruit")
c.Do("ZADD", "fruit", 1, "cherry", 2, "plum", 2, "pear", 3, "grape")
membersWithScore, _ := redis.Strings(c.Do("ZRANGE", "fruit", 0, -1, "WITHSCORES"))
fmt.Println("If some members' scores are same, will sort them by lexicographical order.")
for i, v := range membersWithScore {
if i%2 == 0 {
fmt.Println("member is:", v)
} else {
fmt.Println("Score is:", v)
}
}
}
Output
$ go run main.go
If some members' scores are same, will sort them by lexicographical order.
member is: cherry
Score is: 1
member is: pear
Score is: 2
member is: plum
Score is: 2
member is: grape
Score is: 3