Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

redis

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

like image 741
李东勇 Avatar asked Dec 05 '17 08:12

李东勇


2 Answers

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

like image 75
mmx Avatar answered Oct 04 '22 20:10

mmx


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"
like image 27
Not_a_Golfer Avatar answered Oct 04 '22 19:10

Not_a_Golfer