ZRANGEBYSCORE && ZREVRANGEBYSCORE
- 返回有序集中指定分数区间内的所有的成员。有序集成员按分数值递减(从小到大/从大到小)的次序排列。
- 使用ZRANGEBYSCORE时,具有相同分数值的成员按字典序( lexicographical order )排列。
- 使用ZREVRANGEBYSCORE时,具有相同分数值的成员按字典序的逆序(reverse lexicographical order )排列。
- 使用
(
表示开区间 - 使用
-inf
和+inf
表示不限制最小分数和最大分数,在使用ZRANGEBYSCORE,-inf
应在前面,因为是从小到大,ZREVRANGEBYSCORE反之 -
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
中的LIMIT的使用,和ZRANGEBYLEX 相同,不再记录
Command
127.0.0.1:6379> ZADD fruit 1 cherry 2 plum 2 pear 3 grape
(integer) 4
// 查询整个有序集合
127.0.0.1:6379> ZRANGEBYSCORE fruit -inf +inf WITHSCORES
1) "cherry"
2) "1"
3) "pear"
4) "2"
5) "plum"
6) "2"
7) "grape"
8) "3"
// 查询分数小于等于1的成员
127.0.0.1:6379> ZRANGEBYSCORE fruit -inf 1 WITHSCORES
1) "cherry"
2) "1"
// 查询分数大于2的成员
127.0.0.1:6379> ZRANGEBYSCORE fruit (2 +inf WITHSCORES
1) "grape"
2) "3"
// 查询分数大于等于1,且小于等于2的成员
127.0.0.1:6379> ZRANGEBYSCORE fruit 1 2 WITHSCORES
1) "cherry"
2) "1"
3) "pear"
4) "2"
5) "plum"
6) "2"
Code
只以ZRANGEBYSCORE示例
func zrangebyscore(c redis.Conn) {
defer c.Do("DEL", "fruit")
c.Do("ZADD", "fruit", 1, "cherry", 2, "plum", 2, "pear", 3, "grape")
colorlog.Info("1. Query all the members.")
membersWithScore, _ := redis.Strings(c.Do("ZRANGEBYSCORE", "fruit", "-inf", "+inf", "WITHSCORES"))
for i, v := range membersWithScore {
if i%2 == 0 {
fmt.Println("member is:", v)
} else {
fmt.Println("Score is:", v)
}
}
colorlog.Info("2. Query members that score is less than or equal with 1.")
membersWithScore, _ = redis.Strings(c.Do("ZRANGEBYSCORE", "fruit", "-inf", "1", "WITHSCORES"))
for i, v := range membersWithScore {
if i%2 == 0 {
fmt.Println("member is:", v)
} else {
fmt.Println("Score is:", v)
}
}
colorlog.Info("3. Query members that score is greater than 2.")
membersWithScore, _ = redis.Strings(c.Do("ZRANGEBYSCORE", "fruit", "(2", "+inf", "WITHSCORES"))
for i, v := range membersWithScore {
if i%2 == 0 {
fmt.Println("member is:", v)
} else {
fmt.Println("Score is:", v)
}
}
colorlog.Info("4. Query members that score is greater than or equal with 1, and lees than or equal with 2.")
membersWithScore, _ = redis.Strings(c.Do("ZRANGEBYSCORE", "fruit", "1", "2", "WITHSCORES"))
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
[INF]2020/04/21 11:06:31 1. Query all the members.
member is: cherry
Score is: 1
member is: pear
Score is: 2
member is: plum
Score is: 2
member is: grape
Score is: 3
[INF]2020/04/21 11:06:31 2. Query members that score is less than or equal with 1.
member is: cherry
Score is: 1
[INF]2020/04/21 11:06:31 3. Query members that score is greater than 2.
member is: grape
Score is: 3
[INF]2020/04/21 11:06:31 4. Query members that score is greater than or equal with 1, and lees than or equal with 2.
member is: cherry
Score is: 1
member is: pear
Score is: 2
member is: plum
Score is: 2