3

目前我正在尝试更新排序集成员。查看文档,ZADD如果成员的分数已经存在,则 using 似乎应该更新成员。但是,在使用此代码尝试更新成员时,

db.zadd("users", parseInt(key, 10) + 1, JSON.stringify(newData));

....即使分数已经存在,也会添加一个新条目!如何使用 redis 更新排序集成员?

4

3 回答 3

7

只要条目之间的键和成员匹配,ZADD 就会替换旧成员的分数:

redis localhost:6379> ZADD test-key 40 blah
(integer) 1
redis localhost:6379> ZRANGE test-key 0 -1 WITHSCORES
1) "blah"
2) "40"
redis localhost:6379> ZADD test-key 45 blah
(integer) 0
redis localhost:6379> ZRANGE test-key 0 -1 WITHSCORES
1) "blah"
2) "45"

也许您在 ZADD 命令之间使用了不同的键或成员?

于 2013-09-05T00:18:43.433 回答
2

@Eli 已经解释了如何更新元素分数,现在zadd添加了 @ZettaCircl 解释的新选项,我正在解释如何使用 score 和 element 示例更新元素

  1. NX = 添加新元素
  2. XX = 更新元素

将三个国家添加到排序集中

 127.0.0.1:6379> zadd country nx 1 'pakistan' // nx = add new element
(integer) 1
127.0.0.1:6379> zadd country nx 2 'turkey'
(integer) 1
127.0.0.1:6379> zadd country nx 3 'UK'
(integer) 1

获取有分数的国家

127.0.0.1:6379> zrange country 0 10 withscores
1) "pakistan"
2) "1"
3) "turkey"
4) "2"
5) "UK"
6) "3"

更新国家

使用分数将国家巴基斯坦(元素)更新为新名称

127.0.0.1:6379> zadd country xx ch 1 'islamic republic of pakistan'
(integer) 0 // 0 means not updated

使用元素名称('pakistan')更新巴基斯坦的国家分数

127.0.0.1:6379> zadd country xx ch 4 'pakistan'
(integer) 1 // updated successfully 

获取有分数的国家

我们可以在这里看到我们只更新了分数。

127.0.0.1:6379> zrange country 0 10 withscores
1) "turkey"
2) "2"
3) "UK"
4) "3"
5) "pakistan"
6) "4" // score updated

结论

我们只能使用元素名称更新排序集中的分数。


我们如何更新元素

首先,我们需要删除国家 paksitan。

127.0.0.1:6379> zrem country pakistan
(integer) 1 // removed successfully

获取有分数的国家

127.0.0.1:6379> zrange country 0 10 withscores
1) "turkey"
2) "2"
3) "UK"
4) "3"

用新名称添加巴基斯坦

使用新名称和以前的分数将新元素添加到国家排序集中

127.0.0.1:6379> zadd country nx 1 'islamic republic of pakistan'
(integer) 1

获取有分数的国家

127.0.0.1:6379> zrange country 0 10 withscores
1) "islamic republic of pakistan"
2) "1"
3) "turkey"
4) "2"
5) "UK"
6) "3"

结论

首先我们需要删除元素,然后将新元素添加到排序集中。

于 2020-06-07T08:36:11.400 回答
1

自您 2013 年的回答以来,文档似乎发生了变化。

ZADD options (Redis 3.0.2 or greater)
ZADD supports a list of options, specified after the name of the key and before the first score argument. Options are:

XX: Only update elements that already exist. Never add elements.
NX: Don't update already existing elements. Always add new elements.
CH: Modify the return value from the number of new elements added, to the total number of elements changed (CH is an abbreviation of changed). Changed elements are new elements added and elements already existing for which the score was updated. So elements specified in the command line having the same score as they had in the past are not counted. Note: normally the return value of ZADD only counts the number of new elements added.
INCR: When this option is specified ZADD acts like ZINCRBY. Only one score-element pair can be specified in this mode.

来自https://redis.io/commands/zadd

所以现在,您可以了解 ZADD 的预期行为。鉴于您的回答,选项 XX 可以完成工作。所以像:

db.zadd("users", XX, parseInt(key, 10) + 1, JSON.stringify(newData));
于 2019-06-12T06:06:16.737 回答