gpt4 book ai didi

redis - Redis ZADD:仅在分数较低时更新

转载 作者:行者123 更新时间:2023-12-03 06:40:08 34 4
gpt4 key购买 nike

我需要为添加到集合中的每个键存储最低的分数,但是当我执行ZADD时,即使分数更高,Redis也会用新值覆盖分数。

ZADD myorderset 1 'one' 2 'two' 3 'three'
(integer) 3

ZRANGE myorderset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "two"
4) "2"
5) "three"
6) "3"

ZADD myorderset 5 'three'
(integer) 0

ZRANGE myorderset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "two"
4) "2"
5) "three"
6) "5"
在示例情况下,我不需要更新键“三”,因为新分数比现有分数(3)高(5)。有没有办法在本地执行此操作,还是需要在Lua中创建脚本?
我一直在研究 ZADD修饰符 (XX, NX, CH),但是它们都不满足我的需要。
非常感谢你!

最佳答案

针对此CAS用例的Lua脚本将是最简单且惯用的解决方案:

127.0.0.1:6379> ZADD myorderset 1 'one' 2 'two' 3 'three'
(integer) 3
127.0.0.1:6379> EVAL "local s = redis.call('ZSCORE', KEYS[1], ARGV[2]) if not s or s > ARGV[1] then redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2]) end" 1 myorderset 5 'three'
(nil)
127.0.0.1:6379> ZRANGE myorderset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "two"
4) "2"
5) "three"
6) "3"
127.0.0.1:6379> EVAL "local s = redis.call('ZSCORE', KEYS[1], ARGV[2]) if not s or s > ARGV[1] then redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2]) end" 1 myorderset 2 'three'
(nil)
127.0.0.1:6379> ZRANGE myorderset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "three"
4) "2"
5) "two"
6) "2"

关于redis - Redis ZADD:仅在分数较低时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63354160/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com