Reputation: 11
I use Redis. I want to delete a key key1 if it has the value value1. I have find this command :
DEL key1
but not :
DEL key1 value1
Upvotes: 1
Views: 2935
Reputation: 13234
Redis doesn't have an atomic command for this, but you can build it yourself.
The simplest case would be to GET
followed by DEL
, but it introduces a race condition if another connection changes key1
between the two commands:
GET key1
# then, if it matches the value you care about:
DEL key1
If you can use Lua scripting, then you can do it in one Redis command:
EVAL "if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('del', KEYS[1]) end" 1 key1 value1
If you can't use Lua scripting, then you can use transactions, but it will take multiple commands:
WATCH key1
GET key1
# if the value matches (the EXEC call will fail if anything changed key1):
MULTI
DEL key1
EXEC
# if it doesn't:
UNWATCH key1
Upvotes: 1