Andre
Andre

Reputation: 1

Redis: paginated ordered zrank fetch of a member in multiple sorted sets

New to Redis. Need some help.

USE CASE: I have thousands of leaderboards. They have usernames in them with appropriate scores. A user can belong to 1 or more leaderboards. I need an efficient way to get the rank of every leaderboard a particular user belongs to, preferrably sorted by rank and with pagination. Typical user will belong to hundreds of leaderboards.

AS FAR AS I GOT: I keep a set for each user containing boards he belongs to. To get a user's ranks I get his set of boards then zrank each board in the set and then order it by rank in my code. This seems very inefficient and does not support pagination.

I have been reading and brainstorming and I am stuck. What I need is something like:

user1:boards (a,c,e)
board:a (user1,user23,user5)
board:b (user2,user7,user12)
board:c (user2,user1,user42)
board:d (user36,user4,user9)
board:e (user6,user19,user1)

SORT user1:boards BY board:*->user1

Similar to sorting by hash fields except -> in this case means the sorted set score of the member provided. Would there be any performance improvement if such a feature existed? Or would it be the same as pipelining all the zranks?

Thanks.

Upvotes: 0

Views: 404

Answers (1)

DhruvPathak
DhruvPathak

Reputation: 43235

To make your reads efficient, you just have to make a minor change to your writes. Currently you are storing user boards in a set, store them in a sorted set instead. Lets call it user_boards_sorted_set. So whenever you increase the score of a user 1 in a leaderboard sorted set (board1 for example) , you run a zrank for user 1 on board1, and that rank becomes score for the user1 in user_boards_sorted_set. This way user_boards_sorted_set always contains all the boards the user belongs to, and the scores against each entry contain his rank in that particular leaderboard.Run a ZRANGE on user_boards_sorted_set and you will have the user and his ranks in all the leaderboards sorted by rank.

UPDATE : Based on feedbacks in the comments, and an incorrect assumption made in the above answer .

Another good way would be to use Lua scripting to get individual board rankings by doing ZRANK on all the boards that the user belongs to, and sorting it in LUA itself. This will give significant performance gain as all the ZRANKS and then sorting are done on server side itself, and reduces network transfers.

Upvotes: 1

Related Questions