李东勇
李东勇

Reputation: 220

In redis, how do I delete one key and get its value at the same time

In redis, how do I delete one key and get its value at the same time, and, most important, it is executed in one command so it is thread safe.

Upvotes: 9

Views: 11958

Answers (3)

Ali Rn
Ali Rn

Reputation: 1214

Since Redis 6.2.0 you can use GETDEL command:

Get the value of the key and delete the key. This command is similar to GET, except it also deletes the key on success (if and only if the key's value type is a string).

Reference

Upvotes: 1

mmx
mmx

Reputation: 121

Update 2021: as of redis v 6.2.0, you can use GETDEL

Upvotes: 12

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

There's no single command. You can either write a Lua script or execute a transaction. A transaction would simply look like:

127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> GET foo
QUEUED
127.0.0.1:6379> DEL foo
QUEUED
127.0.0.1:6379> EXEC
1) "bar"
2) (integer) 1

Using a Lua script

127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> EVAL "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x" 1 foo
"bar"
127.0.0.1:6379> GET foo
(nil)

Both operate the same, but with Lua script, the script can be cached and there's no need to repeat the whole code the next time you want to call it. We can use SCRIPT LOAD that caches the scripts and returns a unique id of it to be used as a function name for subsequent calls (Most clients abstract this transparently) e.g.

127.0.0.1:6379> SCRIPT LOAD "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x"
"89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7"

127.0.0.1:6379> SET foo bar
OK

# Now we use the returned SHA of the script to call it without parsing it again:
127.0.0.1:6379> EVALSHA 89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7 1 foo
"bar"

Upvotes: 8

Related Questions