How to Use EVALSHA in Redis: Syntax and Examples
Use
EVALSHA in Redis to run a Lua script by providing its SHA1 hash instead of the full script text. This speeds up execution by caching the script on the server. You call EVALSHA <sha1> <numkeys> <key1> ... <arg1> ... to run the cached script with keys and arguments.Syntax
The EVALSHA command runs a Lua script cached on the Redis server using its SHA1 hash. It requires the script's SHA1 hash, the number of keys the script will access, followed by the keys and any additional arguments.
- sha1: The SHA1 hash of the Lua script.
- numkeys: Number of keys the script will use.
- key1, key2, ...: The keys the script will access.
- arg1, arg2, ...: Additional arguments passed to the script.
plaintext
EVALSHA <sha1> <numkeys> <key1> [key2 ...] [arg1 arg2 ...]
Example
This example shows how to load a Lua script, get its SHA1 hash, and then run it with EVALSHA. The script increments a key's value by a given amount.
redis
127.0.0.1:6379> SCRIPT LOAD "return redis.call('INCRBY', KEYS[1], ARGV[1])" "e0e1f7a9b6a1f2d3c4b5a6d7e8f9a0b1c2d3e4f5" 127.0.0.1:6379> EVALSHA e0e1f7a9b6a1f2d3c4b5a6d7e8f9a0b1c2d3e4f5 1 mycounter 5 (integer) 5 127.0.0.1:6379> EVALSHA e0e1f7a9b6a1f2d3c4b5a6d7e8f9a0b1c2d3e4f5 1 mycounter 3 (integer) 8
Output
(integer) 5
(integer) 8
Common Pitfalls
Common mistakes when using EVALSHA include:
- Using a SHA1 hash that is not loaded on the server, causing a
NOSCRIPTerror. - Incorrectly counting the number of keys in
numkeys. - Passing keys and arguments in the wrong order.
Always load the script first with SCRIPT LOAD or fallback to EVAL if NOSCRIPT occurs.
redis
127.0.0.1:6379> EVALSHA deadbeef 1 mykey 1 (error) NOSCRIPT No matching script. Please use EVAL. -- Correct approach: 127.0.0.1:6379> SCRIPT LOAD "return redis.call('INCRBY', KEYS[1], ARGV[1])" "e0e1f7a9b6a1f2d3c4b5a6d7e8f9a0b1c2d3e4f5" 127.0.0.1:6379> EVALSHA e0e1f7a9b6a1f2d3c4b5a6d7e8f9a0b1c2d3e4f5 1 mykey 1 (integer) 1
Output
(error) NOSCRIPT No matching script. Please use EVAL.
(integer) 1
Quick Reference
| Command | Description |
|---|---|
| SCRIPT LOAD | Loads a Lua script and returns its SHA1 hash. |
| EVALSHA | Runs a cached Lua script by SHA1 hash. |
| EVAL |