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
我不想添加相同键的值或取相同键的最小值/最大值。 是否有可能将这些值放在一起? 我想为同一个键将这两个值放在一起。
最佳答案
排序集中的分数必须是数值,因此不可能在交集/联合操作中返回分数的简单串联。
但是,如果您可以将每个集合的分数值限制在给定范围内,则可以使用 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 的分数。
请注意分数是 double float 。它有一些后果:
如果您只操作整数(即 0.0299999... 实际上是 0.03),您可能需要对其进行适当的舍入
将两个数值编码为一个意味着精度除以 2(仅限 16 位数字到 8 位数字)。它可能适合也可能不适合您的需求。
关于Redis 排序集合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15756629/