【Redis】使用 - zset

Posted by 西维蜀黍 on 2023-02-01, Last Modified on 2024-09-18

Add

ZADD

# Adds members with the given scores to the ZSET
ZADD key-name score member [score member …]

Get

ZRANGE(increasing order of the scores, by index)

ZRANGE is a Redis command used to retrieve a range of elements from a sorted set, sorted by their score. You can specify the start and end positions of the elements you want to retrieve.

# Returns the members and optionally the scores for the members with ranks between start (inclusive) and stop (inclusive)
# start: The starting index (0 for the first element (smallest element), -1 for the last element (largest element)).
#	stop: The stopping index (inclusive).
ZRANGE key-name start stop [WITHSCORES]

# Get all elements
ZRANGE leaderboard 0 -1 WITHSCORES
 1) "player5"
 2) "60"
 3) "player4"
 4) "70"
 5) "player3"
 6) "85"
 7) "player2"
 8) "95"
 9) "player1"
10) "100"

# get the top lowest 3 players (by rank)
ZRANGE leaderboard 0 2
1) "player5"
2) "player4"
3) "player3"

ZREVRANGE (decreasing order of the scores)

"player1": 100
"player2": 95
"player3": 85
"player4": 70
"player5": 60

ZREVRANGE leaderboard 0 2
1) "player1"
2) "player2"
3) "player3"

ZRangeByScore (increasing order of the scores, by score)

The ZRANGEBYSCORE command in Redis is used to retrieve elements from a sorted set based on their score range, rather than their rank (like ZRANGE). You can specify a minimum and maximum score to filter elements in that range.

ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]


"player1": 100
"player2": 95
"player3": 85
"player4": 70
"player5": 60

ZRANGEBYSCORE leaderboard 70 100
1) "player4"
2) "player3"
3) "player2"
4) "player1"

// limit the number of elements returned by specifying the LIMIT option. For example, to get only 2 players starting from the first one with a score between 70 and 100:
ZRANGEBYSCORE leaderboard 70 100 LIMIT 0 2
1) "player4"
2) "player3"

Remove

ZREM

ZREM key-name member

ZREMRANGEBYRANK

# Removes the items from the ZSET with ranks between start and stop
ZREMRANGEBYRANK key-name start stop

ZREMRANGEBYSCORE

# Removes the items from the ZSET with scores between min (inclusive) and max (inclusive)
ZREMRANGEBYSCORE key-name min max

Demo

  1. 添加成员到 ZSET:

    ZADD myzset 1 "one"
    ZADD myzset 2 "two"
    ZADD myzset 3 "three"
    ZADD myzset 4 "four"
    
  2. 查看 ZSET 的成员:

    ZRANGE myzset 0 -1 WITHSCORES
    

    输出:

    1) "one"
    2) "1"
    3) "two"
    4) "2"
    5) "three"
    6) "3"
    7) "four"
    8) "4"
    
  3. 删除分数在 2 到 3 之间的成员:

    ZREMRANGEBYSCORE myzset 2 3
    
  4. 再次查看 ZSET 的成员:

    ZRANGE myzset 0 -1 WITHSCORES
    

    输出:

    1) "one"
    2) "1"
    3) "four"
    4) "4"
    

以上示例展示了如何使用 ZREMRANGEBYSCORE 命令从 Redis 的 ZSET 中根据分数范围删除成员。

为 ZSET的key设置过期时间

在 Redis 中,你不能直接为 zset 中某个member 设置过期时间。但可以为一个 zset 设置过期时间,但这是针对整个键的,而不是键中的某个元素。你可以使用 EXPIREPEXPIRE 命令来设置键的过期时间。

EXPIRE myzset 3600

Reference