ZSCAN
用于迭代有序集合中的元素(包括元素成员和元素分值)
ZSCAN key cursor [MATCH pattern] [COUNT count]
最后的那个COUNT,当有序集合中成员较多时用得上。下面示例中的有序集合的成员很少,所以一次性scan出来。当成员较多时,不会一次性将scan的结果显示出来,这时就需要使用COUNT加大显示的结果的数量。
Command
127.0.0.1:6379> ZADD vehicle 0 benz 1 audi 2 chrysler 3 bmw
(integer) 4
127.0.0.1:6379> ZSCAN vehicle 0
1) "0"
2) 1) "benz"
2) "0"
3) "audi"
4) "1"
5) "chrysler"
6) "2"
7) "bmw"
8) "3"
127.0.0.1:6379> ZSCAN vehicle 0 MATCH b*
1) "0"
2) 1) "benz"
2) "0"
3) "bmw"
4) "3"
Code
此处忽略了错误处理,比如
redis.Scan
的错误处理
func zscan(c redis.Conn) {
defer c.Do("DEL", "vehicle")
c.Do("ZADD", "vehicle", 0, "bmw", 1, "audi", 2, "chrysler", 3, "bmw")
zscanResult, _ := redis.Values(c.Do("ZSCAN", "vehicle", 0))
var cursor int
var membersAndScores []string
redis.Scan(zscanResult, &cursor, &membersAndScores)
fmt.Println("The new cursor is:", cursor)
for i, v := range membersAndScores {
if i%2 == 0 {
fmt.Println("Member", i/2, "is:", v)
} else {
fmt.Println("Score of member", (i-1)/2, "is:", v)
}
}
}
Output
$ go run main.go
The new cursor is: 0
Member 0 is: audi
Score of member 0 is: 1
Member 1 is: chrysler
Score of member 1 is: 2
Member 2 is: bmw
Score of member 2 is: 3