The ranking function is a very common demand. Using the ordered set feature in Redis to implement rankings is a good and fast choice.
General rankings are effective, such as "User Points List". If there is no effectiveness and the ranking is always based on the overall ranking, there may always be a few old users at the top of the list. For new users, that is really frustrating.
First, let’s take a “today’s points list”. The sorting rule is from most to least new points added by users today.
Then when the user adds points, he or she will operate an ordered collection that records the increase in points on that day.
Suppose today is April 1, 2015, and the user with UID 1 has gained 5 points due to a certain operation.
The Redis command is as follows:
ZINCRBY rank:20150401 5 1
Assume that several other users have also added points:
ZINCRBY rank:20150401 1 2ZINCRBY rank:20150401 10 3
Look at the data in the current ordered set rank:20150401 (The withscores parameter can be used to obtain the score of the element):
ZRANGE rank:20150401 0 -1 withscores1) "2"2) "1"3) "1"4) "5"5) "3"6) "10"
#p#Paging title#e#
According to the score from high to low, get the top10:
ZREVRANGE rank:20150401 0 9 withscores1) "3"2) "10"3) "1"4) "5"5) "2" 6) "1"
Since there are only three elements, these data are queried.
If the points ranking list of the day is recorded every day, then other lists with various tricks will be simple.
For example, "yesterday's standings":
ZREVRANGE rank:20150331 0 9 withscores
Use union to achieve the sum of points for multiple days to achieve "last week's standings":
ZUNIONSTORE rank:last_week 7 rank:20150323 rank:20150324 rank:20150325 rank:20150326 rank:20150327 rank:20150328 rank:20150329 WEIGHTS 1 1 1 1 1 1 1
In this way, the points records of 7 days are merged into the ordered set rank:last_week. Weight factor WEIGHTS If not given, the default is 1. In order not to hide the details, I wrote them out deliberately.
Then the information for querying the Top 10 in last week's standings is:
ZREVRANGE rank:last_week 0 9 withscores#p#Paging title#e#
"Monthly list", "Quarterly list", "Annual list", etc. can be deduced in this way.
The following is a simple implementation of the PHP version. Using Redis relies on the PHP extension PhpRedis, and the code also relies on the Carbon library for processing time. The amount of code is very small, so I won’t comment.
<?php namespace BlogRedis; use Redis; use CarbonCarbon;class Ranks { const PREFIX = 'rank:'; protected $redis = null; public function __construct(Redis $redis) { $this->redis = $redis; } public function addScores($member, $scores) { $key = self::PREFIX . date('Ymd'); return $this->redis->zIncrBy($key, $scores, $member); } protected function getOneDayRankings($date, $start, $stop) { $key = self::PREFIX . $date; return $this->redis->zRevRange($key, $start, $stop, true);