在 REDIS 中递增中型排序集的最佳方法是什么? (最好使用 java 驱动程序 JEDIS)Set 中有大约 100-200K 条记录。我想将他们的分数增加一个给定的双数。
之前
1 a
2 b
3 c
之后(增加 1)
2 a
3 b
4 c
我想到的唯一可能的解决方案是:
- 通过网络获取所有排序集(比如 A)内容。 (REDIS -> 应用程序)。
- 创建一个管道,在循环中使用 ZADD 或 ZINCRBY 在同一个 setA 中递增它们
- 然后执行流水线。
还有其他/更好的方法吗?
更新
下面是如何在 REDIS 中使用 EVAL 和 Lua 执行 for 循环来递增所有排序集成员。
local members = redis.call('zrange',KEYS[1],0,-1)
for i, member in ipairs(members) do
redis.call('zincrby',KEYS[1],inc,member)
end
将其保存到字符串中并使用您的驱动程序(在本例中为 java)运行 eval。执行不返回任何内容。
使用绝地武士
// script is the script string
// 1 is the number of keys- keep it this way for this script
// myzset is the name of your sorted set
// 1.5 is the increment, you can use +/- values to inc/dec.
jedis.eval(script, 1, "myzset", "1.5");
最佳答案
客户端和redis之间的通信可能会花费很多时间。为避免这种情况,您可以获取已排序集合的“SET 类型”副本。例如,假设您有一个排序集“key1”:
1 a
2 b
3 c
你有一组“key2”:
a, b, c
你可以轻松实现增量:
def increase_sorted_set(increment = 1)
redis.ZINTERSTORE("key1", 2, "key1", "key2", "WEIGHTS", "1", increment)
end
Redis 将为(未排序的)集合 key2
的每个成员提供默认分数 1
。
例如:
redis 127.0.0.1:6379> ZADD key1 1 a 2 b 3 c
(integer) 3
redis 127.0.0.1:6379> SADD key2 a b c
(integer) 3
redis 127.0.0.1:6379> ZINTERSTORE key1 2 key1 key2 WEIGHTS 1 7
(integer) 3
redis 127.0.0.1:6379> ZRANGE key1 0 -1 WITHSCORES
1) "a"
2) "8"
3) "b"
4) "9"
5) "c"
6) "10"
关于REDIS/jedis 更新排序集中所有成员的分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15002081/