woutr_be woutr_be - 1 month ago 25
Node.js Question

Redis, sorted set with pagination

I currently have the following data structure in Redis

client.hmset('user:' + user.id, 'id', user.id, 'user', JSON.stringify(meta));
client.zadd(['user:user_by_created_time', meta.created_time, 'user:' + user.id]);
client.zadd(['user:user_by_age', meta.age, 'user:' + user.id]);

I then when to get the first 10 users sorted by age, when there are more than 10, I should be able to pass an
that allows me to use pagination.

What I currently have is the following

client.zrangebyscore(['user:user_by_age', '-inf', '+inf'], (err, results) => {
const multi = client.multi();
results.forEach(result => {

multi.exec((err, results) => { ... });

I'm a bit stuck on how to continue with this, I know it's possible to sort a list, but I can't figure out how to only get 10 users after a specific offset.

I'm using the Node Redis client: https://github.com/NodeRedis/node_redis


To paginate with sorted sets use ZRANGE, not ZRANGEBYSCORE. The arguments are the ranks, so to get the first 10 users you use ZRANGE user:user_by_age 0 9, to get the next 10 you use ZRANGE user:user_by_age 10 19, etc.