### Full Example: Execute Custom Script in Go Source: https://glide.valkey.io/how-to/execute-custom-scripts A complete Go example demonstrating client setup, context, script definition, and execution. ```go 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 { ``` -------------------------------- ### Full Example: Execute Custom Script in Python Source: https://glide.valkey.io/how-to/execute-custom-scripts A complete Python example demonstrating client setup, script definition, and execution. ```python import asyncio from 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()) ``` -------------------------------- ### Full Example: Execute Custom Script in Java Source: https://glide.valkey.io/how-to/execute-custom-scripts A complete Java example demonstrating client setup, script definition, and execution within a try-with-resources block. ```java 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(); } } } ``` -------------------------------- ### Install Valkey GLIDE for Go Source: https://glide.valkey.io/how-to/installation Use 'go get' to install the Valkey GLIDE Go library. ```go go get github.com/valkey-io/valkey-glide/go/v2 ``` -------------------------------- ### Example: Get and Check Subscriptions Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Example of how to retrieve the current subscription state and check desired and actual subscriptions for exact channels. ```java // Get current subscription state PubSubState state = client.getSubscriptions().get(); // Check desired subscriptions Set desiredChannels = state.getDesiredSubscriptions() .getOrDefault(PubSubChannelMode.EXACT, Set.of()); System.out.println("Desired channels: " + desiredChannels); // Check actual subscriptions Set actualChannels = state.getActualSubscriptions() .getOrDefault(PubSubChannelMode.EXACT, Set.of()); ``` -------------------------------- ### Glide Cluster Client Setup Source: https://glide.valkey.io/migration/go/go-redis/connection-setup Provides examples for initializing a Glide cluster client, including basic setup and a comprehensive configuration with TLS, credentials, and advanced settings. ```go import ( "github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config" ) client, err := glide.NewClusterClient(&config.ClusterClientConfiguration{ Addresses: []config.NodeAddress{ {Host: "127.0.0.1", Port: 6379}, {Host: "127.0.0.1", Port: 6380}, }, }) // With options clientWithOptions, err := glide.NewClusterClient(&config.ClusterClientConfiguration{ Addresses: []config.NodeAddress{ {Host: "127.0.0.1", Port: 6379}, {Host: "127.0.0.1", Port: 6380}, }, UseTLS: true, Credentials: &config.ServerCredentials{ Username: "user", Password: "password", }, ReadFrom: config.ReadFromAZAffinity, RequestTimeout: 2000 * time.Millisecond, ConnectionBackoff: &config.ConnectionBackoffStrategy{ NumberOfRetries: 5, Factor: 2, ExponentBase: 2, JitterPercent: 10, }, AdvancedConfiguration: &config.AdvancedClusterClientConfiguration{ ConnectionTimeout: 5000 * time.Millisecond, TLSAdvancedConfiguration: &config.TLSAdvancedConfiguration{ UseInsecureTLS: false, }, }, }) ``` -------------------------------- ### Full Example: Execute Custom Script in Node.js Source: https://glide.valkey.io/how-to/execute-custom-scripts A complete Node.js example demonstrating client setup, script definition, and execution. ```javascript 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(); ``` -------------------------------- ### Full Example: Load and Execute Valkey Function (Python) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete Python example demonstrating the setup of a GlideClient, loading a Lua function to increment and retrieve a visit count, and then executing it. ```python import asyncio from glide import Script, GlideClient, GlideClientConfiguration, NodeAddress async def main(): config = GlideClientConfiguration(addresses=[NodeAddress("localhost", 6379)]) client = await GlideClient.create(config) # lua code that updates a key and returns its new value lua_code = """#!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) """ # loading the function to valkey await client.function_load(lua_code, replace=True) await client.set("page:home:visits", "0") # calling the previously loaded function result = await client.fcall("update_visits", keys=["page:home:visits"]) print(result) # b'1' if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Full Example: Execute Custom Script in C# Source: https://glide.valkey.io/how-to/execute-custom-scripts A complete example demonstrating the setup of a standalone client, definition of a Lua script, creation of a `Script` object, preparation of `ScriptOptions`, and invocation of the script with Valkey GLIDE in C#. ```csharp 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); ``` -------------------------------- ### Connect and Ping in PHP Source: https://glide.valkey.io/getting-started/quickstart Connect to a Valkey server and send a PING command using the PHP client. This example demonstrates basic connection setup, PING command execution, and error handling. ```php // Create ValkeyGlide client $client = new ValkeyGlide(); try { // Connect to Valkey server $client->connect( addresses: [['host' => 'localhost', 'port' => 6379]] ); // Test the connection $response = $client->ping(); // Valkey responds with PONG echo "Connected! Server responded: {$response}\n"; } catch (ValkeyGlideException $e) { echo "Connection failed: {$e->getMessage()}\n"; } finally { // Always close the client $client->close(); } ``` -------------------------------- ### Basic Standalone Example Source: https://glide.valkey.io/languages/nodejs/api/index.html Connect to a standalone Valkey instance and perform basic operations like PING, SET, and GET. Ensure TLS is enabled if your server uses it and consider setting a request timeout. ```javascript import { GlideClient, GlideClusterClient, Logger } from "@valkey/valkey-glide"; // When Valkey is in standalone mode, add address of the primary node, and any replicas you'd like to be able to read from. const addresses = [ { host: "localhost", port: 6379, }, ]; // Check `GlideClientConfiguration/GlideClusterClientConfiguration` for additional options. const client = await GlideClient.createClient({ addresses: addresses, // if the server uses TLS, you'll need to enable it. Otherwise, the connection attempt will time out silently. // useTLS: true, // It is recommended to set a timeout for your specific use case requestTimeout: 500, // 500ms timeout clientName: "test_standalone_client", }); // The empty array signifies that there are no additional arguments. const pong = await client.customCommand(["PING"]); console.log(pong); const set_response = await client.set("foo", "bar"); console.log(`Set response is = ${set_response}`); const get_response = await client.get("foo"); console.log(`Get response is = ${get_response}`); Copy ``` -------------------------------- ### Complete Pub/Sub Application with Glide Source: https://glide.valkey.io/tutorials/pubsub/pubsub-basics A full Python example demonstrating Glide client configuration for Pub/Sub, publishing a message, and asynchronously receiving it. Includes client setup, message handling, and cleanup. ```python import asyncio from glide import GlideClient, NodeAddress, GlideClientConfiguration async def main(): print("Starting Pub/Sub tutorial...") # 1. Configure the listening client listening_config = GlideClientConfiguration( addresses=[NodeAddress("localhost", 6379)], pubsub_subscriptions=GlideClientConfiguration.PubSubSubscriptions( channels_and_patterns={ # Listens for messages published to 'ch1' and 'ch2' GlideClientConfiguration.PubSubChannelModes.Exact: {"ch1", "ch2"}, # Listens for messages to channels matching 'chat*' GlideClientConfiguration.PubSubChannelModes.Pattern: {"chat*"} }, callback=None, context=None, ) ) # 2. Configure the publishing client publishing_config = GlideClientConfiguration( addresses=[NodeAddress("localhost", 6379)] ) listening_client = None publishing_client = None try: # 3. Create the clients listening_client = await GlideClient.create(listening_config) publishing_client = await GlideClient.create(publishing_config) # 4. Publish a message to 'ch1' print("Publishing message to 'ch1'...") subscribers_count = await publishing_client.publish("Hello from GLIDE!", "ch1") print(f"Message published to {subscribers_count} subscriber(s).") # 5. Receive the message (asynchronously) print("Waiting to receive message...") message = await listening_client.get_pubsub_message() if message: print(f"Received message: '{message.message}' on channel: '{message.channel}'") else: print("No message received.") # 6. Try to get another message (non-blocking) print("Trying to get another message...") message = listening_client.try_get_pubsub_message() if message: print(f"Found another message: '{message.message}'") else: print("No more messages in the buffer. Done.") finally: # 7. Clean up clients if listening_client: await listening_client.close() print("Listening client closed.") if publishing_client: await publishing_client.close() print("Publishing client closed.") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Basic Standalone Client Example Source: https://glide.valkey.io/languages/nodejs/api Connect to a standalone Valkey instance and perform basic operations like PING, SET, and GET. Ensure TLS is enabled if your server uses it and consider setting a request timeout. ```javascript import { GlideClient, GlideClusterClient, Logger } from "@valkey/valkey-glide"; // When Valkey is in standalone mode, add address of the primary node, and any replicas you'd like to be able to read from. const addresses = [ { host: "localhost", port: 6379, }, ]; // Check `GlideClientConfiguration/GlideClusterClientConfiguration` for additional options. const client = await GlideClient.createClient({ addresses: addresses, // if the server uses TLS, you'll need to enable it. Otherwise, the connection attempt will time out silently. // useTLS: true, // It is recommended to set a timeout for your specific use case requestTimeout: 500, // 500ms timeout clientName: "test_standalone_client", }); // The empty array signifies that there are no additional arguments. const pong = await client.customCommand(["PING"]); console.log(pong); const set_response = await client.set("foo", "bar"); console.log(`Set response is = ${set_response}`); const get_response = await client.get("foo"); console.log(`Get response is = ${get_response}`); ``` -------------------------------- ### Full Example (PHP) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete PHP example demonstrating the connection to Valkey, loading a Lua function, and then executing it. ```php $client = new ValkeyGlide(); $client->connect(addresses: [['host' => 'localhost', 'port' => 6379]]); // lua code that updates a key and returns its new value $luaCode = <<<'LUA' #!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) LUA; // loading the function to valkey $client->functionLoad($luaCode, true); $client->set('page:home:visits', '0'); // calling the previously loaded function $result = $client->fcall('update_visits', ['page:home:visits']); echo $result; // 1 ``` -------------------------------- ### Get Limit Offset Source: https://glide.valkey.io/languages/java/api/glide/api/models/commands/RangeOptions.Limit.html Retrieves the offset from the start of the range. This indicates how many elements to skip before starting to include elements in the result. ```java public long getOffset() ``` -------------------------------- ### GlideClusterClient zcard Example Source: https://glide.valkey.io/languages/nodejs/api/classes/GlideClusterClient.GlideClusterClient.html Example usage of the zcard method to get the cardinality of a sorted set. The output indicates the number of elements. ```javascript const result = await client.zcard("my_sorted_set"); console.log(result); // Output: 3 // Indicates that there are 3 elements in the sorted set `my_sorted_set`. ``` -------------------------------- ### Recommended Database Selection Example Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Demonstrates the recommended approach for selecting a database using client configuration, which persists across reconnections. ```java GlideClient client = GlideClient.createClient( GlideClientConfiguration.builder() .address(NodeAddress.builder().host("localhost").port(6379).build()) .databaseId(5) // Recommended: persists across reconnections .build() ).get(); ``` -------------------------------- ### Full Example (C#) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete C# example demonstrating how to connect to Valkey, load a Lua function, and then call it. ```csharp using Valkey.Glide; using static Valkey.Glide.ConnectionConfiguration; var config = new StandaloneClientConfigurationBuilder() .WithAddress("localhost", 6379) .Build(); await using var client = await GlideClient.CreateClient(config); // lua code that updates a key and returns its new value var luaCode = @"#!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) "; // loading the function to valkey await client.FunctionLoadAsync(luaCode, replace: true); await client.StringSetAsync("page:home:visits", "0"); // calling the previously loaded function var result = await client.FCallAsync("update_visits", ["page:home:visits"], []); Console.WriteLine(result); // 1 ``` -------------------------------- ### go-redis Cluster Client Setup Source: https://glide.valkey.io/migration/go/go-redis/connection-setup Illustrates setting up a go-redis cluster client, both with minimal configuration and with added authentication. ```go import ( "github.com/redis/go-redis/v9" ) cluster := redis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"127.0.0.1:6379", "127.0.0.1:6380"}, }) // With options clusterWithOptions := redis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"127.0.0.1:6379", "127.0.0.1:6380"}, Username: "user", Password: "password", }) ``` -------------------------------- ### Full Example (Go) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete Go program demonstrating the definition, loading, and execution of a Valkey Lua function. ```go package main import ( "context" "fmt" glide "github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config" ) 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 code that updates a key and returns its new value luaCode := `#!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) ` // loading the function to valkey _, err = client.FunctionLoad(ctx, luaCode, true) if err != nil { panic(err) } _, err = client.Set(ctx, "page:home:visits", "0") if err != nil { panic(err) } // calling the previously loaded function result, err := client.FCallWithKeysAndArgs(ctx, "update_visits", []string{"page:home:visits"}, []string{}) if err != nil { panic(err) } fmt.Println(result) // 1 } ``` -------------------------------- ### go-redis Standalone Client Setup Source: https://glide.valkey.io/migration/go/go-redis/connection-setup Demonstrates creating a basic standalone Redis client and one with authentication options using go-redis. ```go import ( "context" "github.com/redis/go-redis/v9" ) var ctx = context.Background() // Simple connection rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // With options rdbWithOptions := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Username: "user", Password: "password", }) ``` -------------------------------- ### Example Pipeline Commands Source: https://glide.valkey.io/concepts/client-features/batch-commands Illustrates a pipeline with MGET and SET commands. This example shows the expected output when keys are empty and how reordering might occur if a slot is migrating and a command is retried. ```text MGET key {key}:1 SET key "value" ``` ```text [null, null] OK ``` ```text ["value", null] OK ``` -------------------------------- ### Start Valkey Server with Docker Source: https://glide.valkey.io/tutorials/lua-scripting/lua-scripting-basics Start a standalone Valkey server instance using Docker. This command ensures a Valkey server is running for the tutorial. ```bash docker run -d --name standalone-valkey -p 6379:6379 -d valkey/valkey ``` -------------------------------- ### Get Configuration Parameters with Route Source: https://glide.valkey.io/languages/java/api/glide/api/commands/ServerManagementClusterCommands.html Retrieves configuration parameter values, supporting single-node or multi-node routing. The first example gets 'timeout' from a random node, while the second retrieves 'maxmemory' from all nodes. ```java Map configParams = client.configGet("timeout", RANDOM).get().getSingleValue(); assert configParams.get("timeout").equals("1000"); Map> configParamsPerNode = client.configGet("maxmemory", ALL_NODES).get().getMultiValue(); ``` -------------------------------- ### Example Scenario: MGET and SET Commands Source: https://glide.valkey.io/languages/nodejs/api/interfaces/Commands.ClusterBatchRetryStrategy.html Illustrates a scenario with MGET and SET commands, showing expected responses and potential issues with command reordering due to ASK redirection and retries. ```text MGET key {key}:1 SET key "value" ``` ```text [null, null] OK ``` ```text ["value", null] OK ``` -------------------------------- ### RangeByIndex Methods Source: https://glide.valkey.io/languages/java/api/glide/api/models/commands/RangeOptions.RangeByIndex.html Provides methods to retrieve the start and end indexes of the range, and to get the limit information. ```APIDOC ## RangeByIndex Methods ### Description Provides methods to retrieve the start and end indexes of the range, and to get the limit information. ### Methods * **getStart()** - Returns the start index of the range as a String. * **getEnd()** - Returns the end index of the range as a String. * **getLimit()** - Returns the limit information for the range query. ``` -------------------------------- ### Get Range Source: https://glide.valkey.io/languages/java/api/glide/api/commands/StringBaseCommands.html Returns a sub-string of the string value stored at key, determined by the offsets start and end. ```APIDOC ## Get Range ### Description Returns the sub-string of the string value stored at `key`, determined by the offsets `start` and `end` (both are inclusive). ### Method `CompletableFuture getrange(GlideString key, int start, int end)` `CompletableFuture getrange(String key, int start, int end)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **GlideString/String**: The sub-string of the value. #### Response Example None ``` -------------------------------- ### Redisson ZRANK & ZREVRANK Source: https://glide.valkey.io/migration/java/redisson/command-comparison-redisson-glide Use RScoredSortedSet to get the 0-based rank of a member from the start (rank) or from the end (revRank). ```java RScoredSortedSet sortedSet = redisson.getScoredSortedSet("sortedSet"); sortedSet.add(1.0, "one"); sortedSet.add(2.0, "two"); sortedSet.add(3.0, "three"); Integer rank = sortedSet.rank("two"); // 1 (0-based index) Integer revRank = sortedSet.revRank("two"); // 1 (0-based index from end) ``` -------------------------------- ### configGet Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Gets the values of configuration parameters. Starting from server version 7, the command supports multiple parameters. ```APIDOC ## configGet ### Description Gets the values of configuration parameters. Starting from server version 7, the command supports multiple parameters. ### Method ```java java.util.concurrent.CompletableFuture> ``` ### Parameters #### Path Parameters - **parameters** (java.lang.String[]) - Required - The configuration parameters to retrieve. ``` -------------------------------- ### Install Valkey Go Client Source: https://glide.valkey.io/migration/go/go-redis/installation Use these commands to add the Valkey Go client library to your project and update your dependencies. ```go go get github.com/valkey-io/valkey-glide/go/v2 go mod tidy ``` -------------------------------- ### Read entries from multiple Redis streams Source: https://glide.valkey.io/languages/nodejs/api/classes/GlideClusterClient.GlideClusterClient.html Use `xread` to read entries from one or more streams, starting from a specified entry ID. The example demonstrates reading from two streams, `my_stream` and `writers`, starting from ID `0-0`. ```javascript const streamResults = await client.xread({"my_stream": "0-0", "writers": "0-0"}); console.log(result); // Output: // [ // { // key: "my_stream", // Stream key // value: { // Stream Ids mapped to entries array. // "1526984818136-0": [["duration", "1532"], ["event-id", "5"], ["user-id", "7782813"]], // Each entry is a key/value tuple. // "1526999352406-0": [["duration", "812"], ["event-id", "9"], ["user-id", "388234"]], // } // }, // { // key: "writers", // value: { // "1526985676425-0": [["name", "Virginia"], ["surname", "Woolf"]], // "1526985685298-0": [["name", "Jane"], ["surname", "Austen"]], // } // } // ] ``` -------------------------------- ### Full Example: Connect with Custom Certificate Source: https://glide.valkey.io/tutorials/tls A complete example demonstrating how to load a custom certificate, configure TLS, and establish a connection using `GlideClient`. Includes error handling for file operations and connection attempts. ```python import asyncio from glide import ( GlideClient, GlideClientConfiguration, NodeAddress, TlsAdvancedConfiguration, AdvancedGlideClientConfiguration ) async def main_with_custom_cert(): # Replace with your server's address and TLS port addresses = [NodeAddress(host="your-self-signed-server.example.com", port=6379)] # 1. Load the certificate as bytes cert_file_path = "/path/to/your/ca-cert.pem" try: with open(cert_file_path, "rb") as f: root_cert_bytes = f.read() except FileNotFoundError: print(f"Error: Certificate file not found at {cert_file_path}") return except Exception as e: print(f"Error reading certificate file: {e}") return # 2. Create TLS advanced configuration tls_config = TlsAdvancedConfiguration(root_pem_cacerts=root_cert_bytes) # 3. Create advanced client configuration advanced_config = AdvancedGlideClientConfiguration( tls_config=tls_config ) # 4. Create main client configuration client_config = GlideClientConfiguration( addresses, use_tls=True, # Don't forget this! advanced_configuration=advanced_config ) try: # 5. Create the client client = await GlideClient.create(client_config) response = await client.ping() print(f"Connected successfully with custom cert! Server responded: {response}") except Exception as e: print(f"Failed to connect with custom cert: {e}") finally: if 'client' in locals() and client.is_connected(): await client.close() if __name__ == "__main__": asyncio.run(main_with_custom_cert()) ``` -------------------------------- ### Get Object Length with Glide JSON Source: https://glide.valkey.io/languages/python/api/reference/glide/async_commands/glide_json Use `glide_json.objlen` to get the number of key-value pairs in a JSON object. It supports JSONPath (starting with '$') and legacy paths. Ensure the client and key are correctly set up. The `path` parameter is optional. ```python >>> from glide import glide_json >>> await glide_json.set(client, "doc", "$", '{"a": 1.0, "b": {"a": {"x": 1, "y": 2}, "b": 2.5, "c": true}}') b'OK' # Indicates successful setting of the value at the root path '$' in the key `doc`. >>> await glide_json.objlen(client, "doc", "$") [2] # Returns the number of key-value pairs at the root object, which has 2 keys: 'a' and 'b'. >>> await glide_json.objlen(client, "doc", ".") 2 # Returns the number of key-value pairs for the object matching the path '.', which has 2 keys: 'a' and 'b'. >>> await glide_json.objlen(client, "doc", "$.b") [3] # Returns the length of the object at path '$.b', which has 3 keys: 'a', 'b', and 'c'. >>> await glide_json.objlen(client, "doc", ".b") 3 # Returns the length of the nested object at path '.b', which has 3 keys. >>> await glide_json.objlen(client, "doc", "$..a") [None, 2] ``` -------------------------------- ### Get Substring of String with go-redis Source: https://glide.valkey.io/migration/go/go-redis/command-comparison-chart Retrieves a partial string from a key based on start and end offsets using go-redis. ```go rdb.GetRange(ctx, "key", 0, 3) ``` -------------------------------- ### BaseClientConfiguration Example Source: https://glide.valkey.io/languages/nodejs/api/interfaces/BaseClient.BaseClientConfiguration.html Demonstrates how to configure a Valkey client with various options including addresses, authentication, timeouts, and reconnection strategies. ```typescript const config: BaseClientConfiguration = { addresses: [ { host: 'redis-node-1.example.com', port: 6379 }, { host: 'redis-node-2.example.com' }, // Defaults to port 6379 ], databaseId: 5, // Connect to database 5 useTLS: true, credentials: { username: 'myUser', password: 'myPassword', }, requestTimeout: 5000, // 5 seconds protocol: ProtocolVersion.RESP3, clientName: 'myValkeyClient', readFrom: ReadFrom.AZAffinity, clientAz: 'us-east-1a', defaultDecoder: Decoder.String, inflightRequestsLimit: 1000, connectionBackoff: { numberOfRetries: 10, // Maximum retries before delay becomes constant factor: 500, // Base delay in milliseconds exponentBase: 2, // Delay doubles with each retry (2^N) jitterPercent: 20, // Optional jitter percentage }, lazyConnect: true, }; ``` -------------------------------- ### info Source: https://glide.valkey.io/languages/nodejs/api/classes/Batch.BaseBatch.html Gets information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ```APIDOC ## info ### Description Gets information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ### Method info ### Parameters #### Path Parameters - **sections** (InfoOptions[]) - Optional - A list of InfoOptions values specifying which sections of information to retrieve. When no parameter is provided, Default is assumed. ### Command Response A string containing the information for the sections requested. ### Returns T ### See valkey.io for details. ``` -------------------------------- ### info Source: https://glide.valkey.io/languages/nodejs/api/classes/Batch.ClusterTransaction.html Gets information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ```APIDOC ## info(sections?: InfoOptions[]): ClusterBatch ### Description Gets information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ### Parameters #### Path Parameters * **sections** (InfoOptions[]) - Optional - A list of InfoOptions values specifying which sections of information to retrieve. When no parameter is provided, Default is assumed. ### Returns ClusterBatch Command Response - A string containing the information for the sections requested. ``` -------------------------------- ### getDefaultInstanceForType in RefreshIamToken.Builder Source: https://glide.valkey.io/languages/java/api/command_request/CommandRequestOuterClass.RefreshIamToken.Builder.html Retrieves the default instance of RefreshIamToken for this builder. This is often used to get a base message to start modifications. ```java public CommandRequestOuterClass.RefreshIamToken getDefaultInstanceForType() ``` -------------------------------- ### Full Example: Load and Execute Valkey Function (Java) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete Java example demonstrating the creation of a GlideClient, loading a Lua function to increment and retrieve a visit count, and then executing it. ```java import glide.api.GlideClient; import glide.api.models.configuration.GlideClientConfiguration; import glide.api.models.configuration.NodeAddress; 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()) { // lua code that updates a key and returns its new value String luaCode = "#!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) "; // loading the function to valkey client.functionLoad(luaCode, true).get(); client.set("page:home:visits", "0").get(); // calling the previously loaded function Object result = client.fcall("update_visits", new String[]{"page:home:visits"}, new String[]{}).get(); System.out.println(result); // 1 } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Full Example: Load and Execute Valkey Function (Node.js) Source: https://glide.valkey.io/how-to/load-and-execute-functions A complete Node.js example demonstrating the creation of a GlideClient, loading a Lua function to increment and retrieve a visit count, and then executing it. ```javascript import {GlideClient} from "@valkey/valkey-glide"; async function main() { const client = await GlideClient.createClient({ addresses: [{host: "localhost", port: 6379}] }); // lua code that updates a key and returns its new value const luaCode = `#!lua name=page_visits server.register_function('update_visits', function(visits) server.call('INCR', visits[1]) return server.call('GET', visits[1]) end) `; // loading the function to valkey await client.functionLoad(luaCode, {replace: true}); await client.set("page:home:visits", "0"); // calling the previously loaded function const result = await client.fcall("update_visits", ["page:home:visits"], []); console.log(result); // 1 client.close(); } main(); ``` -------------------------------- ### Jedis Transaction (MULTI/EXEC) Source: https://glide.valkey.io/migration/java/jedis/manual-migrations/command-comparison-jedis-glide Example of starting, adding commands to, and executing a transaction using Jedis. Results are returned as a List. ```java // Start a transaction Transaction transaction = jedis.multi(); // Add commands to the transaction transaction.set("key", "value"); transaction.incr("counter"); transaction.get("key"); // Execute the transaction List result = transaction.exec(); System.out.println(result); // [OK, 1, value] ``` -------------------------------- ### Go Callback Subscription Source: https://glide.valkey.io/how-to/publish-and-subscribe-messages This Go example demonstrates setting up a callback for message subscriptions with Valkey Glide. It includes dynamic subscription, publishing a message, and verifying its receipt. Proper client closing is essential. ```go var received []string var mu sync.Mutex callback := func(message *PubSubMessage, context any) { mu.Lock() received = append(received, message.Message) mu.Unlock() fmt.Printf("Received '%s' on '%s'\n", message.Message, message.Channel) } sConfig := NewStandaloneSubscriptionConfig(). WithCallback(callback, nil) config := NewGlideClientConfiguration(). WithAddress(&NodeAddress{}). WithSubscriptionConfig(sConfig) client, _ := NewGlideClient(config) defer client.Close() // Subscribe dynamically — messages are delivered to the callback ctx := context.Background() _ = client.Subscribe(ctx, []string{"news"}, 5000) // Publish a message (from another client) publisher.Publish("news", "Hello!") time.Sleep(500 * time.Millisecond) // Verify the callback received the message mu.Lock() fmt.Println("Received messages:", received) mu.Unlock() ``` -------------------------------- ### Get First Bit Position with Start Offset Source: https://glide.valkey.io/languages/java/api/glide/api/commands/BitmapBaseCommands.html Retrieves the position of the first bit matching the specified value (0 or 1) within a given range, starting from the specified offset. Offsets can be negative to indicate positions from the end of the string. ```java Long payload = client.bitpos("myKey1", 1, 4).get(); // Indicates that the first occurrence of a 1 bit value starting from fifth byte is the 34th // bit of the binary value of the string stored at "myKey1". assert payload == 33L; ``` ```java Long payload = client.bitpos(gs("myKey1"), 1, 4).get(); // Indicates that the first occurrence of a 1 bit value starting from fifth byte is the 34th // bit of the binary value of the string stored at "myKey1". assert payload == 33L; ``` -------------------------------- ### Get a Substring of a String with Lettuce Source: https://glide.valkey.io/migration/java/lettuce/command-comparison-chart Use getrange() to retrieve a portion of the string value of a key, specified by start and end offsets. ```java syncCommands.getrange("key", 0, 3) ``` -------------------------------- ### Example NodeAddress Configuration Source: https://glide.valkey.io/languages/python/api/reference/glide_shared/config Demonstrates how to specify DNS addresses and ports for cluster nodes. ```python [ NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379), ] ``` -------------------------------- ### Glide Standalone Client Setup Source: https://glide.valkey.io/migration/go/go-redis/connection-setup Shows how to initialize a Glide client for standalone mode with basic and advanced configurations, including TLS, credentials, and timeouts. ```go import ( "context" "github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config" ) var ctx = context.Background() // Simple connection client, err := glide.NewClient(&config.ClientConfiguration{ Addresses: []config.NodeAddress{ {Host: "localhost", Port: 6379}, }, }) // With options clientWithOptions, err := glide.NewClient(&config.ClientConfiguration{ Addresses: []config.NodeAddress{ {Host: "localhost", Port: 6379}, }, UseTLS: true, Credentials: &config.ServerCredentials{ Username: "user", Password: "password", }, ReadFrom: config.ReadFromAZAffinity, RequestTimeout: 2000 * time.Millisecond, ConnectionBackoff: &config.ConnectionBackoffStrategy{ NumberOfRetries: 5, Factor: 2, ExponentBase: 2, JitterPercent: 10, }, AdvancedConfiguration: &config.AdvancedClientConfiguration{ ConnectionTimeout: 5000 * time.Millisecond, TLSAdvancedConfiguration: &config.TLSAdvancedConfiguration{ UseInsecureTLS: false, }, }, DatabaseId: 0, }) ``` -------------------------------- ### Get Configuration Parameters Source: https://glide.valkey.io/languages/java/api/glide/api/models/BaseBatch.html Reads the configuration parameters of the running server. Supports multiple parameters starting from server version 7. ```java public T configGet(@NonNull @NonNull ArgType[] parameters) ``` -------------------------------- ### Get Configuration Parameters Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Retrieves the values of specified configuration parameters. Supports multiple parameters starting from server version 7. ```java java.util.concurrent.CompletableFuture> configGet​(@NonNull java.lang.String[] parameters) ``` -------------------------------- ### BaseClient Initialization Source: https://glide.valkey.io/languages/python/api/reference/glide/glide_client Illustrates the initialization process of the BaseClient, including setting up UDS connections and starting background tasks. ```APIDOC ## BaseClient Initialization Initializes the client, establishes a UDS connection, starts the reader loop, and sets connection configurations. ### Method ```python async def __init__(self, ...) ``` ### Description Waits for initialization events, creates a UDS connection, starts a background reader task, and configures the connection. ### Returns - `self`: The initialized BaseClient instance. ``` -------------------------------- ### GlideClusterClient time() Example Source: https://glide.valkey.io/languages/nodejs/api/classes/GlideClusterClient.GlideClusterClient.html Demonstrates how to use the time method to get the current server time, routing the request to all nodes in the cluster. ```javascript const result = await client.time('allNodes'); console.log(result); // Output: {'addr': ['1710925775', '913580'], 'addr2': ['1710925775', '913580'], 'addr3': ['1710925775', '913580']} ``` -------------------------------- ### Install Valkey GLIDE for Go Source: https://glide.valkey.io/getting-started/quickstart Install the Valkey GLIDE Go client library. This involves initializing a Go module if necessary, fetching the library, and tidying dependencies. Requires Go 1.22 or later. ```bash # Initialize a new Go module (if needed) go mod init your-project-name # Install GLIDE go get github.com/valkey-io/valkey-glide/go/v2 go mod tidy ``` -------------------------------- ### Get Hash Length - hlen (Existing Key) Source: https://glide.valkey.io/languages/nodejs/api/classes/GlideClient.GlideClient.html Returns the number of fields in a hash. This example demonstrates usage with an existing key. ```javascript const result = await client.hlen("my_hash"); console.log(result); // Output: 3 // Returns the number of fields for the hash stored at key `my_hash`. ``` -------------------------------- ### Example: Get Keys by Pattern (GlideString) Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Demonstrates how to retrieve keys matching a pattern using a GlideString pattern and print the results. ```java GlideString[] keys = client.keys(gs("key*")).get(); System.out.println("Found keys: " + Arrays.toString(keys)); ``` -------------------------------- ### Jedis Cluster Connection Setup Source: https://glide.valkey.io/migration/java/jedis/manual-migrations/connection-setup Demonstrates how to establish a basic Jedis cluster connection and a connection with advanced pool configurations. ```java // Simple cluster connection Set jedisClusterNodes = new HashSet<>(); jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7000)); jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7001)); JedisCluster cluster = new JedisCluster(jedisClusterNodes); ``` ```java // With options JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(128); poolConfig.setMaxIdle(128); poolConfig.setMinIdle(16); poolConfig.setTestOnBorrow(true); poolConfig.setTestOnReturn(true); poolConfig.setTestWhileIdle(true); JedisCluster clusterWithOptions = new JedisCluster(jedisClusterNodes, 2000, 2000, 5, "password", poolConfig); ``` -------------------------------- ### Example: Get Keys by Pattern (String) Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Demonstrates how to retrieve keys matching a pattern using a string pattern and print the results. ```java String[] keys = client.keys("key*").get(); System.out.println("Found keys: " + Arrays.toString(keys)); ``` -------------------------------- ### Get a Substring of a String with Valkey GLIDE Source: https://glide.valkey.io/migration/java/lettuce/command-comparison-chart Use getRange() to retrieve a portion of the string value of a key, specified by start and end offsets. ```java client.getRange("key", 0, 3) ``` -------------------------------- ### Configure and Create GLIDE Client (Go) Source: https://glide.valkey.io/getting-started/quickstart Set up connection configuration and create a new GLIDE client in Go. Includes host, port, request timeout, TLS, and database ID. Requires time and config package imports. ```go // Setting up connection configuration host := "localhost" port := 6379 config := config.NewClientConfiguration(). WithAddress(&config.NodeAddress{Host: host, Port: port}). WithRequestTimeout(5 * time.Second). WithUseTLS(false). WithDatabaseId(0) client, err := glide.NewClient(config) if err != nil { fmt.Println("There was an error: ", err) return } ``` -------------------------------- ### Get Substring of String with Valkey GLIDE Source: https://glide.valkey.io/migration/go/go-redis/command-comparison-chart Retrieves a partial string from a key based on start and end offsets using Valkey GLIDE. ```go client.GetRange(ctx, "key", 0, 3) ``` -------------------------------- ### Execute a Simple 'Hello World' Lua Script Source: https://glide.valkey.io/tutorials/lua-scripting/lua-scripting-basics Creates a Lua script that returns a string and executes it on the Valkey server using `client.invoke_script`. Results are returned as raw bytes. ```python # ... inside the try block print("Successfully connected to Valkey.") # 1. Create a simple 'Hello World' script hello_script = Script("return 'Hello, Valkey!'") # 2. Execute the script on the server result = await client.invoke_script(hello_script) # 3. Print the result print(f"Script result: {result}") ``` -------------------------------- ### info(InfoOptions.Section[] sections) Source: https://glide.valkey.io/languages/java/api/glide/api/GlideClient.html Get information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ```APIDOC ## info(InfoOptions.Section[] sections) ### Description Get information and statistics about the server. Starting from server version 7, command supports multiple section arguments. ### Method N/A (Method signature provided) ### Parameters #### Path Parameters - **sections** (InfoOptions.Section[]) - Required - The sections of information to retrieve. ### Return Type `java.util.concurrent.CompletableFuture` ``` -------------------------------- ### Lettuce Standalone Connection Setup Source: https://glide.valkey.io/migration/java/lettuce/connection-setup Demonstrates creating a Redis client and establishing a connection using Lettuce, both with default and custom options like password and database. ```java RedisClient client = RedisClient.create("redis://localhost"); StatefulRedisConnection connection = client.connect(); RedisCommands syncCommands = connection.sync(); ``` ```java // With options RedisURI redisUri = RedisURI.Builder.redis("localhost") .withPassword("password") .withDatabase(2) .build(); RedisClient clientWithOptions = RedisClient.create(redisUri); StatefulRedisConnection connectionWithOptions = clientWithOptions.connect(); RedisCommands syncCommandsWithOptions = connectionWithOptions.sync(); ``` -------------------------------- ### Ping With Route Example Source: https://glide.valkey.io/languages/java/api/glide/api/commands/ConnectionManagementClusterCommands.html Example demonstrating how to ping the server using a specified route (ALL_NODES) and assert the "PONG" response. ```java String payload = clusterClient.ping(ALL_NODES).get(); assert payload.equals("PONG"); ``` -------------------------------- ### Create ClusterScanCursor in Java Source: https://glide.valkey.io/concepts/client-features/cluster-scan Initialize a ClusterScanCursor for starting a cluster-wide scan in Java. Use `initalCursor()` to get a cursor that manages the scan state. ```java ClusterScanCursor cursor = ClusterScanCursor.initalCursor(); ```