Execute Custom Scripts
Valkey scripting allows you to execute Lua code directly on the Valkey server. This guide will go over executing custom Lua scripts with GLIDE.
Prerequisites
Section titled “Prerequisites”- Running Valkey server (standalone or cluster)
- GLIDE installed.
Execute a Custom Script
Section titled “Execute a Custom Script”The following steps shows how to run a simple a custom Lua script using GLIDE.
-
Define the lua script
lua = """server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])""" -
Create a
Scriptobject with the Lua codescript = Script(lua) -
Execute script with keys and arguments
keys = ["username"]args = ["John Doe"]result = await client.invoke_script(script, keys=keys, args=args)print(result) # b'username: John Doe'
Full Example
import asynciofrom glide import Script, GlideClient, GlideClientConfiguration, NodeAddress
async def main(): config = GlideClientConfiguration(addresses=[NodeAddress("localhost", 6379)]) client = await GlideClient.create(config)
lua = """ server.call('SET', KEYS[1], ARGV[1]) return KEYS[1] .. ': ' .. server.call('GET', KEYS[1]) """
script = Script(lua)
keys = ["username"] args = ["John Doe"] result = await client.invoke_script(script, keys=keys, args=args) print(result)
if __name__ == "__main__": asyncio.run(main())-
Define the lua script
String lua = """server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])"""; -
Create a
Scriptobject with the Lua codeScript script = new Script(lua, false); -
Execute script with keys and arguments
String[] keys = {"username"};String[] args = {"John Doe"};Object result = client.invokeScript(script,ScriptOptions.builder().key(keys[0]).arg(args[0]).build()).get();System.out.println(result); // username: John Doe
Full Example
import glide.api.GlideClient;import glide.api.models.configuration.GlideClientConfiguration;import glide.api.models.configuration.NodeAddress;import glide.api.models.Script;import glide.api.models.commands.ScriptOptions;
public class Example { public static void main(String[] args) { GlideClientConfiguration config = GlideClientConfiguration.builder() .address(NodeAddress.builder() .host("localhost") .port(6379) .build()) .build();
try (GlideClient client = GlideClient.createClient(config).get()) { String lua = """ server.call('SET', KEYS[1], ARGV[1]) return KEYS[1] .. ': ' .. server.call('GET', KEYS[1]) """;
Script script = new Script(lua, false);
Object result = client.invokeScript(script, ScriptOptions.builder() .key("username") .arg("John Doe") .build()).get(); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } }}-
Define the lua script
const lua = `server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])`; -
Create a
Scriptobject with the Lua codeconst script = new Script(lua); -
Execute script with keys and arguments
const keys = ["username"];const args = ["John Doe"];const result = await client.invokeScript(script, {keys, args});console.log(result); // username: John Doe
Full Example
import {GlideClient, Script} from "@valkey/valkey-glide";
async function main() { const client = await GlideClient.createClient({ addresses: [{host: "localhost", port: 6379}] });
const lua = ` server.call('SET', KEYS[1], ARGV[1]) return KEYS[1] .. ': ' .. server.call('GET', KEYS[1]) `;
const script = new Script(lua);
const keys = ["username"]; const args = ["John Doe"]; const result = await client.invokeScript(script, {keys, args}); console.log(result);
client.close();}
main();-
Define the lua script
lua := `server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])` -
Create a
Scriptobject with the Lua codescript := options.NewScript(lua) -
Execute script with keys and arguments
scriptOptions := options.NewScriptOptions().WithKeys([]string{"username"}).WithArgs([]string{"John Doe"})result, err := client.InvokeScriptWithOptions(ctx, *script, *scriptOptions)if err != nil {// handle error}fmt.Println(result) // username: John Doe
Full Example
package main
import ( "context" "fmt" glide "github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config" "github.com/valkey-io/valkey-glide/go/v2/options")
func main() { ctx := context.Background() myConfig := config.NewClientConfiguration(). WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})
client, err := glide.NewClient(myConfig) if err != nil { panic(err) } defer client.Close()
lua := ` server.call('SET', KEYS[1], ARGV[1]) return KEYS[1] .. ': ' .. server.call('GET', KEYS[1]) `
script := options.NewScript(lua)
scriptOptions := options.NewScriptOptions(). WithKeys([]string{"username"}). WithArgs([]string{"John Doe"}) result, err := client.InvokeScriptWithOptions(ctx, *script, *scriptOptions) if err != nil { panic(err) } fmt.Println(result)}-
Define the lua script
var lua = @"server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])"; -
Create a
Scriptobject with the Lua codeusing var script = new Script(lua); -
Execute script with keys and arguments
var options = new ScriptOptions().WithKeys("username").WithArgs("John Doe");var result = await client.ScriptInvokeAsync(script, options);Console.WriteLine(result); // username: John Doe
Full Example
using Valkey.Glide;using static Valkey.Glide.ConnectionConfiguration;
var config = new StandaloneClientConfigurationBuilder() .WithAddress("localhost", 6379) .Build();await using var client = await GlideClient.CreateClient(config);
var lua = @"server.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. server.call('GET', KEYS[1])";
using var script = new Script(lua);
var options = new ScriptOptions() .WithKeys("username") .WithArgs("John Doe");var result = await client.ScriptInvokeAsync(script, options);Console.WriteLine(result);Using eval()
Section titled “Using eval()”-
Define the lua script
$lua = <<<'LUA'redis.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. redis.call('GET', KEYS[1])LUA; -
Execute script with keys and arguments
$result = $client->eval($lua,['username', 'John Doe'], // keys and args combined1 // num_keys - how many arguments are keys);echo $result; // username: John Doe
Using evalSha() for Better Performance
Section titled “Using evalSha() for Better Performance”For scripts executed multiple times, use evalsha() to avoid sending the script body repeatedly:
-
Load the script and get its SHA1 hash
$lua = <<<'LUA'redis.call('SET', KEYS[1], ARGV[1])return KEYS[1] .. ': ' .. redis.call('GET', KEYS[1])LUA;$sha = hash('sha1', $lua);// Or use SCRIPT LOAD to ensure it's cached on server -
Execute using the SHA1 hash
$result = $client->evalsha($sha,['username', 'John Doe'],1 // num_keys);echo $result; // username: John Doe
What’s Next
Section titled “What’s Next”See our documentations for more on how GLIDE support scripting.