node_redis get zrange withscores

th0rv picture th0rv · Jun 11, 2014 · Viewed 10.6k times · Source

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.

Answer

Chhavi Gangwal picture Chhavi Gangwal · Jun 12, 2014

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();