Redis 排序集合并

标签 redis

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/

相关文章:

redis - 在 Redis 中,所有哈希键都存储在同一个 "table"中吗?如果是这样,它如何影响性能?

python - celery 没有同时执行任务

java - 如何在 Android Studio 上安装生菜库?

caching - Redis 哨兵故障转移不起作用

node.js - 带有 Redis 消息队列的 NodeJS - 如何设置多个消费者(线程)

redis - Redis 如何检查一个元素是否是集合的成员?

python flask : How add requests to a queue and rearrange the tasks in queue before executing

ruby-on-rails - 多线程环境下Redis连接(Unicorn)

node.js - 使用 Azure Redis 缓存存储 Node JS 快速 session

session - 错误 : non-declaration statement outside function body on redisstor