Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Redis ZRANGE in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

The ZRANGE command in Redis is used for retrieving a range of members in a sorted set stored at a specified key, ordered by the scores from the lowest to the highest. Common use cases include:

Code Examples

Basic Usage of ZRANGE

In this example, we retrieve members from a sorted set between index ranges 0 and -1, which represents all members from start to finish.

const redis = require('redis');
const client = redis.createClient();

client.zrange('mySortedSet', 0, -1, (err, members) => {
  if (err) throw err;
  console.log(members); // Logs all members in the sorted set
});

Using ZRANGE with Scores

To also fetch the scores along with the members, you can use the 'WITHSCORES' option:

const client = redis.createClient();

client.zrange('mySortedSet', 0, -1, 'WITHSCORES', (err, members) => {
  if (err) throw err;
  for (let i = 0; i < members.length; i += 2) {
    console.log(`Member: ${members[i]}, Score: ${members[i+1]}`);
  }
});

This will output each member along with their corresponding score, useful for applications where you need both the member and their rank/score.

Best Practices

Common Mistakes

FAQs

Can I use ZRANGE to get elements in descending order?

No, for descending order you should use the ZREVRANGE command. ZRANGE always returns elements in ascending order of scores.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost