### Start with Custom Test Image Source: https://redis.github.io/lettuce/integration-testing Starts the Redis environment using a custom Docker image tag for client libraries. ```bash make start CLIENT_LIBS_TEST_IMAGE_TAG= ``` -------------------------------- ### Starting Redis Instance for Testing Source: https://redis.github.io/lettuce Command to start a Redis instance manually, typically used when building or testing Lettuce. This relies on the Makefile configuration. ```bash $ make start ``` -------------------------------- ### KeyCommands Interface Example Source: https://redis.github.io/lettuce/redis-command-interfaces An example of a `KeyCommands` interface extending `Commands`, demonstrating methods for Redis GET and SET operations. Each method signature maps to a specific Redis command, with return types and parameter types indicating expected results and input serialization. ```APIDOC ## KeyCommands Interface ### Description This interface declares methods for interacting with Redis keys, including retrieving a key's value and setting a key-value pair. It extends the `Commands` marker interface. ### Methods #### `String get(String key)` ##### Description Retrieves the value associated with a given key. ##### Parameters - **key** (String) - Required - The name of the key to retrieve. ##### Response - **Success Response (200)** - (String) - The value of the key, or null if the key does not exist. #### `String set(String key, String value)` ##### Description Sets a key to a specified string value. ##### Parameters - **key** (String) - Required - The name of the key to set. - **value** (String) - Required - The string value to set for the key. ##### Response - **Success Response (200)** - (String) - OK response. #### `String set(String key, byte[] value)` ##### Description Sets a key to a specified byte array value. ##### Parameters - **key** (String) - Required - The name of the key to set. - **value** (byte[]) - Required - The byte array value to set for the key. ##### Response - **Success Response (200)** - (String) - OK response. ``` -------------------------------- ### PING Command Example Source: https://redis.github.io/lettuce/advanced-usage/custom-commands Demonstrates the creation of a `PING` command with a status output. ```java RedisCommand command = new Command<>(CommandType.PING, new StatusOutput<>(StringCodec.UTF8)); ``` -------------------------------- ### PING Command Output Example Source: https://redis.github.io/lettuce/advanced-usage/custom-commands Shows the creation of a `PING` command specifically for its status output. ```java Command command = new Command<>(CommandType.PING, new StatusOutput<>(StringCodec.UTF8)); ``` -------------------------------- ### Basic Redis Connection Setup Source: https://redis.github.io/lettuce/user-guide/redis-search Establishes a basic connection to a Redis instance using Lettuce. This is the initial step before interacting with Redis Search. ```java RedisURI redisURI = RedisURI.Builder.redis("localhost").withPort(6379).build(); RedisClient redisClient = RedisClient.create(redisURI); StatefulRedisConnection connection = redisClient.connect(); RediSearchCommands search = connection.sync(); ``` -------------------------------- ### Start Redis Version 8.6 Source: https://redis.github.io/lettuce/integration-testing Starts a Redis environment with a specific version using Docker Compose. Supported versions are listed in the documentation. ```bash make start version=8.6 ``` -------------------------------- ### Basic Async SET and GET with Blocking get() Source: https://redis.github.io/lettuce/user-guide/async-api Demonstrates basic asynchronous SET and GET operations. Results are retrieved using the blocking get() method, which throws an ExecutionException if an error occurs. ```java RedisAsyncCommands async = client.connect().async(); RedisFuture set = async.set("key", "value"); RedisFuture get = async.get("key"); set.get() == "OK" get.get() == "value" ``` -------------------------------- ### MixedCommands Interface Example Source: https://redis.github.io/lettuce/redis-command-interfaces Demonstrates defining Redis commands with custom annotations and parameter referencing using both index-based and name-based approaches. ```APIDOC ## MixedCommands Interface Example ### Description This interface shows how to define Redis commands using the `@Command` annotation. It illustrates both index-based (`?0`, `?1`) and name-based (`:key`, `:in`) parameter referencing. Parameters not explicitly referenced are appended as command arguments. ### Interface Definition ```java interface MixedCommands extends Commands { @Command("SET ?1 ?0") String set(String value, String key); @Command("NR.OBSERVE :key :in -> :out TRAIN") List nrObserve(@Param("key") String key, @Param("in") int[] in, @Param("out") int... out); } ``` ### Parameter Referencing - **Index-based**: `?0`, `?1`, ... (zero-based) - **Name-based**: `:key`, `:in`, ... (references parameter names, requires `javac -parameters` or `@Param` annotation) - **Unreferenced Parameters**: Appended as arguments after the last command segment. ``` -------------------------------- ### Obtain and Use Command Interface Instance Source: https://redis.github.io/lettuce/redis-command-interfaces Get a proxy instance of your command interface from the factory and use it to execute Redis commands. ```java public class SomeClient { KeyCommands commands; public SomeClient(RedisCommandFactory factory) { commands = factory.getCommands(KeyCommands.class); } public void doSomething() { String value = commands.get("Walter"); } } ``` -------------------------------- ### Configure RedisURI with Streaming Credentials Source: https://redis.github.io/lettuce/user-guide/connecting-redis This example demonstrates how to create a `RedisURI` using a streaming credentials provider and enable automatic re-authentication. It shows emitting initial credentials, setting `ClientOptions.ReauthenticateBehavior.ON_NEW_CREDENTIALS`, and connecting to Redis. ```java // Create a streaming credentials provider MyStreamingRedisCredentialsProvider streamingCredentialsProvider = new MyStreamingRedisCredentialsProvider(); // Emit initial credentials streamingCredentialsProvider.emitCredentials("testuser", "testpass".toCharArray()); // Enable automatic re-authentication ClientOptions clientOptions = ClientOptions.builder() // enable automatic re-authentication .reauthenticateBehavior(ClientOptions.ReauthenticateBehavior.ON_NEW_CREDENTIALS) .build(); // Create a RedisURI with streaming credentials provider RedisURI redisURI = RedisURI.builder().withHost(HOST).withPort(PORT) .withAuthentication(streamingCredentialsProvider) .build(); // RedisClient RedisClient redisClient = RedisClient.create(redisURI); rediscClient.connect().sync().ping(); // ... // Emit new credentials when needed streamingCredentialsProvider.emitCredentials("testuser", "password-rotated".toCharArray()); ``` -------------------------------- ### MixedCommands Interface Example Source: https://redis.github.io/lettuce/redis-command-interfaces This example demonstrates various uses of the @Command annotation within a Java interface for interacting with Redis. ```APIDOC ## CLIENT SETNAME ### Description Sets the name for the current client connection. ### Method Not explicitly defined, but implied by the Java method signature. ### Endpoint Not applicable (Redis command interface). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java redisClient.connect().sync().setName("my-client-name"); ``` ### Response #### Success Response - **String** (String) - Confirmation of the operation, typically OK. #### Response Example ``` OK ``` ## MGET ### Description Retrieves the values of multiple keys from Redis. ### Method Not explicitly defined, but implied by the Java method signature. ### Endpoint Not applicable (Redis command interface). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java redisClient.connect().sync().mgetAsValues("key1", "key2", "key3"); ``` ### Response #### Success Response - **List>** (List) - A list of values corresponding to the requested keys. Each value is wrapped in a `Value` object which may indicate if the key exists. #### Response Example ```json [ {"value": "value1"}, {"value": null}, {"value": "value3"} ] ``` ## SET mykey ### Description Sets the value of a specific key in Redis. The key is predefined as 'mykey'. ### Method Not explicitly defined, but implied by the Java method signature. ### Endpoint Not applicable (Redis command interface). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java redisClient.connect().sync().set("some-value"); ``` ### Response #### Success Response - **String** (String) - Confirmation of the operation, typically OK. #### Response Example ``` OK ``` ## NR.OBSERVE ?0 ?1 -> ?2 TRAIN ### Description Executes a custom Redis command for observing data, with specific parameters for input and output. ### Method Not explicitly defined, but implied by the Java method signature. ### Endpoint Not applicable (Redis command interface). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java redisClient.connect().sync().nrObserve("my-key", new int[]{1, 2}, new int[]{3, 4, 5}); ``` ### Response #### Success Response - **List** (List) - A list of integers representing the observed results. #### Response Example ```json [10, 20, 30] ``` ``` -------------------------------- ### Basic Redis Connection and Command Execution Source: https://redis.github.io/lettuce/user-guide/connecting-redis Demonstrates creating a Redis client, establishing a connection, executing a GET command, and closing the connection and client. This is the fundamental workflow for interacting with Redis. ```java RedisClient client = RedisClient.create("redis://localhost"); StatefulRedisConnection connection = client.connect(); RedisCommands commands = connection.sync(); String value = commands.get("foo"); ... connection.close(); client.shutdown(); ``` -------------------------------- ### Declare a Basic Command Interface Source: https://redis.github.io/lettuce/redis-command-interfaces Start by declaring an interface that extends Lettuce's `Commands` interface. ```java interface KeyCommands extends Commands { … } ``` -------------------------------- ### Basic Lettuce Setup for Vector Sets Source: https://redis.github.io/lettuce/user-guide/vector-sets Establishes a connection to a Redis instance using Lettuce, preparing for vector set operations. Ensure Redis is running on localhost:6379. ```java RedisURI redisURI = RedisURI.Builder.redis("localhost").withPort(6379).build(); RedisClient redisClient = RedisClient.create(redisURI); StatefulRedisConnection connection = redisClient.connect(); RedisVectorSetCommands vectorSet = connection.sync(); ``` -------------------------------- ### KeyCommands Interface Example Source: https://redis.github.io/lettuce/redis-command-interfaces Illustrates how to explicitly mark parameters as keys or values using the `@Key` and `@Value` annotations, which influences Redis Cluster routing and codec selection. ```APIDOC ## KeyCommands Interface Example ### Description This interface demonstrates the use of `@Key` and `@Value` annotations to explicitly identify key and value parameters. This is particularly important for Redis Cluster to determine command routing and for influencing `RedisCodec` selection. ### Interface Definition ```java interface KeyCommands extends Commands { String set(@Key String key, @Value String value); } ``` ### Annotations - **`@Key`**: Marks a parameter as a Redis key. - **`@Value`**: Marks a parameter as a Redis value. ### Influence - **Redis Cluster**: The first key parameter affects command routing. - **`RedisCodec`**: Hinting influences the selection of the appropriate codec for encoding/decoding. ``` -------------------------------- ### Redis Pub/Sub Subscription Source: https://redis.github.io/lettuce Example of setting up a connection for Pub/Sub messaging and subscribing to a channel using Lettuce's synchronous API. Requires a listener implementation. ```java RedisPubSubCommands connection = client.connectPubSub().sync(); connection.getStatefulConnection().addListener(new RedisPubSubListener() { ... }) connection.subscribe("channel"); ``` -------------------------------- ### Basic Synchronous Redis Usage Source: https://redis.github.io/lettuce Demonstrates how to connect to a Redis instance and perform a basic synchronous GET operation using Lettuce. Requires a running Redis instance on localhost. ```java RedisClient client = RedisClient.create("redis://localhost"); StatefulRedisConnection connection = client.connect(); RedisStringCommands sync = connection.sync(); String value = sync.get("key"); ``` -------------------------------- ### Building RedisURI with Password and Database Source: https://redis.github.io/lettuce/user-guide/connecting-redis Illustrates using the RedisURI.Builder to construct a Redis URI with a password and a specific database number. This is useful for more complex authentication and multi-database setups. ```java RedisURI redisUri = RedisURI.Builder.redis("localhost") .withPassword("authentication") .withDatabase(2) .build(); RedisClient client = RedisClient.create(redisUri); // … client.shutdown(); ``` -------------------------------- ### Hgetall with KeyValueStreamingChannel Source: https://redis.github.io/lettuce/advanced-usage/streaming-api Example of using KeyValueStreamingChannel to process key-value pairs from a Redis hash. Implement the onKeyValue method to handle each pair as it arrives. ```java Long count = redis.hgetall(new KeyValueStreamingChannel() { @Override public void onKeyValue(String key, String value) { ... } }, key); ``` -------------------------------- ### Configure Brave Tracing with ClientResources Source: https://redis.github.io/lettuce/advanced-usage/observability Configure Brave tracing by providing a Tracing instance, service name, and optional span customizers. This example excludes command arguments from span tags and customizes spans with the command type. ```java brave.Tracing clientTracing = …; BraveTracing tracing = BraveTracing.builder().tracing(clientTracing) .excludeCommandArgsFromSpanTags() .serviceName("custom-service-name-goes-here") .spanCustomizer((command, span) -> span.tag("cmd", command.getType().name())) .build(); ClientResources resources = ClientResources.builder().tracing(tracing).build(); ``` -------------------------------- ### Run Integration Tests Source: https://redis.github.io/lettuce/integration-testing Executes integration tests using Maven. Assumes the environment is already started. Integration tests are enabled by default when using this command. ```bash make test ``` -------------------------------- ### Create Redis Search Index with Filtering Source: https://redis.github.io/lettuce/user-guide/redis-search Configure an index to only include documents that match specific criteria using the `filter` option during index creation. This example indexes only active products. ```java // Index only documents matching certain criteria CreateArgs conditionalArgs = CreateArgs.builder() .on(CreateArgs.TargetType.HASH) .prefix("product:") .filter("@status=='active'") // Only index active products .build(); search.ftCreate("active-products-idx", conditionalArgs, fields); ``` -------------------------------- ### Configure Failover with Weighted Databases Source: https://redis.github.io/lettuce/advanced-usage/failover Configure a list of Redis databases with weights to enable automatic failover. Higher weights indicate higher priority. This example sets up 'redis-east' as primary and 'redis-west' as secondary. ```java import io.lettuce.core.RedisURI; import io.lettuce.core.failover.api.DatabaseConfig; import io.lettuce.core.failover.MultiDbClient; import io.lettuce.core.failover.api.MultiDbOptions; import io.lettuce.core.failover.api.StatefulRedisMultiDbConnection; import java.util.Arrays; // Configure databases with weights (higher weight = higher priority) // redis-east RedisURI eastUri = RedisURI.builder() .withHost("redis-east.example.com") .withPort(6379) .withPassword("secret".toCharArray()) .build(); DatabaseConfig east = DatabaseConfig.builder(eastUri) .weight(1.0f) // Primary database .build(); // redis-west RedisURI westUri = RedisURI.builder() .withHost("redis-west.example.com") .withPort(6379) .withPassword("secret".toCharArray()) .build(); DatabaseConfig west = DatabaseConfig.builder(westUri) .weight(0.5f) // Secondary database .build(); // Create the multi-database client MultiDbClient client = MultiDbClient.create(Arrays.asList(east, west)); // Connect and use like a regular Redis connection StatefulRedisMultiDbConnection connection = client.connect(); // Execute commands asynchronously - they go to the highest-weighted healthy database connection.async().set("key", "value"); String value = connection.async().get("key").get(); // Clean up connection.close(); client.shutdown(); ``` -------------------------------- ### Connect to Standalone Master/Replica Source: https://redis.github.io/lettuce/ha-sharding Establishes a connection to a standalone Master/Replica Redis setup. Ensure the RedisClient, Codec, and RedisURI are properly configured. The connection is closed and the client shut down afterward. ```java RedisClient redisClient = RedisClient.create(); StatefulRedisMasterReplicaConnection connection = MasterReplica.connect(redisClient, StringCodec.UTF8, RedisURI.create("redis://localhost")); connection.setReadFrom(ReadFrom.MASTER_PREFERRED); System.out.println("Connected to Redis"); connection.close(); redisClient.shutdown(); ``` -------------------------------- ### Connect to Static Master/Replica Topology Source: https://redis.github.io/lettuce/ha-sharding Establishes a connection to a Master/Replica setup with a predefined list of node addresses. This is useful for environments like AWS ElastiCache where topology discovery is not desired or possible. The connection needs to be re-established manually in case of failover. ```java RedisClient redisClient = RedisClient.create(); List nodes = Arrays.asList(RedisURI.create("redis://host1"), RedisURI.create("redis://host2"), RedisURI.create("redis://host3")); StatefulRedisMasterReplicaConnection connection = MasterReplica .connect(redisClient, StringCodec.UTF8, nodes); connection.setReadFrom(ReadFrom.MASTER_PREFERRED); System.out.println("Connected to Redis"); connection.close(); redisClient.shutdown(); ``` -------------------------------- ### Async SET and GET with Blocking await() and get() Source: https://redis.github.io/lettuce/user-guide/async-api Shows asynchronous SET and GET operations with explicit waiting using await() and timed get(). This allows for controlled blocking and retrieval of results. ```java RedisAsyncCommands async = client.connect().async(); RedisFuture set = async.set("key", "value"); RedisFuture get = async.get("key"); set.await(1, SECONDS) == true set.get() == "OK" get.get(1, TimeUnit.MINUTES) == "value" ``` -------------------------------- ### Configure ReadFrom in Redis Standalone Master/Replica Source: https://redis.github.io/lettuce/ha-sharding Connect to a static Master/Replica setup in Standalone mode and set the ReadFrom policy to REPLICA. This enables reading from replica nodes. The connection requires the master node's RedisURI. ```java RedisURI masterUri = RedisURI.Builder.redis("master-host", 6379).build(); RedisClient client = RedisClient.create(); StatefulRedisMasterReplicaConnection connection = MasterReplica.connect( client, StringCodec.UTF8, masterUri); connection.setReadFrom(ReadFrom.REPLICA); connection.sync().get("key"); // Replica read connection.close(); client.shutdown(); ``` -------------------------------- ### Subscribe to GET Operation (Anonymous Class) Source: https://redis.github.io/lettuce/user-guide/reactive-api Performs a GET operation and subscribes to the result using an anonymous inner class for handling the value. ```java commands.get("key").subscribe(new Consumer() { public void accept(String value) { System.out.println(value); } }); ``` -------------------------------- ### Set up RedisCommandFactory Source: https://redis.github.io/lettuce/redis-command-interfaces Instantiate `RedisCommandFactory` with a connected client to enable proxy creation for command interfaces. ```java RedisClient client = …; RedisCommandFactory factory = new RedisCommandFactory(client.connect()); ``` -------------------------------- ### Subscribe to GET Operation (Lambda) Source: https://redis.github.io/lettuce/user-guide/reactive-api Performs a GET operation and subscribes to the result using a Java 8 lambda expression for concise value handling. ```java commands .get("key") .subscribe(value -> System.out.println(value)); ``` -------------------------------- ### Command Naming Strategies Source: https://redis.github.io/lettuce/redis-command-interfaces Demonstrates different ways to map method names to Redis commands using annotations and naming strategies. ```java public interface MixedCommands extends Commands { List mget(String... keys); @Command("MGET") List> mgetAsValues(String... keys); @CommandNaming(strategy = DOT) double nrRun(String key, int... indexes); } ``` -------------------------------- ### Enable StartTLS on RedisURI Source: https://redis.github.io/lettuce/advanced-usage/ssl-connections Set the startTLS property to true on a RedisURI to enable StartTLS before establishing an SSL connection. ```java RedisURI redisUri = ... redisUri.setStartTls(true); ``` -------------------------------- ### Perform Redis GET operation asynchronously Source: https://redis.github.io/lettuce/user-guide/async-api Executes a Redis GET command asynchronously using the obtained RedisAsyncCommands interface. Returns a RedisFuture representing the result. ```java RedisFuture future = commands.get("key"); ``` -------------------------------- ### SET Command with Arguments Source: https://redis.github.io/lettuce/advanced-usage/custom-commands Illustrates creating a `SET` command with a key and value using `CommandArgs`. ```java StringCodec codec = StringCodec.UTF8; RedisCommand command = new Command<>(CommandType.SET, new StatusOutput<>(codec), new CommandArgs<>(codec) .addKey("key") .addValue("value")); ``` -------------------------------- ### Filter items starting with 'M' Source: https://redis.github.io/lettuce/user-guide/reactive-api Filters a Flux to emit only items that start with the letter 'M'. This is useful for selecting specific data based on string patterns before further processing. ```java Flux.just("Ben", "Michael", "Mark") .filter(s -> s.startsWith("M")) .flatMap(commands::get) .subscribe(value -> System.out.println("Got value: " + value)); ``` -------------------------------- ### Start Java Flight Recording Source: https://redis.github.io/lettuce/advanced-usage/events Record JFR events by starting your Java application with the specified JVM argument. This enables the collection of detailed Redis event data. ```shell java -XX:StartFlightRecording:filename=recording.jfr,duration=10s … ``` -------------------------------- ### Reactive Redis Operations Source: https://redis.github.io/lettuce Illustrates the use of Lettuce's reactive API with Project Reactor's Mono. It shows performing SET and GET operations and blocking for the result of the GET. ```java StatefulRedisConnection connection = client.connect(); RedisStringReactiveCommands reactive = connection.reactive(); Mono set = reactive.set("key", "value"); Mono get = reactive.get("key"); set.subscribe(); get.block() == "value" ``` -------------------------------- ### Using WATCH with Multi Source: https://redis.github.io/lettuce/user-guide/transactions-multi Demonstrates using WATCH to monitor a key. If the key changes before exec(), the transaction will fail, returning an empty list. ```Java redis.watch(key); RedisConnection redis2 = client.connect(); redis2.set(key, value + "X"); redis2.close(); redis.multi(); redis.append(key, "foo"); redis.exec(); // result is an empty list because of the changed key ``` -------------------------------- ### Managing Suggestions Source: https://redis.github.io/lettuce/user-guide/redis-search Get the size of a suggestion dictionary and delete specific suggestions. ```APIDOC ## Get Suggestion Dictionary Size ### Description Returns the number of terms in a suggestion dictionary. ### Method `search.ftSuglen(dictionaryName)` ### Parameters - **dictionaryName** (String) - Required - The name of the suggestion dictionary. ### Response Example ```json 1500 ``` ## Delete Suggestion ### Description Deletes a specific term from a suggestion dictionary. ### Method `search.ftSugdel(dictionaryName, term)` ### Parameters - **dictionaryName** (String) - Required - The name of the suggestion dictionary. - **term** (String) - Required - The suggestion term to delete. ### Response Example ```json true ``` ``` -------------------------------- ### HGETALL Command with Map Output Source: https://redis.github.io/lettuce/advanced-usage/custom-commands Demonstrates creating an `HGETALL` command that returns a map of strings. ```java StringCodec codec = StringCodec.UTF8; Command> command = new Command<>(CommandType.HGETALL, new MapOutput<>(codec), new CommandArgs<>(codec).addKey(key)); ``` -------------------------------- ### Invoke SET Command Source: https://redis.github.io/lettuce/redis-command-interfaces Example of invoking the SET command using the declared KeyCommands interface. ```java commands.set("key", "value"); ``` -------------------------------- ### Initialize Lettuce Redis Client Source: https://redis.github.io/lettuce/user-guide/async-api Establishes a connection to a Redis instance using RedisClient and obtains an asynchronous command interface. ```java RedisClient client = RedisClient.create("redis://localhost"); RedisAsyncCommands commands = client.connect().async(); ``` -------------------------------- ### Building Lettuce with Maven Source: https://redis.github.io/lettuce Command to build the Lettuce project using Apache Maven. This assumes you have cloned the repository and are in the project directory. ```bash $ make test ``` -------------------------------- ### Enable StartTLS during RedisURI Builder Source: https://redis.github.io/lettuce/advanced-usage/ssl-connections Configure a RedisURI using the builder pattern to enable StartTLS for the SSL connection. ```java RedisURI redisUri = RedisURI.Builder.redis(host(), sslPort()) .withSsl(true) .withStartTls(true) .build(); ``` -------------------------------- ### Manage Suggestion Dictionary Size and Entries Source: https://redis.github.io/lettuce/user-guide/redis-search Get the number of suggestions in a dictionary and delete specific suggestions. ```Java // Get suggestion dictionary size Long count = search.ftSuglen("autocomplete"); // Delete a suggestion Boolean deleted = search.ftSugdel("autocomplete", "old suggestion"); ``` -------------------------------- ### Getting Suggestions Source: https://redis.github.io/lettuce/user-guide/redis-search Retrieve suggestions from a dictionary based on a prefix, with options for fuzzy matching, limiting results, and including scores/payloads. ```APIDOC ## Get Suggestions ### Description Retrieves a list of suggestions from a dictionary that match a given prefix. Supports advanced options like fuzzy matching and including scores/payloads. ### Method `search.ftSugget(dictionaryName, prefix, [sugGetArgs])` ### Parameters - **dictionaryName** (String) - Required - The name of the suggestion dictionary. - **prefix** (String) - Required - The prefix to search for. - **sugGetArgs** (SugGetArgs) - Optional - Advanced arguments for retrieving suggestions. - `fuzzy()`: Enables fuzzy matching. - `max(Integer)`: Limits the number of suggestions returned. - `withScores()`: Includes the score for each suggestion. - `withPayloads()`: Includes the payload for each suggestion. ### Response Example ```json [ { "value": "wireless headphones", "score": 1.0, "payload": "category:electronics" } ] ``` ### Request Example ```java SugGetArgs getArgs = SugGetArgs.builder() .fuzzy() .max(5) .withScores() .withPayloads() .build(); List> results = search.ftSugget("autocomplete", "head", getArgs); ``` ``` -------------------------------- ### Get the last item from a Flux Source: https://redis.github.io/lettuce/user-guide/reactive-api Retrieves only the last emitted item from a Flux. This is useful when only the final result of a sequence is needed. ```java Flux.just("Ben", "Michael", "Mark") .last() .subscribe(value -> System.out.println("Got value: " + value)); ``` -------------------------------- ### Building Secure RedisURI with SSL, Password, and Database Source: https://redis.github.io/lettuce/user-guide/connecting-redis Demonstrates building a secure Redis URI using SSL, specifying a password, and selecting a database. This is essential for encrypted connections with authentication. ```java RedisURI redisUri = RedisURI.Builder.redis("localhost") .withSsl(true) .withPassword("authentication") .withDatabase(2) .build(); RedisClient client = RedisClient.create(redisUri); // … client.shutdown(); ``` -------------------------------- ### Basic Aggregation Source: https://redis.github.io/lettuce/user-guide/redis-search Perform a simple aggregation on an index without any complex pipeline operations. Useful for getting a count or basic summary. ```java // Simple aggregation without pipeline operations AggregationReply results = search.ftAggregate("products-idx", "*"); ``` -------------------------------- ### Declare KeyCommands Interface Source: https://redis.github.io/lettuce/redis-command-interfaces Define a Java interface extending Commands to declare Redis key-related operations like GET and SET. ```java public interface KeyCommands extends Commands { String get(String key); String set(String key, String value); String set(String key, byte[] value); } ``` -------------------------------- ### Choose Vector Set Quantization Types Source: https://redis.github.io/lettuce/user-guide/vector-sets Illustrates how to select different quantization types (NO_QUANTIZATION, Q8, BINARY) for vector additions based on precision, performance, and memory requirements. ```java public class VectorSetBestPractices { // 1. Use appropriate quantization for your use case public void chooseQuantization() { // High precision needed (scientific, financial) VAddArgs highPrecision = VAddArgs.Builder .quantizationType(QuantizationType.NO_QUANTIZATION) .build(); // Balanced performance (most applications) VAddArgs balanced = VAddArgs.Builder .quantizationType(QuantizationType.Q8) .build(); // Maximum speed/minimum memory (large scale) VAddArgs fast = VAddArgs.Builder .quantizationType(QuantizationType.BINARY) .build(); } // ... other methods ... } ``` -------------------------------- ### Execute Multiple Asynchronous Commands Source: https://redis.github.io/lettuce/user-guide/transactions-multi For asynchronous execution, chain RedisFuture objects. Results can be accessed via callbacks or blocking get(). ```Java redis.multi(); RedisFuture set1 = redis.set("one", "1"); RedisFuture set2 = redis.set("two", "2"); RedisFuture mget = redis.mget("one", "two"); RedisFuture llen = mgetredis.llen(key); set1.thenAccept(value -> …); // OK set2.thenAccept(value -> …); // OK RedisFuture> exec = redis.exec(); // result: list("OK", "OK", list("1", "2"), 0L) mget.get(); // list("1", "2") llen.thenAccept(value -> …); // 0L ``` -------------------------------- ### Explain Redis Search Query Plan Source: https://redis.github.io/lettuce/user-guide/redis-search Use `ftExplain` to understand how Redis Search executes a query. Supports basic and detailed explanations with dialect options. ```java // Basic query explanation String plan = search.ftExplain("products-idx", "@title:wireless"); ``` ```java // Detailed explanation with dialect ExplainArgs explainArgs = ExplainArgs.builder() .dialect(QueryDialects.DIALECT2) .build(); String detailedPlan = search.ftExplain("products-idx", "@title:wireless", explainArgs); System.out.println("Execution plan: " + detailedPlan); ``` -------------------------------- ### Create Redis Client and Reactive Commands Source: https://redis.github.io/lettuce/user-guide/reactive-api Initializes a Redis client and obtains reactive commands for String/String data types. ```java RedisClient client = RedisClient.create("redis://localhost"); RedisStringReactiveCommands commands = client.connect().reactive(); ``` -------------------------------- ### Block and Get Last Element Source: https://redis.github.io/lettuce/user-guide/reactive-api Converts a Flux to a single value using block(). Avoid this in production code as it negates non-blocking benefits. ```java String last = Flux.just("Ben", "Michael", "Mark").last().block(); System.out.println(last); ``` -------------------------------- ### Create and Use Basic Async Connection Pool Source: https://redis.github.io/lettuce/advanced-usage/connection-pooling Demonstrates creating a bounded asynchronous connection pool for standalone Redis and executing a transaction. Ensure pool initialization is awaited to prevent 'Pool exhausted' exceptions. Connections must be released after use. ```java RedisClient client = RedisClient.create(); CompletionStage>> poolFuture = AsyncConnectionPoolSupport.createBoundedObjectPoolAsync( () -> client.connectAsync(StringCodec.UTF8, RedisURI.create(host, port)), BoundedPoolConfig.create()); // await poolFuture initialization to avoid NoSuchElementException: Pool exhausted when starting your application // execute work CompletableFuture transactionResult = pool.acquire().thenCompose(connection -> { RedisAsyncCommands async = connection.async(); async.multi(); async.set("key", "value"); async.set("key2", "value2"); return async.exec().whenComplete((s, throwable) -> pool.release(connection)); }); // terminating pool.closeAsync(); // after pool completion client.shutdownAsync(); ``` -------------------------------- ### Configure DnsAddressResolverGroup Source: https://redis.github.io/lettuce/advanced-usage/client-resources Configure a custom DnsAddressResolverGroup for DNS resolution. This is useful for DNS-based Redis HA setups. Ensure that the dnsEventLoop is properly initialized. ```java new DnsAddressResolverGroup( new DnsNameResolverBuilder(dnsEventLoop) .channelType(NioDatagramChannel.class) .resolveCache(NoopDnsCache.INSTANCE) .cnameCache(NoopDnsCnameCache.INSTANCE) .authoritativeDnsServerCache(NoopAuthoritativeDnsServerCache.INSTANCE) .consolidateCacheSize(0) ); ``` -------------------------------- ### Basic Redis Connection and Operation Source: https://redis.github.io/lettuce/getting-started Demonstrates establishing a connection to a Redis server, performing a SET operation, and closing the connection. ```java RedisClient redisClient = RedisClient.create("redis://password@localhost:6379/0"); StatefulRedisConnection connection = redisClient.connect(); RedisCommands syncCommands = connection.sync(); syncCommands.set("key", "Hello, Redis!"); connection.close(); redisClient.shutdown(); ``` -------------------------------- ### Initialize RedisCommandFactory with Codecs Source: https://redis.github.io/lettuce/redis-command-interfaces Instantiates a RedisCommandFactory with a connection and a list of codecs, including ByteArrayCodec and StringCodec. This sets up the factory for encoding and decoding Redis data. ```java RedisCommandFactory factory = new RedisCommandFactory(connection, Arrays.asList(new ByteArrayCodec(), new StringCodec(LettuceCharsets.UTF8))); ``` -------------------------------- ### Get Random Elements from a Vector Set Source: https://redis.github.io/lettuce/user-guide/vector-sets Retrieves a specified number of random elements from a given vector set. This is useful for sampling or exploratory analysis. ```java // Get random elements from the vector set List randomElements = vectorSet.vrandmember("points", 3); System.out.println("Random elements: " + randomElements); ``` -------------------------------- ### Get the first item from a Flux Source: https://redis.github.io/lettuce/user-guide/reactive-api Retrieves the first emitted item from a Flux. This is the opposite of the `last()` operator and is used when only the initial element of a sequence is needed. ```java Flux.just("Ben", "Michael", "Mark") .next() .subscribe(value -> System.out.println("Got value: " + value)); ``` -------------------------------- ### Get Connection to a Specific Node Source: https://redis.github.io/lettuce/ha-sharding Retrieve a connection to a specific node within the cluster using its host and port. Note that this connection should not be closed independently. ```java RedisURI node1 = RedisURI.create("node1", 6379); RedisURI node2 = RedisURI.create("node2", 6379); RedisClusterClient clusterClient = RedisClusterClient.create(Arrays.asList(node1, node2)); StatefulRedisClusterConnection connection = clusterClient.connect(); RedisClusterCommands node1 = connection.getConnection("host", 7379).sync(); ... // do not close node1 connection.close(); clusterClient.shutdown(); ``` -------------------------------- ### Add and Remove Redis Databases Dynamically Source: https://redis.github.io/lettuce/advanced-usage/failover Demonstrates how to add a new database configuration and remove an existing one from a multi-database connection at runtime. ```java StatefulRedisMultiDbConnection connection = client.connect(); // Add a new database RedisURI newDb = RedisURI.create("redis://new-server:6379"); DatabaseConfig newConfig = DatabaseConfig.builder(newDb) .weight(0.8f) .build(); connection.addDatabase(newConfig); // Remove a database connection.removeDatabase(existingUri); ``` -------------------------------- ### Either-Or Chaining for Master-Replica Get Source: https://redis.github.io/lettuce/user-guide/async-api Consumes the value from the first future that completes between a master and replica Redis client. Useful for fast data retrieval. ```java RedisStringAsyncCommands master = masterClient.connect().async(); RedisStringAsyncCommands replica = replicaClient.connect().async(); RedisFuture future = master.get("key"); future.acceptEither(replica.get("key"), new Consumer() { @Override public void accept(String value) { System.out.println("Got value: " + value); } }); ``` -------------------------------- ### Redis Coroutines Commands Example Source: https://redis.github.io/lettuce/user-guide/kotlin-api Retrieve commands using the Coroutines API for asynchronous operations. Note that Coroutine Extensions are experimental and require opt-in. ```kotlin val api: RedisCoroutinesCommands = connection.coroutines() val foo1 = api.set("foo", "bar") val foo2 = api.keys("fo*") ``` -------------------------------- ### Create and Search Multiple Redis Search Indexes Source: https://redis.github.io/lettuce/user-guide/redis-search Demonstrates creating specialized indexes for different data types and performing separate searches on each, intended for later result aggregation. ```java // Create specialized indexes search.ftCreate("products-idx", productFields); search.ftCreate("reviews-idx", reviewFields); ``` ```java // Search each index separately and combine results SearchReply productResults = search.ftSearch("products-idx", "wireless"); SearchReply reviewResults = search.ftSearch("reviews-idx", "wireless"); // Combine and process results as needed ``` -------------------------------- ### Get Index Information and Statistics Source: https://redis.github.io/lettuce/user-guide/redis-search Retrieve statistics like document count and memory usage for a specific index. Also shows how to list all available indexes. ```Java // Get index information Map info = search.ftInfo("products-idx"); System.out.println("Index size: " + info.get("num_docs")); System.out.println("Index memory: " + info.get("inverted_sz_mb") + " MB"); // List all indexes List indexes = search.ftList(); ``` -------------------------------- ### Import Lettuce Core Classes Source: https://redis.github.io/lettuce/getting-started Import the necessary classes from the Lettuce core library to begin coding. ```java import io.lettuce.core.*; ``` -------------------------------- ### HKEYS Command with List Output Source: https://redis.github.io/lettuce/advanced-usage/custom-commands Illustrates creating an `HKEYS` command that returns a list of strings. ```java StringCodec codec = StringCodec.UTF8; Command> command = new Command<>(CommandType.HKEYS, new KeyListOutput<>(codec), new CommandArgs<>(codec).addKey(key)); ``` -------------------------------- ### Get Vector Set Information Source: https://redis.github.io/lettuce/user-guide/vector-sets Retrieve detailed metadata and graph structure links for a vector set. Useful for understanding the internal state of your vector data. ```java VectorMetadata metadata = vectorSet.vinfo("points"); System.out.println("Vector set metadata: " + metadata); List links = vectorSet.vlinks("points", "pt:A"); System.out.println("Graph links for pt:A: " + links); ``` -------------------------------- ### Set and Get JSON Attributes for an Element Source: https://redis.github.io/lettuce/user-guide/vector-sets Demonstrates how to set JSON-formatted attributes for a vector element, retrieve them, and clear them. Ensure the attribute string is valid JSON. ```java // Set JSON attributes for an element String attributes = "{\"category\": \"electronics\", \"price\": 299.99, \"brand\": \"TechCorp\"}"; Boolean attrSet = vectorSet.vsetattr("products", "item:1", attributes); // Get attributes for an element String retrievedAttrs = vectorSet.vgetattr("products", "item:1"); System.out.println("Attributes: " + retrievedAttrs); // Clear all attributes for an element Boolean cleared = vectorSet.vClearAttributes("products", "item:1"); ``` -------------------------------- ### Getting the Last Aggregated Value with last Source: https://redis.github.io/lettuce/user-guide/reactive-api Append the last() transformation after reduce to obtain the final aggregated result, such as the total count of elements in all Redis sets. ```java Flux.just("Ben", "Michael", "Mark") .flatMap(commands::scard) .reduce((sum, current) -> sum + current) .last() .subscribe(result -> System.out.println("Number of elements in sets: " + result)); ``` -------------------------------- ### Create Default Client Resources Source: https://redis.github.io/lettuce/advanced-usage/client-resources Use the create() factory method on DefaultClientResources to instantiate ClientResources with default settings. This is suitable for most common use cases. ```java ClientResources res = DefaultClientResources.create(); ``` -------------------------------- ### Chaining GET Operations Asynchronously Source: https://redis.github.io/lettuce/user-guide/reactive-api Loads multiple keys asynchronously using flatMap and subscribes to each value. Demonstrates non-blocking I/O handled by Netty EventLoop. ```java Flux.just("Ben", "Michael", "Mark"). flatMap(key -> commands.get(key)). subscribe(value -> System.out.println("Got value: " + value)); ``` -------------------------------- ### Dynamic and Re-entrant Aggregation Pipelines Source: https://redis.github.io/lettuce/user-guide/redis-search Demonstrates building aggregation pipelines where operations can be repeated and applied in any order, allowing for dynamic and re-entrant processing of data. ```java AggregateArgs complexPipeline = AggregateArgs.builder() // First transformation .apply("@price * @quantity", "total_value") // First filter .filter("@total_value > 100") // First grouping .groupBy(GroupBy.of("category") .reduce(Reducer.sum("@total_value").as("category_revenue"))) // First sort .sortBy("category_revenue", SortDirection.DESC) // Second transformation .apply("@category_revenue / 1000", "revenue_k") // Second filter .filter("@revenue_k > 5") // Second grouping (re-entrant) .groupBy(GroupBy.of("revenue_k") .reduce(Reducer.count().as("high_revenue_categories"))) // Second sort (re-entrant) .sortBy("high_revenue_categories", SortDirection.DESC) .build(); ``` -------------------------------- ### Create RedisURI by setting values directly Source: https://redis.github.io/lettuce/user-guide/connecting-redis Instantiate RedisURI by directly providing host, port, timeout, and time unit. ```java new RedisURI("localhost", 6379, 60, TimeUnit.SECONDS); ``` -------------------------------- ### Asynchronous Redis Operations Source: https://redis.github.io/lettuce Shows how to use the asynchronous API in Lettuce to perform SET and GET operations. It demonstrates awaiting the completion of multiple Redis futures. ```java StatefulRedisConnection connection = client.connect(); RedisStringAsyncCommands async = connection.async(); RedisFuture set = async.set("key", "value"); RedisFuture get = async.get("key"); LettuceFutures.awaitAll(set, get) == true set.get() == "OK" get.get() == "value" ```