REDIS/jedis 更新排序集中所有成员的分数

标签 redis sortedset jedis batch-updates

在 REDIS 中递增中型排序集的最佳方法是什么? (最好使用 java 驱动程序 JEDIS)Set 中有大约 100-200K 条记录。我想将他们的分数增加一个给定的双数。

之前

1 a
2 b
3 c

之后(增加 1)

2 a
3 b
4 c

我想到的唯一可能的解决方案是:

  1. 通过网络获取所有排序集(比如 A)内容。 (REDIS -> 应用程序)。
  2. 创建一个管道,在循环中使用 ZADD 或 ZINCRBY 在同一个 setA 中递增它们
  3. 然后执行流水线。

还有其他/更好的方法吗?

更新

下面是如何在 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/

相关文章:

amazon-web-services - 如何备份 AWS Elasticache Redis 数据?

graph - Redis:实现加权有向图

c# - 获取 null 作为整数类型的默认值

redis - 使用 Redis-Cli 了解延迟

amazon-web-services - Flask-Session Redis 连接到 AWS 上的错误主机?

node.js - 在 nodejs 上循环 redis 返回的 promise

java - Spring Data Redis - 存储日期时出现问题

java - NoSuchMethodError : org. springframework.data.repository.config.RepositoryConfigurationSource.getAttribute 错误

redis - Spring Data 对 Redis BRPOPLPUSH 的支持

node.js - 为什么连接到集群在 IoRedis 中不断循环?