Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis zrange and zrangebyscore

Tags:

redis

Are these 2 Redis commands different, except for the second having optional LIMIT argument? http://redis.io/commands/zrange http://redis.io/commands/zrangebyscore

like image 807
user1756971 Avatar asked Jan 22 '14 20:01

user1756971


People also ask

What is Zrange in Redis?

Redis ZRANGE command returns the specified range of elements in the sorted set stored at the key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with an equal score.

How do you find the intersection of two sets in Redis?

Redis ZINTERSTORE command computes the intersection of numkeys sorted sets given by the specified keys, and stores the result in the destination. It is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments.

What is ZSET in Redis?

ZSET is a short name for Redis Sorted Set, a Redis data type documented here. Each key in a sorted set has multiple values inside, associated with a floating value score.

How do I create a sorted set in Redis?

To create a sorted set, use the zadd command. zadd accepts as arguments the name of the key that will hold the sorted set, followed by the score of the member you're adding and the value of the member itself.


2 Answers

They are different:

  • ZRANGE key start stop ...: start and stop are zero-based indexes (i.e they correspond to a position of an element within the sorted set),
  • ZRANGEBYSCORE key min max ...: min and max refer to scores (i.e they are used to specify a score range).

So, the first one operates by indexes while the second one (as its name implies) operates by scores. Thus they are used for different purposes.

like image 162
deltheil Avatar answered Oct 04 '22 01:10

deltheil


say, the sorted set is:

value score
tom 0
bob 1
alice 100
lucy 102

when you use zrangebyscores, and the max score is 2, the min score is 0, then, you will get tom and bob;

when you use zrange, and the start is 0, the stop is 2, then you will get tom, bob and alice.

127.0.0.1:6379> zadd example 0 tom 1 bob 100 alice 102 lucy
127.0.0.1:6379> zrange example 0 2 WITHSCORES
1) "tom"
2) "0"
3) "bob"
4) "1"
5) "alice"
6) "100"
127.0.0.1:6379> zrangebyscore example 0 2 WITHSCORES
1) "tom"
2) "0"
3) "bob"
4) "1"

this is the key difference.

like image 37
Kingname Avatar answered Oct 04 '22 02:10

Kingname