How to Use SCRIPT LOAD in Redis: Syntax and Examples
Use
SCRIPT LOAD in Redis to load a Lua script into the server's script cache and get its SHA1 hash. This hash can then be used with EVALSHA to run the script efficiently without sending the full script every time.Syntax
The SCRIPT LOAD command loads a Lua script into Redis's script cache and returns its SHA1 hash. This hash uniquely identifies the script and can be used to execute it later with EVALSHA.
Syntax:
SCRIPT LOAD <script>
Where:
<script>is the Lua script code as a string.
redis
SCRIPT LOAD "return redis.call('PING')"Output
"e0e1f1d7a6a1b2c3d4e5f67890123456789abcd1"
Example
This example shows how to load a simple Lua script that returns the string 'Hello, Redis!' and then execute it using the returned SHA1 hash.
redis
127.0.0.1:6379> SCRIPT LOAD "return 'Hello, Redis!'" "3f0a1b2c3d4e5f67890123456789abcdef123456" 127.0.0.1:6379> EVALSHA 3f0a1b2c3d4e5f67890123456789abcdef123456 0 "Hello, Redis!"
Output
"Hello, Redis!"
Common Pitfalls
Common mistakes when using SCRIPT LOAD include:
- Not using the returned SHA1 hash with
EVALSHA, causing errors. - Modifying the script after loading it without reloading, which leads to mismatched hashes.
- Trying to run
EVALSHAwith a SHA1 hash that was never loaded, resulting in aNOSCRIPTerror.
Always ensure the script is loaded and the correct SHA1 hash is used for execution.
redis
127.0.0.1:6379> EVALSHA deadbeefdeadbeefdeadbeefdeadbeefdeadbeef 0 (error) NOSCRIPT No matching script. Please use SCRIPT LOAD.
Output
(error) NOSCRIPT No matching script. Please use SCRIPT LOAD.
Quick Reference
| Command | Description |
|---|---|
| SCRIPT LOAD | Loads a Lua script into Redis and returns its SHA1 hash. |
| EVALSHA | Executes a cached script by its SHA1 hash. |
| SCRIPT EXISTS | Checks if scripts exist in the cache by SHA1 hashes. |
| SCRIPT FLUSH | Removes all scripts from the script cache. |
Key Takeaways
SCRIPT LOAD stores a Lua script in Redis and returns its SHA1 hash for later use.
Use the returned SHA1 hash with EVALSHA to run the script efficiently.
If EVALSHA is called with an unknown hash, Redis returns a NOSCRIPT error.
Always reload the script if you change its content to get a new SHA1 hash.
SCRIPT LOAD helps reduce network overhead by avoiding sending full scripts repeatedly.