### Install adk-redis and run an example Source: https://redis.io/docs/latest/integrate/google-adk/examples Installs the adk-redis library with all features and provides commands to navigate to an example directory and run a Python script. Ensure you set your GOOGLE_API_KEY before running. ```bash pip install adk-redis[all] cd examples/simple_redis_memory export GOOGLE_API_KEY=your-key python main.py ``` -------------------------------- ### KeysOnlyReader Examples Source: https://redis.io/docs/latest/operate/oss_and_stack/stack-with-enterprise/deprecated-features/gears-v1/jvm/classes/readers/keysonlyreader Provides examples of how to use the KeysOnlyReader. The first example shows how to get all keys in the database using the default constructor. The second example demonstrates how to retrieve keys that match a specific pattern, like those starting with 'user:'. ```APIDOC ## Examples Get all keys in the database: ```java KeysOnlyReader reader = new KeysOnlyReader(); ``` Only get keys that start with "user:": ```java KeysOnlyReader reader = new KeysOnlyReader(1000, "user:*"); ``` ``` -------------------------------- ### Redis GET Command Examples Source: https://redis.io/docs/latest/commands/get Illustrates the behavior of the GET command with non-existent keys and existing keys. ```redis redis> GET nonexisting (nil) redis> SET mykey "Hello" "OK" redis> GET mykey "Hello" ``` -------------------------------- ### Go (go-redis) Example Source: https://redis.io/docs/latest/commands/ttl Example of using the `TTL` command in `go-redis` to get the time-to-live for a key. ```APIDOC ## Go (go-redis) ### Method Signature ```go TTL( ctx: context.Context, key: string ) → *DurationCmd ``` ### Description Returns the remaining time to live of a key that has a timeout, in seconds. ### Parameters - **ctx** (context.Context): The context for the request. - **key** (string): The key to check. ### Returns - **DurationCmd**: A command object that can be used to retrieve the time-to-live. The result is in seconds, or a negative value to signal an error (-1 if no expiry, -2 if key doesn't exist). ### Example ```go // Assuming 'rdb' is an instance of redis.Client ctx := context.Background() rdb.Set(ctx, "mykey", "Hello", 0).Result() rdb.Expire(ctx, "mykey", 10*time.Second).Result() ttlValue, err := rdb.TTL(ctx, "mykey").Result() // ttlValue will be 10 ``` -------------------------------- ### Example: Joining a cluster with basic parameters Source: https://redis.io/docs/latest/operate/rs/references/cli-utilities/rladmin/cluster/join This example demonstrates how to join a cluster using the essential parameters: the IP address of an existing node, the admin username, and the admin password. ```bash $ rladmin cluster join nodes 192.0.2.2 \ username admin@example.com \ password admin-password Joining cluster... ok ``` -------------------------------- ### Example Usage: HELLO with AUTH and SETNAME Source: https://redis.io/docs/latest/commands/hello An example demonstrating how to use the HELLO command to switch protocol, authenticate, and set a client name. ```APIDOC ## Example: HELLO with AUTH and SETNAME ### Request ``` > HELLO 3 AUTH default "my_password" SETNAME "my_client" ``` ### Response (Example) ``` 1# "server" => "redis" 2# "version" => "7.0.0" 3# "proto" => (integer) 3 4# "id" => (integer) 15 5# "mode" => "standalone" 6# "role" => "master" 7# "modules" => (empty array) ``` ``` -------------------------------- ### Example HTTP Request with Parameters Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/cluster/stats An example of an HTTP GET request to fetch cluster statistics for a specific interval and start time. The `interval` and `stime` parameters are optional. ```http GET /v1/cluster/stats/1?interval=1hour&stime=2014-08-28T10:00:00Z ``` -------------------------------- ### Example Usage: Switching to RESP3 Source: https://redis.io/docs/latest/commands/hello An example of how to use the HELLO command to switch to the RESP3 protocol. ```APIDOC ## Example: Switch to RESP3 ### Request ``` > HELLO 3 ``` ### Response (Example) ``` 1# "server" => "redis" 2# "version" => "6.0.0" 3# "proto" => (integer) 3 4# "id" => (integer) 10 5# "mode" => "standalone" 6# "role" => "master" 7# "modules" => (empty array) ``` ``` -------------------------------- ### Example HTTP Request for Cluster Stats Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/cluster/stats/last An example HTTP GET request to the cluster stats endpoint, including optional query parameters for interval and start time. The 'interval' parameter specifies the time frame for the stats, and 'stime' sets the starting point. ```http GET /v1/cluster/stats/last?interval=1sec&stime=2015-10-14T06:44:00Z ``` -------------------------------- ### Redis CLI RPUSH and LRANGE Example Source: https://redis.io/docs/latest/commands/rpush Shows how to use the RPUSH command in the Redis command-line interface to add elements to a list and LRANGE to retrieve them. This is a basic example for getting started. ```redis redis> RPUSH mylist "hello" (integer) 1 redis> RPUSH mylist "world" (integer) 2 redis> LRANGE mylist 0 -1 1) "hello" 2) "world" ``` -------------------------------- ### Python Quick-Start: Set and Get Source: https://redis.io/docs/latest/commands/set Demonstrates setting a key-value pair and retrieving its value using the `redis-py` library. Ensure the client is connected before performing operations. ```python import { createClient } from 'redis'; const client = createClient(); client.on('error', err => console.log('Redis Client Error', err)); await client.connect().catch(console.error); await client.set('bike:1', 'Process 134'); const value = await client.get('bike:1'); console.log(value); // returns 'Process 134' await client.close(); ``` -------------------------------- ### Go Quick-Start Source: https://redis.io/docs/latest/commands/get Connect to Redis, set a key-value pair, and retrieve the value using the GET command in Go. ```go package example_commands_test import ( "context" "fmt" "github.com/redis/go-redis/v9" ) func ExampleClient_Set_and_get() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) err := rdb.Set(ctx, "bike:1", "Process 134", 0).Err() if err != nil { panic(err) } fmt.Println("OK") value, err := rdb.Get(ctx, "bike:1").Result() if err != nil { panic(err) } fmt.Printf("The name of the bike is %s", value) } ``` -------------------------------- ### Example HOTKEYS GET Output Source: https://redis.io/docs/latest/commands/hotkeys-get This example shows the typical output of the HOTKEYS GET command when both NET and CPU metrics were specified during HOTKEYS START. It includes tracking status, sample ratio, selected slots, performance metrics, and lists of hotkeys sorted by CPU time and network bytes. ```redis HOTKEYS GET 1) 1) "tracking-active" 2) (integer) 0 3) "sample-ratio" 4) (integer) 1 5) "selected-slots" 6) 1) 1) (integer) 0 2) (integer) 16383 7) "all-commands-all-slots-us" 8) (integer) 103 9) "net-bytes-all-commands-all-slots" 10) (integer) 2042 11) "collection-start-time-unix-ms" 12) (integer) 1770824933147 13) "collection-duration-ms" 14) (integer) 0 15) "total-cpu-time-user-ms" 16) (integer) 23 17) "total-cpu-time-sys-ms" 18) (integer) 7 19) "total-net-bytes" 20) (integer) 2038 21) "by-cpu-time-us" 22) 1) "hotkey_001_counter" 2) (integer) 29 3) "hotkey_001" 4) (integer) 25 5) "hotkey_001_hash" 6) (integer) 11 7) "hotkey_001_list" 8) (integer) 9 9) "hotkey_001_set" 10) (integer) 9 23) "by-net-bytes" 24) 1) "hotkey_001" 2) (integer) 446 3) "hotkey_002" 4) (integer) 328 5) "hotkey_001_hash" 6) (integer) 198 7) "hotkey_001_set" 8) (integer) 167 9) "hotkey_001_counter" 10) (integer) 116 ``` -------------------------------- ### Initialize and Run MCP Server from Source Source: https://redis.io/docs/latest/integrate/redis-mcp/install After cloning the repository and installing `uv`, navigate to the `mcp-redis` directory and use `uv` commands to set up and run the MCP server. This includes creating a virtual environment, activating it, syncing dependencies, and running the server. ```bash cd mcp-redis uv venv source .venv/bin/activate uv sync ``` ```bash # Run with CLI interface uv run redis-mcp-server --help # Or run the main file directly (uses environment variables) uv run src/main.py ``` -------------------------------- ### Get All Shards Stats HTTP Request Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/shards/stats This example shows how to make an HTTP GET request to retrieve statistics for all shards. It includes optional query parameters for specifying a time interval and start time. ```http GET /v1/shards/stats?interval=1hour&stime=2014-08-28T10:00:00Z ``` -------------------------------- ### ACL User with Selectors (Example 3) Source: https://redis.io/docs/latest/commands/acl-setuser This example demonstrates setting up a user with multiple permission sets (selectors). The user has root permissions for GET on any key, and a selector for SET on keys starting with 'app1'. ```redis ACL SETUSER virginia on +GET allkeys (+SET ~app1*) ``` -------------------------------- ### Go: ExampleClient.keys_cmd Source: https://redis.io/docs/latest/commands/keys Demonstrates using the MSET command to set multiple keys and then the KEYS command to retrieve keys matching specific patterns in Go. Sorting is applied for consistent output. ```go func ExampleClient_keys_cmd() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) keysResult1, err := rdb.MSet(ctx, "firstname", "Jack", "lastname", "Stuntman", "age", "35").Result() if err != nil { panic(err) } fmt.Println(keysResult1) // >>> OK keysResult2, err := rdb.Keys(ctx, "*name*").Result() if err != nil { panic(err) } sort.Strings(keysResult2) fmt.Println(keysResult2) // >>> [firstname lastname] keysResult3, err := rdb.Keys(ctx, "a??").Result() if err != nil { panic(err) } fmt.Println(keysResult3) // >>> [age] keysResult4, err := rdb.Keys(ctx, "*").Result() if err != nil { panic(err) } sort.Strings(keysResult4) fmt.Println(keysResult4) // >>> [age firstname lastname] } ``` -------------------------------- ### Go: MSET and KEYS command examples Source: https://redis.io/docs/latest/commands/del Demonstrates using MSET to set multiple key-value pairs and KEYS to retrieve keys matching a pattern. Note: KEYS is generally discouraged in production environments due to performance implications. ```go keysResult1, err := rdb.MSet(ctx, "firstname", "Jack", "lastname", "Stuntman", "age", "35").Result() if err != nil { panic(err) } fmt.Println(keysResult1) // >>> OK ``` ```go keysResult2, err := rdb.Keys(ctx, "*name*").Result() if err != nil { panic(err) } sort.Strings(keysResult2) fmt.Println(keysResult2) // >>> [firstname lastname] ``` ```go keysResult3, err := rdb.Keys(ctx, "a??").Result() if err != nil { panic(err) } fmt.Println(keysResult3) // >>> [age] ``` ```go keysResult4, err := rdb.Keys(ctx, "*").Result() if err != nil { panic(err) } sort.Strings(keysResult4) fmt.Println(keysResult4) // >>> [age firstname lastname] ``` -------------------------------- ### Get Keys Matching Wildcard Pattern Source: https://redis.io/docs/latest/commands/keys Retrieves keys matching a pattern with wildcards. This example uses 'a??' to find keys starting with 'a' followed by any two characters. ```rust match r.keys::<&str, Vec>("a??").await { Ok(res) => { println!("{res:?}"); // >>> ["age"] }, Err(e) => { println!("Error getting keys: {e}"); return; } } ``` -------------------------------- ### Example: KEYS Command Source: https://redis.io/docs/latest/commands/scan Demonstrates how to find keys matching a pattern. It shows using wildcards like '*' and '??' to retrieve keys based on their names. ```go package example_commands_test import ( "context" "fmt" "sort" "github.com/redis/go-redis/v9" ) func ExampleClient_keys_cmd() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) keysResult1, err := rdb.MSet(ctx, "firstname", "Jack", "lastname", "Stuntman", "age", "35").Result() if err != nil { panic(err) } fmt.Println(keysResult1) // >>> OK keysResult2, err := rdb.Keys(ctx, "*name*").Result() if err != nil { panic(err) } sort.Strings(keysResult2) fmt.Println(keysResult2) // >>> [firstname lastname] keysResult3, err := rdb.Keys(ctx, "a??").Result() if err != nil { panic(err) } fmt.Println(keysResult3) // >>> [age] keysResult4, err := rdb.Keys(ctx, "*").Result() if err != nil { panic(err) } sort.Strings(keysResult4) fmt.Println(keysResult4) // >>> [age firstname lastname] } ``` -------------------------------- ### Get Specific Shard Stats HTTP Request Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/shards/stats This example demonstrates how to make an HTTP GET request to retrieve statistics for a single, specific shard identified by its UID. It also shows the use of optional query parameters for time interval and start time. ```http GET /v1/shards/stats/1?interval=1hour&stime=2014-08-28T10:00:00Z ``` -------------------------------- ### Java-Sync Quick-Start Example Source: https://redis.io/docs/latest/commands/lpop Demonstrates the usage of various list commands including LPUSH, LRANGE, LLEN, RPUSH, and LPOP using Lettuce's asynchronous API. Shows how to push elements, retrieve ranges, get list lengths, and pop elements from the left. ```java package io.redis.examples.async; import io.lettuce.core.*; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.api.StatefulRedisConnection; import java.util.concurrent.CompletableFuture; public class CmdsListExample { public void run() { RedisClient redisClient = RedisClient.create("redis://localhost:6379"); try (StatefulRedisConnection connection = redisClient.connect()) { RedisAsyncCommands asyncCommands = connection.async(); CompletableFuture lpush = asyncCommands.lpush("mylist", "world").thenCompose(res1 -> { System.out.println(res1); // >>> 1 return asyncCommands.lpush("mylist", "hello"); }).thenCompose(res2 -> { System.out.println(res2); // >>> 2 return asyncCommands.lrange("mylist", 0, -1); }) .thenAccept(res3 -> System.out.println(res3)) // >>> [hello, world] .toCompletableFuture(); lpush.join(); CompletableFuture lrange = asyncCommands.rpush("mylist", "one").thenCompose(res4 -> { System.out.println(res4); // >>> 1 return asyncCommands.rpush("mylist", "two"); }).thenCompose(res5 -> { System.out.println(res5); // >>> 2 return asyncCommands.rpush("mylist", "three"); }).thenCompose(res6 -> { System.out.println(res6); // >>> 3 return asyncCommands.lrange("mylist", 0, 0); }).thenCompose(res7 -> { System.out.println(res7); // >>> [one] return asyncCommands.lrange("mylist", -3, 2); }).thenCompose(res8 -> { System.out.println(res8); // >>> [one, two, three] return asyncCommands.lrange("mylist", -100, 100); }).thenCompose(res9 -> { System.out.println(res9); // >>> [one, two, three] return asyncCommands.lrange("mylist", 5, 10); }) .thenAccept(res10 -> System.out.println(res10)) // >>> [] .toCompletableFuture(); lrange.join(); CompletableFuture llen = asyncCommands.lpush("mylist", "World").thenCompose(res11 -> { System.out.println(res11); // >>> 1 return asyncCommands.lpush("mylist", "Hello"); }).thenCompose(res12 -> { System.out.println(res12); // >>> 2 return asyncCommands.llen("mylist"); }) .thenAccept(res13 -> System.out.println(res13)) // >>> 2 .toCompletableFuture(); llen.join(); CompletableFuture rpush = asyncCommands.rpush("mylist", "hello").thenCompose(res14 -> { System.out.println(res14); // >>> 1 return asyncCommands.rpush("mylist", "world"); }).thenCompose(res15 -> { System.out.println(res15); // >>> 2 return asyncCommands.lrange("mylist", 0, -1); }) .thenAccept(res16 -> System.out.println(res16)) // >>> [hello, world] .toCompletableFuture(); rpush.join(); CompletableFuture lpop = asyncCommands.rpush("mylist", "one", "two", "three", "four", "five") .thenCompose(res17 -> { System.out.println(res17); // >>> 5 return asyncCommands.lpop("mylist"); }).thenCompose(res18 -> { System.out.println(res18); // >>> one return asyncCommands.lpop("mylist", 2); }).thenCompose(res19 -> { System.out.println(res19); // >>> [two, three] ``` -------------------------------- ### Get all elements from a stream in reverse order Source: https://redis.io/docs/latest/commands/xrevrange This example demonstrates how to retrieve all elements from a Redis stream in reverse order using the XREVRANGE command with '+' and '-' as the start and end IDs. ```redis XREVRANGE somestream + - ``` -------------------------------- ### Java: Basic LRANGE Example Source: https://redis.io/docs/latest/commands/lrange Demonstrates retrieving all elements from a list using LRANGE with start index 0 and end index -1. This is a common way to get the entire list content. ```java CompletableFuture lpush = asyncCommands.lpush("mylist", "world").thenCompose(res1 -> { System.out.println(res1); // >>> 1 return asyncCommands.lpush("mylist", "hello"); }).thenCompose(res2 -> { System.out.println(res2); // >>> 2 return asyncCommands.lrange("mylist", 0, -1); }) .thenAccept(res3 -> System.out.println(res3)); // >>> [hello, world] lpush.join(); ``` -------------------------------- ### Example module status with extra all Source: https://redis.io/docs/latest/operate/rs/references/cli-utilities/rladmin/status This example shows how to display all extra information for cluster and database modules, including version, minimum Redis version, and module ID. ```bash $ rladmin status modules extra all CLUSTER MODULES: MODULE VERSION MIN_REDIS_VERSION ID RedisBloom 2.4.5 6.0 1b895a180592cbcae5bd3bff6af24be2 RedisBloom 2.6.8 7.1 95264e7c9ac9540268c115c86a94659b RediSearch 2 2.6.12 6.0 2c000539f65272f7a2712ed3662c2b6b RediSearch 2 2.8.9 7.1 dd9a75710db528afa691767e9310ac6f RedisGears 2.0.15 7.1 18c83d024b8ee22e7caf030862026ca6 RedisGraph 2.10.12 6.0 5a1f2fdedb8f6ca18f81371ea8d28f68 RedisJSON 2.4.7 6.0 28308b101a0203c21fa460e7eeb9344a RedisJSON 2.6.8 7.1 b631b6a863edde1b53b2f7a27a49c004 RedisTimeSeries 1.8.11 6.0 8fe09b00f56afe5dba160d234a6606af RedisTimeSeries 1.10.9 7.1 98a492a017ea6669a162fd3503bf31f3 DATABASE MODULES: DB:ID NAME MODULE VERSION ARGS STATUS db:1 search-json-db RediSearch 2 2.8.9 PARTITIONS AUTO OK db:1 search-json-db RedisJSON 2.6.8 OK db:2 timeseries-db RedisTimeSeries 1.10.9 OK ``` -------------------------------- ### Basic MSET Usage Example Source: https://redis.io/docs/latest/commands/mset This example demonstrates the basic usage of the MSET command to set two keys, 'key1' and 'key2', with their respective values. It also shows how to retrieve the values using GET to verify the operation. ```redis redis> MSET key1 "Hello" key2 "World" "OK" redis> GET key1 "Hello" redis> GET key2 "World" redis> ``` -------------------------------- ### Redis CLI CONFIG GET Example Source: https://redis.io/docs/latest/commands/config-get An example demonstrating the use of CONFIG GET with multiple parameters and glob-style patterns in redis-cli. ```redis redis> config get *max-*-entries* maxmemory 1) "maxmemory" 2) "0" 3) "hash-max-listpack-entries" 4) "512" 5) "hash-max-ziplist-entries" 6) "512" 7) "set-max-intset-entries" 8) "512" 9) "zset-max-listpack-entries" 10) "128" 11) "zset-max-ziplist-entries" 12) "128" ``` -------------------------------- ### Java (Lettuce-Async) Client Example Source: https://redis.io/docs/latest/commands/sdiffstore Example of using the sdiffstore command with the Lettuce-Async client. ```APIDOC ## sdiffstore (Lettuce-Async) ### Description Stores the difference between sets in a destination key using the Lettuce-Async client. ### Method Signature ```java sdiffstore( destination: K, // the destination type: key. keys: K... // the key. ) → RedisFuture ``` ### Parameters - **destination**: The key for the destination set. - **keys**: One or more keys representing the source sets. ``` -------------------------------- ### Go Redis MSET, KEYS, and TTL Examples Source: https://redis.io/docs/latest/commands/scan Demonstrates setting multiple key-value pairs, retrieving keys matching a pattern, and checking the time-to-live of a key using the Go redis client. ```go rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) keysResult1, err := rdb.MSet(ctx, "firstname", "Jack", "lastname", "Stuntman", "age", "35").Result() if err != nil { panic(err) } fmt.Println(keysResult1) // >>> OK keysResult2, err := rdb.Keys(ctx, "*name*").Result() if err != nil { panic(err) } sort.Strings(keysResult2) fmt.Println(keysResult2) // >>> [firstname lastname] keysResult3, err := rdb.Keys(ctx, "a??").Result() if err != nil { panic(err) } fmt.Println(keysResult3) // >>> [age] keysResult4, err := rdb.Keys(ctx, "*").Result() if err != nil { panic(err) } sort.Strings(keysResult4) fmt.Println(keysResult4) // >>> [age firstname lastname] } func ExampleClient_ttl_cmd() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) tlResult1, err := rdb.Set(ctx, "mykey", "Hello", 10*time.Second).Result() if err != nil { panic(err) } fmt.Println(ttlResult1) // >>> OK tlResult2, err := rdb.TTL(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println(math.Round(ttlResult2.Seconds())) // >>> 10 } ``` -------------------------------- ### Get and Rename Databases with Python Source: https://redis.io/docs/latest/operate/rs/references/rest-api/quick-start Use the Python requests library to fetch a list of databases and then rename them using the REST API. Ensure you have the 'requests' library installed. This example makes unverified HTTPS requests, which is not recommended for production. ```python import requests import json import warnings host = "[host]" port = "[port]" username = "[username]" password = "[password]" # Suppress only the single InsecureRequestWarning from urllib3 needed for this example from urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) # Get the list of databases using GET /v1/bdbs bdbs_uri = "https://{}:{}/v1/bdbs".format(host, port) print("GET {}".format(bdbs_uri)) get_resp = requests.get(bdbs_uri, auth = (username, password), headers = { "accept" : "application/json" }, verify = False) print("{} {}".format(get_resp.status_code, get_resp.reason)) for header in get_resp.headers.keys(): print("{}: {}".format(header, get_resp.headers[header])) print("\n" + json.dumps(get_resp.json(), indent=4)) # Rename all databases using PUT /v1/bdbs for bdb in get_resp.json(): uid = bdb["uid"] # Get the database ID from the JSON response put_uri = "{}/{}".format(bdbs_uri, uid) new_name = "database{}".format(uid) put_data = { "name" : new_name } print("PUT {} {}".format(put_uri, json.dumps(put_data))) put_resp = requests.put(put_uri, data = json.dumps(put_data), auth = (username, password), headers = { "content-type" : "application/json" }, verify = False) print("{} {}".format(put_resp.status_code, put_resp.reason)) for header in put_resp.headers.keys(): print("{}: {}".format(header, put_resp.headers[header])) print("\n" + json.dumps(put_resp.json(), indent=4)) ``` -------------------------------- ### Go Example: HSET and HGET Source: https://redis.io/docs/latest/commands/hget Demonstrates setting and getting individual fields in a hash using HSET and HGET. Shows how to retrieve values and handle potential errors. ```go package example_commands_test import ( "context" "fmt" "sort" "time" "github.com/redis/go-redis/v9" ) func ExampleClient_hset() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) res1, err := rdb.HSet(ctx, "myhash", "field1", "Hello").Result() if err != nil { panic(err) } fmt.Println(res1) // >>> 1 res2, err := rdb.HGet(ctx, "myhash", "field1").Result() if err != nil { panic(err) } fmt.Println(res2) // >>> Hello res3, err := rdb.HSet(ctx, "myhash", "field2", "Hi", "field3", "World", ).Result() if err != nil { panic(err) } fmt.Println(res3) // >>> 2 res4, err := rdb.HGet(ctx, "myhash", "field2").Result() if err != nil { panic(err) } fmt.Println(res4) // >>> Hi res5, err := rdb.HGet(ctx, "myhash", "field3").Result() if err != nil { panic(err) } fmt.Println(res5) // >>> World res6, err := rdb.HGetAll(ctx, "myhash").Result() if err != nil { panic(err) } keys := make([]string, 0, len(res6)) for key, _ := range res6 { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { fmt.Printf("Key: %v, value: %v\n", key, res6[key]) } // >>> Key: field1, value: Hello // >>> Key: field2, value: Hi // >>> Key: field3, value: World } ``` -------------------------------- ### Track provisioning status Source: https://redis.io/docs/latest/operate/rc/api/get-started/process-lifecycle When the processing phase succeeds and the task is in the `processing-completed` state, the provisioning phase starts. You can query the resource identifier to track the progress of the provisioning phase. For example, when you provision a new subscription, use GET /v1/subscriptions/{subscriptionId}. ```APIDOC ## GET /v1/subscriptions/{subscriptionId} ### Description Tracks the progress of the provisioning phase for a subscription using its resource ID. ### Method GET ### Endpoint /v1/subscriptions/{subscriptionId} ### Parameters #### Path Parameters - **subscriptionId** (string) - Required - The resource ID of the subscription being provisioned. ``` -------------------------------- ### Java (Lettuce-Sync) Client Example Source: https://redis.io/docs/latest/commands/getbit Example of using the getbit command with the Lettuce-Sync client library. ```APIDOC ## getbit(key: K, offset: long) -> Long ### Description Gets the bit value at the specified offset for the given key. ### Parameters - **key** (K) - Required - The key of the string. - **offset** (long) - Required - The offset in the string to get a bit at. ### Returns - **Long** - The bit value stored at the offset. ``` -------------------------------- ### Basic COPY Example Source: https://redis.io/docs/latest/commands/copy A simple example demonstrating how to use the COPY command. It first sets a key, then copies it to a new key, and finally retrieves the value of the new key. ```redis SET dolly "sheep" COPY dolly clone GET clone ``` -------------------------------- ### Example HTTP Request to Get a Module Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/modules An example of an HTTP GET request to retrieve a specific module using its UID. Replace '{string: uid}' with the actual module ID. ```http GET /v1/modules/1 ``` -------------------------------- ### Java (Lettuce-Sync) Client Example Source: https://redis.io/docs/latest/commands/sdiffstore Example of using the sdiffstore command with the Lettuce-Sync client. ```APIDOC ## sdiffstore (Lettuce-Sync) ### Description Stores the difference between sets in a destination key using the Lettuce-Sync client. ### Method Signature ```java sdiffstore( destination: K, // the destination type: key. keys: K... // the key. ) → Long ``` ### Parameters - **destination**: The key for the destination set. - **keys**: One or more keys representing the source sets. ``` -------------------------------- ### Example HTTP Request for Flushing an Active-Active Database Source: https://redis.io/docs/latest/operate/rs/references/rest-api/requests/crdbs/flush This is an example of an HTTP PUT request to flush a specific Active-Active database. Replace the placeholder GUID with your actual database GUID. ```http PUT /v1/crdbs/552bbccb-99f3-4142-bd17-93d245f0bc79/flush ``` -------------------------------- ### PHP Example Source: https://redis.io/docs/latest/commands/ttl Example of using the `ttl` method in PHP to get the time-to-live for a key. ```APIDOC ## PHP ### Method Signature ```php ttl( $key: string ) → int ``` ### Description Returns the remaining time to live of a key that has a timeout, in seconds. ### Parameters - **$key** (string): The key to check. ### Returns - **int**: The time-to-live in seconds, or a negative value to signal an error (-1 if no expiry, -2 if key doesn't exist). ### Example ```php // Assuming '$redis' is an instance of Redis $redis->set('mykey', 'Hello'); $redis->expire('mykey', 10); $ttlValue = $redis->ttl('mykey'); // $ttlValue will be 10 ``` -------------------------------- ### Example: EXPIRE and TTL Commands Source: https://redis.io/docs/latest/commands/scan Demonstrates setting expiration times for keys and retrieving their Time To Live (TTL). Includes examples for EXPIRE, EXPIREXX, EXPIRENX, and TTL. ```go package example_commands_test import ( "context" "fmt" "math" "github.com/redis/go-redis/v9" ) func ExampleClient_expire_cmd() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) expireResult1, err := rdb.Set(ctx, "mykey", "Hello", 0).Result() if err != nil { panic(err) } fmt.Println(expireResult1) // >>> OK expireResult2, err := rdb.Expire(ctx, "mykey", 10*time.Second).Result() if err != nil { panic(err) } fmt.Println(expireResult2) // >>> true expireResult3, err := rdb.TTL(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println(math.Round(expireResult3.Seconds())) // >>> 10 expireResult4, err := rdb.Set(ctx, "mykey", "Hello World", 0).Result() if err != nil { panic(err) } fmt.Println(expireResult4) // >>> OK expireResult5, err := rdb.TTL(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println(expireResult5) // >>> -1ns expireResult6, err := rdb.ExpireXX(ctx, "mykey", 10*time.Second).Result() if err != nil { panic(err) } fmt.Println(expireResult6) // >>> false expireResult7, err := rdb.TTL(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println(expireResult7) // >>> -1ns expireResult8, err := rdb.ExpireNX(ctx, "mykey", 10*time.Second).Result() if err != nil { panic(err) } fmt.Println(expireResult8) // >>> true expireResult9, err := rdb.TTL(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println(math.Round(expireResult9.Seconds())) // >>> 10 } ``` -------------------------------- ### Python (redis-py) Example Source: https://redis.io/docs/latest/commands/get Example of using the GET command with the redis-py client in Python. ```APIDOC ## GET with redis-py (Python) ### Description This snippet demonstrates how to retrieve a string value from Redis using the `get` method of the `redis-py` library. It also shows setting a key first. ### Method `r.get(key)` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import redis r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True) res = r.set("bike:1", "Process 134") print(res) # >>> True res = r.get("bike:1") print(res) # >>> "Process 134" ``` ### Response #### Success Response (200) - **res** (boolean or string) - The result of the `set` operation (True) or the retrieved value (string) or None if the key does not exist. #### Response Example ``` True "Process 134" ``` ``` -------------------------------- ### BITFIELD Example Usage Source: https://redis.io/docs/latest/commands/bitfield An example demonstrating the use of BITFIELD with INCRBY and GET subcommands. ```APIDOC ## Example ``` > BITFIELD mykey INCRBY i5 100 1 GET u4 0 1) (integer) 1 2) (integer) 0 ``` ``` -------------------------------- ### Example of Running GearsBuilder Source: https://redis.io/docs/latest/operate/oss_and_stack/stack-with-enterprise/deprecated-features/gears-v1/jvm/classes/gearsbuilder/run This example demonstrates how to create a GearsBuilder and immediately run the associated pipeline. ```java GearsBuilder.CreateGearsBuilder(reader).run(); ``` -------------------------------- ### C Quick-Start: HGET and HMGET Source: https://redis.io/docs/latest/commands/hget This example demonstrates connecting to Redis, setting hash fields using HSET, and retrieving multiple fields at once using HMGET. ```c #include #include #include #include int main(int argc, char **argv) { redisContext *c = redisConnect("127.0.0.1", 6379); if (c == NULL || c->err) { if (c) { printf("Connection error: %s\n", c->errstr); redisFree(c); } else { printf("Connection error: can't allocate redis context\n"); } return 1; } redisReply *reply; // Set up hash with fields reply = redisCommand(c, "HSET %s %s %s %s %s", "myhash", "field1", "Hello", "field2", "World"); freeReplyObject(reply); // Get multiple fields at once reply = redisCommand(c, "HMGET %s %s %s %s", "myhash", "field1", "field2", "nofield"); printf("HMGET myhash field1 field2 nofield:\n"); for (size_t i = 0; i < reply->elements; i++) { if (reply->element[i]->type == REDIS_REPLY_NIL) { printf(" [%zu]: null\n", i); } else { printf(" [%zu]: %s\n", i, reply->element[i]->str); } } // >>> [0]: Hello // >>> [1]: World // >>> [2]: null freeReplyObject(reply); redisFree(c); return 0; } ``` -------------------------------- ### Java-Sync (Jedis) Example Source: https://redis.io/docs/latest/commands/ttl Example of using the `ttl` method in Jedis to get the time-to-live for a key. ```APIDOC ## Java-Sync (Jedis) ### Method Signature ```java ttl( key: byte[] ) → long ``` ### Description Returns the remaining time to live of a key that has a timeout, in seconds. ### Parameters - **key** (byte[]): The key to check. ### Returns - **long**: The time-to-live in seconds, or a negative value in order to signal an error (-1 if no expiry, -2 if key doesn't exist). ### Example ```java // Assuming 'jedis' is an instance of Jedis jedis.set("mykey", "Hello"); jedis.expire("mykey", 10); long ttlValue = jedis.ttl("mykey"); // ttlValue will be 10 ``` -------------------------------- ### redis-di start CLI Help Source: https://redis.io/docs/latest/integrate/redis-data-integration/reference/cli/redis-di-start Comprehensive CLI help output for the redis-di start command, detailing all available options and their descriptions. ```bash Usage: redis-di start [OPTIONS] Starts the pipeline Options: -l, --log-level [TRACE|DEBUG|INFO|WARNING|ERROR|CRITICAL] [default: INFO] --rdi-host TEXT Host/IP of RDI Database [required] --rdi-port INTEGER RANGE Port of RDI Database [1<=x<=65535; required] --rdi-user TEXT RDI Database Username --rdi-password TEXT RDI Database Password --rdi-key TEXT Private key file to authenticate with --rdi-cert TEXT Client certificate file to authenticate with --rdi-cacert TEXT CA certificate file to verify with --rdi-key-password TEXT Password for unlocking an encrypted private key --help Show this message and exit. ``` -------------------------------- ### Go Example: HGETALL for All Fields Source: https://redis.io/docs/latest/commands/hget Shows how to retrieve all fields and their values from a hash using HGETALL. Demonstrates setting multiple fields and then fetching them. ```go func ExampleClient_hgetall() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password DB: 0, // use default DB }) hGetAllResult1, err := rdb.HSet(ctx, "myhash", "field1", "Hello", "field2", "World", ).Result() if err != nil { panic(err) } fmt.Println(hGetAllResult1) // >>> 2 hGetAllResult2, err := rdb.HGetAll(ctx, "myhash").Result() if err != nil { panic(err) } keys := make([]string, 0, len(hGetAllResult2)) for key, _ := range hGetAllResult2 { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { fmt.Printf("Key: %v, value: %v\n", key, hGetAllResult2[key]) } // >>> Key: field1, value: Hello // >>> Key: field2, value: World } ``` -------------------------------- ### Go (go-redis) Client Example Source: https://redis.io/docs/latest/commands/client-id Example of how to get the client ID using the go-redis library. ```APIDOC ```go import ( "context" "fmt" "github.com/go-redis/redis/v8" ) func main() { r := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.Background() clientId, err := r.ClientID(ctx).Result() if err != nil { panic(err) } fmt.Printf("Client ID: %d\n", clientId) } ``` ``` -------------------------------- ### Example: Add Instance to Active-Active Database Source: https://redis.io/docs/latest/operate/rs/references/cli-utilities/crdb-cli/crdb/add-instance This example demonstrates how to add a new instance to an Active-Active database using the `crdb-cli`. It specifies the database GUID and the connection details for the new cluster. ```bash $ crdb-cli crdb add-instance --crdb-guid db6365b5-8aca-4055-95d8-7eb0105c0b35 \ --instance fqdn=cluster2.redis.local,username=admin@redis.local,password=admin-password Task f809fae7-8e26-4c8f-9955-b74dbbd47949 created ---> Status changed: queued -> started ---> Status changed: started -> finished ``` -------------------------------- ### Java-Sync (Jedis) Client Example Source: https://redis.io/docs/latest/commands/client-id Example of how to get the client ID using the Jedis library. ```APIDOC ```java import redis.clients.jedis.Jedis; public class RedisClientId { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); long clientId = jedis.clientId(); System.out.println("Client ID: " + clientId); jedis.close(); } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.