Decrement score in Redis or remove if 0

2019-07-03 11:32发布

问题:

How can I decrement score of one Redis element by 1 in sorted set or remove it if it's value is 0? Currently I am using $redis.zincrby user_cart, -1, params[:product_id] (Rails 4.1.4), but I get negative values.

Thanks in advance!

回答1:

ZINCRBY's reply is the new score so you can check it and issue a ZREM if it is < 1.



回答2:

You can write a LUA script that does it on the Redis server side. You can use this one:

local ans = redis.call('ZINCRBY', KEYS[1], ARGV[1], ARGV[2])
if   tonumber(ans) < 1 then
    redis.call('ZREM', KEYS[1], ARGV[2]) 
end
return (tonumber(ans) < 1 and '-1' or ans)

On any deletion it will return -1 otherwise it will return the new member score.

Here's a sinnpet from a test run:

evalsha 6e8a61a2367772383f535587ce75e92d4e047fcf 1 myzset 3 blah
"3"
zrank myzset blah
(integer) 0
evalsha 6e8a61a2367772383f535587ce75e92d4e047fcf 1 myzset -3 blah
"-1"
zrank myzset blah
(nil)
evalsha 6e8a61a2367772383f535587ce75e92d4e047fcf 1 myzset -3 blah
"-1"
zrank myzset blah
(nil)


标签: redis