Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis get key or set to default if none exists

Tags:

redis

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.

like image 272
23tux Avatar asked Jan 06 '23 02:01

23tux


1 Answers

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
like image 180
Duru Can Celasun Avatar answered Jan 11 '23 10:01

Duru Can Celasun