I need to store the lowest score for each key I add to the set, but when I do ZADD
, Redis overwrites the score with the new value even if the score is higher.
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"
In the example case, I need the key ‘three’ not be updated since the new score is higher (5) than the existing (3). Is there a way to do this natively or do I need to create a script in Lua?
I’ve been researching ZADD
modifiers (XX, NX, CH)
but none of them do what I need.
Thank you very much!
2
Answers
There is no single command or command option to do it both. You can either use combination of
ZSCORE
withZADD
(in lua). Alternatively("It is/looks like over-engineered") you may useZUNIONSTORE
with theaggregate
optionMIN
.If you prefer,
new
set name with random string in application levelEXPIRE
to this new set, no need toDEL
the new key manually after theZUNIONSTORE
, it will be expired eventually.MULTI
/EXEC
in a single transaction.A Lua script for this CAS use case would be the simplest and idiomatic solution: