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

Use Case(s)

The ZUNIONSTORE command in Redis is used to aggregate sorted sets into a new sorted set. Common use cases include:

  • Combining scores from different game levels or sessions into a single leaderboard.
  • Aggregating statistics from multiple sources, where each source contributes a sorted set of values.
  • Creating weighted search results where different aspects (like user rating and relevancy score) are stored in separate sorted sets.

Code Examples

Basic Usage of ZUNIONSTORE

This example demonstrates how to combine two sorted sets into a new set, summing up their scores:

const redis = require('redis'); const client = redis.createClient(); client.zadd('set1', 1, 'a', 2, 'b', () => { client.zadd('set2', 1, 'b', 2, 'c', () => { client.zunionstore('out', 2, 'set1', 'set2', 'AGGREGATE', 'SUM', (err, response) => { console.log('Number of elements in the resulting set:', response); client.zrange('out', 0, -1, 'WITHSCORES', (err, result) => { console.log('Resulting set:', result); }); }); }); });

Weighted Union of Sorted Sets

In this example, different weights are assigned to each input set before aggregating them using ZUNIONSTORE:

const client = redis.createClient(); client.zadd('scores2019', 50, 'Alice', 70, 'Bob', () => { client.zadd('scores2020', 80, 'Alice', 60, 'Bob', () => { client.zunionstore('weighted_scores', 2, 'scores2019', 'scores2020', 'WEIGHTS', 0.5, 1.5, 'AGGREGATE', 'SUM', (err, response) => { console.log('Number of elements in the weighted score set:', response); client.zrange('weighted200', 0, -1, 'WITHSCORES', (err, result) => { console.log('Weighted scores:', result); }); }); }); });

Best Practices

  • Ensure that all input keys exist and contain valid sorted sets to avoid unexpected empty results.
  • Consider memory implications when creating large result sets, as ZUNIONSTORE writes a new sorted set into the database.

Common Mistakes

  • Not specifying aggregation method when different behaviors are expected. Default is sum, but min or max can also be specified.
  • Incorrectly configuring weights for the sorted sets, which could lead to improper score calculations.

FAQs

Q: What happens if one of the sorted sets does not exist? A: Redis treats non-existing keys as empty sets. If all inputs are nonexistent, the resulting sorted set will be empty.

Q: Can I use ZUNIONSTORE with more than two sets? A: Yes, ZUNIONSTORE can combine any number of sorted sets as specified by the first argument after the destination key.

Was this content helpful?

Start building today

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