Use Cases for Redis' “Score” and “Ranking” Fea

2019-08-29 04:18发布

问题:

What are some use cases for Redis' "score" and "ranking" features for sets (outside of the typical "leaderboard" examples for games? I'm trying to figure out how to make use of these dynamic new features as I anticipate moving from using a traditional relational database to Redis as a persistent data store.

回答1:

ZSETs are great for selections or ranges based on scores, but scores can be any numerical value, like a timestamp.

We store daily stock prices for all US stocks in redis. Here's an example for ebay...

ZADD key score member [score member ...] 
...
ZADD stocks:ebay 1 30.39 2 32.70 3 31.25 4 31.75 5 29.12 6 29.87 7 29.93

The score values in this case would normally be long timestamps, with that aside, if we want daily prices for the last 3 days, we simply convert two dates to timestamps and pull from redis using the timestamp range 1 3...

zrangebyscore stocks:ebay 1 3

1) "30.39"
2) "32.70"
3) "31.25"

The query is very fast and works well for our needs.

Hope it helps!



回答2:

zset is the only type of key who can be sorted

by example you can imagine puts all comments key id of a specific article in a zset, users will vote up/down each comments and this will change the score value

after that when you need to draw comments you can get them ordered, better comments in first place (like here)

using ZREMRANGEBYSCORE you can imagine delete all pretty bad comments each days

but as each redis type, they still basic, give you a dedicated use case is hard there can be some :- )



标签: redis