Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node_redis get zrange withscores

Does anybody know how can I get members with scores by node redis? I tried something like this:

client.ZRANGE(key, 0, -1, withscores, function(err, replies) {

});

Thanks.

like image 315
th0rv Avatar asked Jun 11 '14 08:06

th0rv


2 Answers

This code looks good. Check out the following link for retrieving what you want :

http://ricochen.wordpress.com/2012/02/28/example-sorted-set-functions-with-node-js-redis/

Added the code here from that link example in case it is ever removed.

var rc=require('redis').createClient();
var _=require('underscore');

rc.zincrby('myset', 1, 'usera');
rc.zincrby('myset', 5, 'userb');
rc.zincrby('myset', 3, 'userc');
rc.zrevrange('myset', 0, -1, 'withscores', function(err, members) {
        // the resulting members would be something like
        // ['userb', '5', 'userc', '3', 'usera', '1']
        // use the following trick to convert to
        // [ [ 'userb', '5' ], [ 'userc', '3' ], [ 'usera', '1' ] ]
        // learned the trick from
        // http://stackoverflow.com/questions/8566667/split-javascript-array-in-chunks-using-underscore-js
    var lists=_.groupBy(members, function(a,b) {
        return Math.floor(b/2);
    });
    console.log( _.toArray(lists) );
});
rc.quit();
like image 142
Chhavi Gangwal Avatar answered Sep 21 '22 12:09

Chhavi Gangwal


Seems your code is right. The following is the syntax to get zrange.

without score:

redisClient.zrange(keyName,start,stop,function(err,result){
   //result is array
   // every index will give you member name
})

Ex :

redisClient.zrange("mySortedset",-1,-1,function(err,result){
       //result is array
       // every index will give you member name
})

with score:

redisClient.zrange(keyName,start,stop,'withscores',function(err,result){
   //result is array
   // here even index will hold member
   // odd index will hold its score
})

Ex :

redisClient.zrange("mySortedset",-1,-1,'withscores',function(err,result){
   //result is array
   // here even index will hold member
   // odd index will hold its score
})
like image 42
jerry Avatar answered Sep 19 '22 12:09

jerry