ZUNIONSTORE

ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight
  [weight ...]] [AGGREGATE <SUM | MIN | MAX | COUNT>]
Available since:
Redis Open Source 2.0.0
Time complexity:
O(N)+O(M log(M)) with N being the sum of the sizes of the input sorted sets, and M being the number of elements in the resulting sorted set.
ACL categories:
@write, @sortedset, @slow,
Compatibility:
Redis Software and Redis Cloud compatibility
Note:
This command's behavior varies in clustered Redis environments. See the multi-key operations page for more information.

Computes the union of numkeys sorted sets given by the specified keys, and stores the result in destination. It is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments.

By default, the resulting score of an element is the sum of its scores in the sorted sets where it exists.

Using the WEIGHTS option, it is possible to specify a multiplication factor for each input sorted set. Each element's score is multiplied by its corresponding weight before aggregation. When WEIGHTS is not given, the multiplication factors default to 1.

With the AGGREGATE option, it is possible to specify how the results of the union are aggregated. This option defaults to SUM, where the score of an element is summed across the inputs where it exists. When this option is set to either MIN or MAX, the resulting set will contain the minimum or maximum score of an element across the inputs where it exists. For SUM, MIN, and MAX, each element's score is multiplied by its corresponding weight before aggregation.

When AGGREGATE COUNT is specified, the original element scores are ignored entirely. The resulting score for each element is determined by which input sets contain it, optionally scaled by WEIGHTS:

  • Without WEIGHTS, each input set containing the element contributes 1 to its score — effectively counting set membership.
  • With WEIGHTS, each input set containing the element contributes its corresponding weight, so the score becomes the sum of those weights.

This enables a common use case: counting set membership frequency directly at the command level, without application-side workarounds.

If destination already exists, it is overwritten.

Examples

ZADD zset1 1 "one" ZADD zset1 2 "two" ZADD zset2 1 "one" ZADD zset2 2 "two" ZADD zset2 3 "three" ZUNIONSTORE out 2 zset1 zset2 WEIGHTS 2 3 ZRANGE out 0 -1 WITHSCORES

Redis Software and Redis Cloud compatibility

Redis
Software
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

Integer reply: the number of elements in the resulting sorted set.

History

  • Starting with Redis version 8.8.0: Added COUNT aggregate option.
RATE THIS PAGE
Back to top ↑