本文内容为 http://redis.io/commands/zunionstore 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]

计算由给定键指定的 numkeys 个有序集合的并集(Union),然后将结果存储在键 destination 中。

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.

默认的,一个元素的最终分值(Score)为所有存在该元素的有序集合中对应分值的总和(Sum)

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

使用 WEIGHTS 选项时,可以为各个有序集合输入指定一个乘法系数(Multiplication factor )。这意味着在将每个有序集合输入中的每个元素的分值传递给聚合函数(Aggregation function)之前,会将该分值乘以对应的系数。当未给定 WEIGHTS 选项时,乘法系数默认为 1

Using the WEIGHTS option, it is possible to specify a multiplication factor for each input sorted set. This means that the score of every element in every input sorted set is multiplied by this factor before being passed to the aggregation function. When WEIGHTS is not given, the multiplication factors default to 1.

使用 AGGREGATE 选项时,可以指定并集运算结果的聚合方式。该选项默认值为 SUM,即将输入中所有存在该元素的集合中对应的分值全部加一起。当选项被设置为 MIN 或 MAX 任意值时,结果集合将保存输入中所有存在该元素的集合中对应的分值的最小或最大值。

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.

如果目标键 destination 已经存在,将会被覆盖。

If destination already exists, it is overwritten.
  • 返回键 destination 对应的有序集合中元素的个数。

    The number of elements in the resulting sorted set at destination.
  • redis> ZADD zset1 1 "one"
    (integer) 1
    redis> ZADD zset1 2 "two"
    (integer) 1
    redis> ZADD zset2 1 "one"
    (integer) 1
    redis> ZADD zset2 2 "two"
    (integer) 1
    redis> ZADD zset2 3 "three"
    (integer) 1
    redis> ZUNIONSTORE out 2 zset1 zset2 WEIGHTS 2 3
    (integer) 3
    redis> ZRANGE out 0 -1 WITHSCORES
    1) "one"
    2) "5"
    3) "three"
    4) "9"
    5) "two"
    6) "10"
  • 版本支持

    2.0.0+

    时间复杂度(Time complexity)

    最坏情况为 O(N*K)+O(M*log(M)) 。

    O(N*K)+O(M*log(M)) worst case with N being the smallest input sorted set, K being the number of input sorted sets and M being the number of elements in the resulting sorted set.