Is there a command in redis where I can set a default value for a key if it does not exist?
For example if get hello
returns (nil)
I would like to default it to world
. But if the key hello
already exists, I would like to return this value.
You can do it with a Lua script:
local value = redis.call("GET", KEYS[1])
if (not value) then
redis.call("SET", KEYS[1], ARGV[1])
return ARGV[1]
end
return value
Save this as script.lua
and call it like this:
$ redis-cli eval "$(cat script.lua") 1 myKey defaultValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With