ZRANGEBYSCORE && ZREVRANGEBYSCOR

2020-04-21  本文已影响0人  NotFoundW

ZRANGEBYSCORE && ZREVRANGEBYSCORE

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
上一篇下一篇

猜你喜欢

热点阅读