Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis sorted set with multiple score "columns"

Tags:

redis

I have a need for a leaderboard where users are stored with a score AND a percentage of level completeness. I only need to be able to sort by score and get ranks by score.

Using Redis' sorted sets a can easily store users' scores like so:

ZADD leaderboard:gamemode1 100 user1
ZADD leaderboard:gamemode1 300 user2

however, I am struggelig to figure out, how to best store the percentage values belonging to the scores of 100 and 300.

Should I do something like this:

ZADD leaderboard:gamemode1 100 user1:29.45

where the :29.45 is the percentage for user1's score of 100 in gamemode1? I think this will make it complicated to update user1's score for gamemode1 later.

Or should I instead create a hashtable as a book-keeping mechanism, that stores all users' scores and percentages for all gamemodes?

My concern about the hashtable approach is, that if I want to show a leaderboard of ~50 users with their score and percentage values, I will then have to query that hashtable 50 times to get the percentages, after pulling the top50 scores with ZRANGE.

Does anyone have any input on how to construct this in a good way?

like image 735
acrmuui Avatar asked Jan 11 '23 18:01

acrmuui


1 Answers

When working with Sorted Sets, keep in mind that it has member string unicity.

That means:

ZADD game1 100 user1
ZADD game1 90 user1

Leaves you with only 90 user1.

Just a heads-up, I think you've covered that.

For storing the percentage, you could use the decimal part of the score:

ZADD leaderboard:gamemode1 100.0995 user1
ZADD leaderboard:gamemode1  90.0850 user2

Above, I use the decimal part for the percentage like this: 0.0995 = 99.5%.

You can also use the score for score only, and serialize the member string:

ZADD leaderboard:gamemode1 100 [serialized dictionary/dataset]
ZADD leaderboard:gamemode1  90 [serialized dictionary/dataset]

If you use JSON or MsgPack, you can always use server-side scripting to update some data within the serialized string.

I would not recommend bookkeeping for this simple scenario, at least not at this stage. You can always implement that when needed.

Hope this helps, TW

like image 182
Tw Bert Avatar answered Jan 31 '23 08:01

Tw Bert