In Redis,How to fetch all member having score less than x ? And what will be time complexity of doing that task?
You can use the ZRANGEBYSCORE redis command.
e.g. the members with score less than 4
zadd myset 1 "one"
zadd myset 2 "two"
zadd myset 3 "three"
zadd myset 5 "five"
zadd myset 6 "six"
ZRANGEBYSCORE myset -inf 4
result:
1) "one"
2) "two"
3) "three"
also for score greater than 4
ZRANGEBYSCORE myset 4 +inf
result:
1) "five"
2) "six"
About the complexity, due to the redis documentation it is O(log(N)+M)
EDIT: 2nd example
Let's say that we have a scoreboard of an online game, which we store in a sorted set in redis. The following command creates this test
zadd scoreboard 101 "John" 333 "Mary" 323 "Nick" 900 "Steve" 901 "Sam" 333 "Mike"
The players that qualify to the next round are the ones with the score less than 330. To find these players we run the following command.
ZRANGEBYSCORE scoreboard -inf 330
which will result to 2 players (John and Nick)
1) "John"
2) "Nick"
To explain a bit further this command: ZRANGEBYSCORE: the redis command, check the documentation scoreboard: the sorted-set that I created -inf: is the minimum price of my command 330: the maximum price of my command
What it does is to find all members in this range from -infinite to 330, which I understand as all the members from 330 and below.
I hope that I helped :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With