Home  >  Article  >  Database  >  How to use Redis to implement the ranking function

How to use Redis to implement the ranking function

藏色散人
藏色散人forward
2020-08-13 11:45:244480browse

The following column Redis Tutorial will introduce to you how to use Redis to implement the ranking function. I hope it will be helpful to friends in need!

How to use Redis to implement the ranking function

The ranking function is a very common demand. Using the features of ordered sets 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 of all, 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 will operate an ordered set 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 2
ZINCRBY rank:20150401 10 3

Look at the data in the current ordered set rank:20150401 (the withscores parameter can be attached Get the score of the element):

ZRANGE rank:20150401 0 -1 withscores
1) "2"
2) "1"
3) "1"
4) "5"
5) "3"
6) "10"

According to the score from high to low, get the top10:

ZREVRANGE rank:20150401 0 9 withscores
1) "3"
2) "10"
3) "1"
4) "5"
5) "2"
6) "1"

Because 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 many tricks will be simple.
For example, "yesterday's standings":

ZREVRANGE rank:20150331 0 9 withscores

Use the 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 of 7 days are recorded 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 querying the top 10 information of last week's standings is:

ZREVRANGE rank:last_week  0 9 withscores

"Monthly List", "Quarterly List", "Annual List" and so on.

The above is the detailed content of How to use Redis to implement the ranking function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete