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

Use Case(s)

The ZRANGEBYSCORE command in Redis is used to retrieve a range of members in a sorted set stored at a specific key, where the members have scores within a given range. This is particularly useful in applications that require leaderboard functionality, time-series data filtering based on scores, or any scenario where data needs to be retrieved based on score criteria.

Code Examples

Example 1: Basic Usage of zrangebyscore

This example demonstrates how to retrieve members with scores between 10 and 20 from a sorted set:

const redis = require('redis'); const client = redis.createClient(); client.on('error', (err) => console.log('Redis Client Error', err)); client.connect(); async function getScoresInRange() { const scores = await client.zRangeByScore('mySortedSet', 10, 20); console.log(scores); // Output might be ['member1', 'member2'] } getScoresInRange();

Example 2: Using WITHSCORES Option

In this example, we fetch members and their scores from the sorted set using the WITHSCORES option, which is useful for displaying both member names and their corresponding scores:

async function getScoresAndMembersInRange() { const scores = await client.zRangeByScore('mySortedSet', 5, 15, { WITHSCORES: true }); console.log(scores); // Output might be ['member3', '12', 'member4', '14'] } getScoresAndMembersInRange();

Best Practices

  • Connection Management: Always handle Redis client connections carefully. Close the connection when it's no longer needed.
  • Error Handling: Implement error handling for your Redis operations to manage any failures or exceptions gracefully.

Common Mistakes

  • Ignoring Promises: When using node_redis with async functions, ensure that you handle the promises correctly either using await or .then() method to prevent unhandled promise rejections.
  • Score Precision: Ensure that the score values are precise and consistent as floating point precision issues can lead to unexpected results.

FAQs

What does the WITHSCORES option do in ZRANGEBYSCORE?

It modifies the command to return both the elements and their scores, instead of just the elements. Each element’s score follows its respective member name in the list returned.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.