0
0
Redisquery~5 mins

Lua script syntax in Redis

Choose your learning style9 modes available
Introduction
Lua scripts in Redis let you run multiple commands together safely and quickly without interruptions.
You want to update several keys in Redis at once without other commands interfering.
You need to perform a calculation or check before changing data in Redis.
You want to reduce the number of round trips between your app and Redis server.
You want to ensure a group of commands run as a single atomic operation.
You want to reuse a small program inside Redis for common tasks.
Syntax
Redis
EVAL script numkeys key [key ...] arg [arg ...]
script is the Lua code you want to run, given as a string.
numkeys tells Redis how many keys you pass next, so it knows which arguments are keys.
Examples
This script gets the value of 'mykey' from Redis.
Redis
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
This script sets 'mykey' to 'newvalue' and then returns the new value.
Redis
EVAL "redis.call('SET', KEYS[1], ARGV[1]); return redis.call('GET', KEYS[1])" 1 mykey newvalue
This script increments the 'counter' key by 1 and returns the new count.
Redis
EVAL "local val = redis.call('INCR', KEYS[1]); return val" 1 counter
Sample Program
This script checks if the key 'greeting' exists. If not, it sets it to 'Hello' and returns 'Hello'. If it exists, it returns the current value.
Redis
EVAL "local current = redis.call('GET', KEYS[1]); if not current then redis.call('SET', KEYS[1], ARGV[1]); return ARGV[1] else return current end" 1 greeting Hello
OutputSuccess
Important Notes
KEYS array holds the keys passed after numkeys; ARGV array holds the other arguments.
Lua scripts run atomically in Redis, so no other commands run during the script.
Keep scripts short and simple to avoid blocking Redis for too long.
Summary
Lua scripts let you run multiple Redis commands together safely and quickly.
Use EVAL with your Lua code, number of keys, keys, and arguments.
Scripts can read and write keys, and return results.