首页 > 代码库 > Sorted sets

Sorted sets

Redis in Action JOSIAH L. CARLSON MANNING Shelter Island

ZSETs offer the ability to store a mapping of members to scores (similar to the keys and values  of HASHes).  These  mappings  allow  us  to  manipulate  the  numeric  scores, and fetch and scan over both members and scores based on the sorted order of the scores.
In chapter 1, we showed a brief example that used ZSETs as a way of sorting submitted articles based on time and how many up-votes they had received, and in chapter 2, we had an example that used ZSETs as a way of handling the expiration of old cookies. In this section, we’ll talk about commands that operate on ZSETs. You’ll learn how to  add  and  update  items  in ZSETs,  as  well  as  how  to  use  the ZSET  intersection  and union commands. When finished with this section, you’ll have a much clearer under-standing about how ZSETs work, which will help you to better understand what we did with them in chapter 1, and how we’ll use them in chapters 5, 6, and 7.

conn.zadd(‘zset-key‘, ‘a‘, 3, ‘b‘, 2, ‘c‘, 1);//ZADD key-name score member [score member ...]—Adds members with the given scores to the ZSETconn.zcard(‘zset-key‘);//ZCARD key-name—Returns the number of members in the ZSET -->Knowing how large a ZSET is can tell us in some cases if it’s necessary to trim our ZSETconn.zincrby(‘zset-key‘, ‘c‘, 3);//ZINCRBY key-name increment member—Increments the member in the ZSETconn.zscore(‘zset-key‘, ‘b‘);//ZSCORE key-name member—Returns the score of the member in the ZSET --->Fetching scores of individual members can be useful if we’ve been keeping counters or toplistsconn.zrank(‘zset-key‘, ‘c‘);//ZRANK key-name member—Returns the position of the given member in the ZSETconn.zcount(‘zset-key‘, 0, 3);//ZCOUNT key-name min max—Returns the number of members with scores between the provided minimum and maximum -->Counting the number of itemswith a given range of scores canbe quite useful for some tasksconn.zrem(‘zset-key‘, ‘b‘);//ZREM key-name member [member ...]—Removes the members from the ZSET, returning the number of members that were removed --->Removing membersis as easy as adding themconn.zrange(‘zset-key‘, 0, -1, withscore=True);//ZRANGE key-name start stop [WITHSCORES]—Returns the members and optionally the scores for the members with ranks between start and stop --->For debugging, we usually fetch theentire ZSET with this ZRANGE call, but real use caseswill usually fetch items a relatively small group at a time

 

Sorted sets