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

Use Case(s)

The ZUNION command in Redis is used to aggregate sorted sets stored in the database. Common use cases include:

  • Combining multiple leaderboards into a single leaderboard.
  • Aggregating scores from different categories.
  • Merging temporal data entries from various time-series data.

Code Examples

Example 1: Basic Usage of ZUNION

This example demonstrates how to combine two sorted sets using ZUNION in Node.js with the node_redis library.

const redis = require('redis'); const client = redis.createClient(); // Assuming sorted sets 'key1' and 'key2' already exist client.zunionstore('out', 2, 'key1', 'key2', (err, res) => { if (err) throw err; console.log('Number of elements in the resulting set:', res); // Fetching and displaying the combined set client.zrange('out', 0, -1, 'WITHSCORES', (err, result) => { if (err) throw err; console.log('Combined Set:', result); }); });

In this code, zunionstore is used to store the result of the union into a new key 'out'. The parameters 2, 'key1', and 'key2' specify the number of keys to union and their names.

Example 2: Using Weights with ZUNION

Weights can be applied to give different importance to each set in the union.

const redis = require('redis'); const client = redis.createClient(); client.zunionstore('weighted_out', 2, 'key1', 'key2', 'WEIGHTS', 1, 3, (err, res) => { if (err) throw err; console.log('Number of elements in the weighted set:', res); // Displaying the weighted combined set client.zrange('weighted_out', 0, -1, 'WITHSCORES', (err, result) => { if (err) throw err; console.log('Weighted Combined Set:', result); }); });

Here, weights of 1 and 3 are assigned to key1 and key2 respectively, altering the score calculation in the resulting set.

Best Practices

  • Always handle errors properly to avoid unhandled exceptions.
  • When using weights, ensure they align with your application logic to prevent skewed results.

Common Mistakes

  • Not checking if the input sorted sets exist or are non-empty can lead to unexpected results or empty outputs.
  • Forgetting to handle callback errors which might lead to silent failures in your application workflow.


Q: Can ZUNION store the result in one of the source sets? A: Yes, the destination in ZUNIONSTORE can be one of the input sets, effectively updating it with the union result.

Q: How does ZUNION handle duplicate elements across sets? A: ZUNION aggregates scores of duplicate elements, so if an element exists in multiple sets, its scores from all sets are summed up.

Was this content helpful?

Start building today

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