1

Redis 太棒了!

如果我有 2 个排序集,例如 - “set1 = key1:100, key2:200, key3:300”

另一个像“set2 = key1:1, key2:2, key3:3”

那么是否有可能得到这样的 - set3 = key1:100_1, key2:200_2, key3:300_3

我不想添加相同键的值或取相同键的最小值/最大值。是否有可能将这些值放在一起?我想为同一个键将这两个值放在一起。

4

1 回答 1

1

排序集中的分数必须是数值,因此不可能在交集/并集操作中返回分数的简单串联。

但是,如果您可以将每个集合的分数值绑定到给定范围,则可以使用 SUM 运算通过简单的算术将两个值编码为单个值。

例子:

# For s1, we assume the score is between 0 and 999
> zadd s1 100 key1 200 key2 300 key3
(integer) 3
# For s2, we assume the score is between 0 and 99
> zadd s2 1 key1 2 key2 3 key3
(integer) 3

# Get the intersection, dividing the s2 score by 100
> zinterstore s3 2 s1 s2 WEIGHTS 1 0.01
(integer) 3

# Get the result with scores
> zrange s3 0 -1 withscores
1) "key1"
2) "100.01000000000001"
3) "key2"
4) "200.02000000000001"
5) "key3"
6) "300.02999999999997"

在结果分数中,整数部分包含来自 s1 的分数,小数部分包含来自 s2 的分数。

请注意分数是双浮点数。它有一些后果:

  • 如果您仅操作整数(即 0.0299999... 实际上是 0.03),您可能必须正确舍入它

  • 将两个数值合二为一意味着精度除以 2(仅 16 位到 8 位)。它可能适合也可能不适合您的需求。

于 2013-04-02T07:47:36.953 回答