Saturday 11 April 2015

Redis sorted sets

Sortedset is a set which maintaince order. Every element in a sorted set is associated with a floating point value, called the score, Elements in sortedset are ordered by this score value.

1. If A and B are two elements with a different score, then A > B if A.score is > B.score.
2. If A and B have exactly the same score, then A > B if the A string is lexicographically greater than the B string.

ZADD command is used to add elements to sorted set.

Syntax
ZADD key score1 member1 score2 member2 ... scoreN memberN

127.0.0.1:6379> zadd krishna 97 Mathematics 86 Physics 94 Chemistry 40 English 
(integer) 4 
127.0.0.1:6379>
127.0.0.1:6379> zrange krishna 0 3 
1) "English" 
2) "Physics" 
3) "Chemistry" 
4) "Mathematics" 
127.0.0.1:6379> 
127.0.0.1:6379> zrevrange krishna 0 3 
1) "Mathematics" 
2) "Chemistry" 
3) "Physics" 
4) "English" 


Above snippet stores krishna's marks in different subjects. “zrange”command returns the specified range of elements in the sorted set stored at key. The elements are ordered from the lowest to the highest score. “zrevrange” command returns the specified range of elements in the sorted set stored at key. The elements are ordered from the highest to the lowest score.

Use “withscore” to reurn data with scores.

127.0.0.1:6379> zrange krishna 0 3 withscores 
1) "English" 
2) "40" 
3) "Physics" 
4) "86" 
5) "Chemistry" 
6) "94" 
7) "Mathematics" 
8) "97" 

127.0.0.1:6379> zrevrange krishna 0 3 withscores 
1) "Mathematics" 
2) "97" 
3) "Chemistry" 
4) "94" 
5) "Physics" 
6) "86" 
7) "English" 
8) "40" 



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment