### Client Settings Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc Example demonstrating how to configure client settings, including compression options. ```APIDOC ## Compression Options ### Description The client can optionally compress documents before sending them to Couchbase Server. .Template for configuring CompressionExample settings [source,java] ---- include::devguide:example$java/ClientSettingsExample.java[tag=client_settings_9,indent=0] ---- [[compression.enable]] ==== Enabling Compression ``` -------------------------------- ### SDK 3 Connection Lifecycle Example (Simple Get) Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Demonstrates the SDK 3 approach where `bucket()` returns immediately, and operations are handled transparently even if the bucket is not fully open yet. Error handling is consolidated at the operation level. ```java Cluster cluster = Cluster.connect("couchbase://localhost", "user", "password"); // Get a reference to the bucket. This returns immediately. Bucket bucket = cluster.bucket("travel-sample"); // Get a reference to the collection. This also returns immediately. Collection collection = bucket.defaultCollection(); // Perform a GET operation. The SDK handles waiting for the bucket/collection if needed. try { GetResult getResult = collection.get("some-document-id"); System.out.println(getResult.content()); } catch (DocumentNotFoundException | TimeoutException e) { // Handle exceptions like document not found or operation timeout System.err.println("Error getting document: " + e.getMessage()); } // Disconnect when done // cluster.disconnect(); ``` -------------------------------- ### Micrometer Prometheus Registry Setup Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/observability-metrics.adoc Example of creating a Micrometer Prometheus registry and passing it to the SDK for metrics integration. This sets up an HTTP server for Prometheus scraping. ```java include::devguide:example$java/MetricsMicrometer.java[tag=metrics-micrometer-prometheus,indent=0] ``` -------------------------------- ### Clone the Quickstart Project Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/sample-application.adoc Clone the Java Spring Boot quickstart project from GitHub to begin building your REST API. ```bash git clone https://github.com/couchbase-examples/java-springboot-quickstart.git ``` -------------------------------- ### Simple SQL++ Query (Local Server) Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc Example of executing a simple SQL++ query against a local Couchbase Server instance, requiring the Travel Sample Bucket to be installed. ```java include::devguide:example$java/SimpleQuery.java[tag=class,indent=0] ``` -------------------------------- ### Install Java using SDKMAN! Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/platform-help.adoc Use this command to install a specific version of Java via SDKMAN!. You may be prompted to set this version as the default. ```bash $ sdk install java 23.0.2-oracle ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/sample-application.adoc Change your current directory to the root of the cloned quickstart project. ```bash cd java-springboot-quickstart ``` -------------------------------- ### Configure Compression Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc This example demonstrates how to configure compression settings for the client. ```java ClusterEnvironment env = ClusterEnvironment.builder() .compressionConfig(CompressionConfig.enableMax(1024)) .build(); Cluster cluster = Cluster.connect(connectionString, ClusterOptions.clusterOptions(username, password).environment(env)); ``` -------------------------------- ### SDK 2 Search Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc This is an example of a search query in SDK 2. It demonstrates how to construct a basic search query with a limit and specified fields. ```java // SDK 2 search query SearchQueryResult searchResult = bucket.query(new SearchQuery( "indexname", SearchQuery.queryString("airports")).limit(5).fields("a", "b", "c"), 2, TimeUnit.SECONDS ); for (SearchQueryRow row : searchResult.hits()) { // ... } ``` -------------------------------- ### Install Maven Dependencies Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/student-record-developer-tutorial.adoc Run this command in your project's root directory to download and install all the dependencies defined in your pom.xml file. This is necessary after modifying the pom.xml. ```bash mvn install ``` -------------------------------- ### SDK 2 View Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc This is an example of a view query in SDK 2. It shows how to query a view with limit and skip parameters, and iterate over the results. ```java // SDK 2 view query ViewResult query = bucket.query( ViewQuery.from("design", "view").limit(5).skip(2), 10, TimeUnit.SECONDS ); for (ViewRow row : query) { // ... } ``` -------------------------------- ### CouchbaseQueue Usage Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Provides an example of using CouchbaseQueue, which implements Queue and does not allow null values. ```java CouchbaseQueue queue = new CouchbaseQueue<>(); queue.offer("task1"); queue.offer("task2"); // queue.offer(null); // This would throw NullPointerException System.out.println(queue.poll()); System.out.println(queue.poll()); ``` -------------------------------- ### Install Project Dependencies with Maven Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/sample-application.adoc Install the application's dependencies using Maven. The `-DskipTests=true` option is used to bypass tests that require the application to be running. ```bash mvn clean install -DskipTests=true ``` -------------------------------- ### Configure Client Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc This example demonstrates how to configure various client settings, including I/O options, using the ClusterEnvironment builder. ```java ClusterEnvironment env = ClusterEnvironment.builder() .securityConfig(config -> config.enableNativeTls(true)) .securityConfig(config -> config.trustCertificate(Path.of("/path/to/certificate.pem"))) .ioConfig(config -> config.enableDnsSrv(true)) .ioConfig(config -> config.mutationTokensEnabled(true)) .build(); ``` -------------------------------- ### SDK 2 Connection Lifecycle Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Illustrates the traditional connection, bucket opening, KV operation, and disconnection pattern used in SDK 2. ```java try { // Connect to cluster Cluster cluster = CouchbaseCluster.create("127.0.0.1"); // Open bucket Bucket bucket = cluster.openBucket("travel-sample"); // Perform KV operation // ... // Disconnect bucket.close(); cluster.disconnect(); } catch (Exception e) { // Handle exception } ``` -------------------------------- ### Simple SQL++ Query (Couchbase Capella) Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc Example of executing a simple SQL++ query against Couchbase Capella, requiring the Travel Sample Bucket. ```java include::devguide:example$java/SimpleQueryCloud.java[tag=class,indent=0] ``` -------------------------------- ### Streaming SQL++ Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/sdk-release-notes.adoc Use queryStreaming methods to process query result rows as they arrive from the server without using the Reactive API. This example prints each row's content. ```java clusterOrScope.queryStreaming( "select 'hello' as greeting", row -> System.out.println(row.contentAsObject()) ); ``` -------------------------------- ### Sample Course Records JSON Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/student-record-developer-tutorial.adoc Example JSON output representing course records retrieved from Couchbase. ```json [ { "course-name": "art history", "credit-points": 100, "faculty": "fine art" }, { "course-name": "fine art", "credit-points": 50, "faculty": "fine art" }, { "course-name": "graphic design", "credit-points": 200, "faculty": "media and communication" } ] ``` -------------------------------- ### CouchbaseArraySet Usage Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Shows how to use CouchbaseArraySet, which implements Set and allows null values. ```java CouchbaseArraySet set = new CouchbaseArraySet<>(); set.add("element1"); set.add(null); set.add("element2"); set.add("element1"); // Duplicate, will be ignored System.out.println(set.contains("element1")); System.out.println(set.contains(null)); System.out.println(set.size()); ``` -------------------------------- ### Connect to Bucket and Scope for Querying Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc Before querying at the scope level, you need to connect to the specific bucket and scope. This setup is required for scope-level queries. ```java Cluster cluster = Cluster.connect(connectionString, username, password); Bucket bucket = cluster.bucket("travel-sample"); Scope scope = bucket.scope("inventory"); ``` -------------------------------- ### SDK 3 Analytics Simple Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Demonstrates how to perform a simple analytics query in SDK 3. The `analyticsQuery` method is now at the `Cluster` level. ```java AnalyticsResult result = cluster.analyticsQuery(AnalyticsQuery.simple("select * from foo")); ``` -------------------------------- ### Parameterized Vector Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/vector-searching-with-sdk.adoc Shows how to parameterize a vector query for potential Query Plan reuse and efficiency. This is similar to parameterizing regular N1QL queries. ```java Cluster cluster = Cluster.connect(connectionString, username, password); String searchVector = "[0.1, 0.2, 0.3, 0.4, 0.5]"; SearchRequest request = SearchRequest.builder() .vectorSearch( VectorSearch.builder() .field("vector_field") .vector(searchVector) .k(3) .build() ) .build(); // Parameterize the query QueryOptions options = QueryOptions.queryOptions() .parameter("vector_param", searchVector) .search(request); QueryResult result = cluster.query("SELECT * FROM `travel-sample` WHERE META().id LIKE 'hotel_%' AND VECTOR_SEARCH(vector_field, $vector_param, {k: 3})", options); for (SearchResult row : result.rows()) { System.out.println(row.fields()); } cluster.disconnect(); ``` -------------------------------- ### CouchbaseMap Usage Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Demonstrates the basic usage of CouchbaseMap, which implements Map and allows null values but not null keys. ```java CouchbaseMap map = new CouchbaseMap<>(); map.put("key1", "value1"); map.put("key2", null); System.out.println(map.get("key1")); System.out.println(map.get("key2")); ``` -------------------------------- ### CouchbaseArrayList Usage Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Illustrates the usage of CouchbaseArrayList, which implements List and permits null values. ```java CouchbaseArrayList list = new CouchbaseArrayList<>(); list.add("item1"); list.add(null); list.add("item2"); System.out.println(list.get(0)); System.out.println(list.get(1)); System.out.println(list.get(2)); ``` -------------------------------- ### Connect with Username and Password (Full RBAC Configuration) Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Provides the full configuration for RBAC authentication, allowing explicit authenticator setup. ```java PasswordAuthenticator authenticator = PasswordAuthenticator.create("user", "password"); Cluster cluster = Cluster.connect("couchbase://localhost", authenticator); ``` -------------------------------- ### Connect to Couchbase Capella Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/start-using-sdk.adoc Connect to your Couchbase Capella cluster using the provided connection details. This snippet is part of the complete Hello World example. ```java Cluster cluster = Cluster.connect("couchbase://your-ip-address?ssl=true", "your-username", "your-password"); Bucket bucket = cluster.bucket("your-bucket"); Collection collection = bucket.defaultCollection(); ``` -------------------------------- ### SDK 3 View Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc This snippet demonstrates how to perform a view query in SDK 3, migrating from SDK 2. It highlights the use of `ViewScanConsistency` for staleness. ```java include::devguide:example$java/Migrating.java[tag=viewquery,indent=0] ``` -------------------------------- ### Configure Log4j 2 Output Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/collecting-information-and-logging.adoc This example log4j2.xml configuration directs messages to the console and sets logging levels for the Couchbase SDK and other components. ```xml ``` -------------------------------- ### Vector Search Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/full-text-searching-with-sdk.adoc Demonstrates how to perform a single vector query using the SDK, which is supported from Couchbase Server 7.6 onwards. ```APIDOC ## Vector Search As of Couchbase Server 7.6, the Search Service supports vector search in addition to traditional search queries. ### Single Vector Query Example This example demonstrates performing a single vector query: ```java // Assume SearchRequest, VectorSearch, VectorQuery are imported // Assume 'vector_field' is the name of the document field containing embedded vectors // Assume the vector data is available as a float array float[] vectorData = { ... }; // Populate with actual vector data SearchRequest request = SearchRequest.builder() .withVectorSearch( VectorSearch.fromQuery( VectorQuery.builder("vector_field", vectorData).build() ) ) .build(); // Execute the search request using Cluster.searchQuery() or Scope.search() ``` **Explanation:** - A `SearchRequest` can contain both traditional `SearchQuery` and `VectorSearch` components. - `VectorSearch` allows for one or more `VectorQuery` objects. - A `VectorQuery` specifies the document field containing the vectors (e.g., `"vector_field"`) and the vector data itself as a `float[]`. ``` -------------------------------- ### Get Dependency Versions Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/sdk-release-notes.adoc Use grep to find the versions of specific dependencies in the project's pom.xml files. ```bash src=../couchbase-jvm-clients grep '' $src/pom.xml grep '' $src/pom.xml echo tracing-opentelemetry ; grep '' $src/tracing-opentelemetry/pom.xml | head -2 | tail -1 ; grep '' $src/pom.xml echo tracing-opentracing ; grep '' $src/tracing-opentracing/pom.xml | head -2 | tail -1 ; grep '' $src/tracing-opentracing/pom.xml echo metrics-opentelemetry ; grep '' $src/metrics-opentelemetry/pom.xml | head -2 | tail -1 ; grep '' $src/pom.xml echo metrics-micrometer ; grep '' $src/metrics-micrometer/pom.xml | head -2 | tail -1 ; grep '' $src/pom.xml ``` -------------------------------- ### Get Security Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/managing-connections.adoc Retrieve the current security settings for a self-managed Couchbase Server installation, including available cipher suites. ```bash /opt/couchbase/bin/couchbase-cli setting-security -c localhost -u Administrator -p password --get ``` -------------------------------- ### Run Java Application to Retrieve Records Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/student-record-developer-tutorial.adoc This console command executes a Java application that retrieves course records. It requires Maven to be installed and configured. ```console mvn exec:java -Dexec.mainClass="ArtSchoolRetriever" -Dexec.cleanupDaemonThreads=false ``` -------------------------------- ### Handling Non-Transactional Writes Concurrently Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Illustrates how to handle potential conflicts when non-transactional writes occur concurrently with transactional operations on the same document. This example shows the setup for detecting and overriding such writes. ```java { // tag::concurrency[] // Perform a non-transactional write collection.upsert("myKey", JsonObject.create().put("name", "overridden value")); // Attempt a transactional operation that might conflict transactions.insert("myBucket", "myKey", JsonObject.create().put("name", "transactional value")); // end::concurrency[] } ``` -------------------------------- ### Configure Client Settings with Environment Options Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/sdk-release-notes.adoc Demonstrates the recommended approach for configuring client settings, such as KV timeouts, using the `ClusterOptions` and `Environment` builders. This replaces deprecated static builder methods. ```java Cluster cluster = Cluster.connect( connectionString, ClusterOptions.clusterOptions(username, password) .environment(env -> env .timeoutConfig(timeout -> timeout .kvTimeout(Duration.ofSeconds(3)) ) ) ); ``` -------------------------------- ### Example ThresholdLoggingTracer JSON Output Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/observability-tracing.adoc This is an example of the JSON blob emitted by the ThresholdLoggingTracer, showing details of slow Key/Value operations. ```json [ { "top":[ { "operation_name":"GetRequest", "server_us":2, "last_local_id":"E64FED2600000001/00000000EA6B514E", "last_local_address":"127.0.0.1:51807", "last_remote_address":"127.0.0.1:11210", "last_dispatch_us":2748, "last_operation_id":"0x9", "total_us":324653 }, { "operation_name":"GetRequest", "server_us":0, "last_local_id":"E64FED2600000001/00000000EA6B514E", "last_local_address":"127.0.0.1:51807", "last_remote_address":"127.0.0.1:11210", "last_dispatch_us":1916, "last_operation_id":"0x1b692", "total_us":2007 } ], "service":"kv", "count":2 } ] ``` -------------------------------- ### Execute a Basic SQL++ Query Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc Demonstrates how to execute a simple SQL++ query using the SDK. Ensure you have a `Cluster` object initialized. ```java Cluster cluster = Cluster.connect(connectionString, username, password); // Use the default bucket Bucket bucket = cluster.bucket("travel-sample"); // Use the default scope Scope scope = bucket.scope("inventory"); // Execute a query QueryResult result = scope.query("SELECT " + ""name"" FROM `travel-sample`.inventory.airline WHERE iataCode = \"AA\""); // Process the results for (Row row : result.rows()) { System.out.println(row.toMap()); } cluster.disconnect(); ``` -------------------------------- ### Configure Environment via Connection String Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Demonstrates configuring the SDK environment directly within the connection string. This is a concise way to apply specific settings during cluster connection. ```java Cluster cluster = Cluster.connect("couchbase://localhost?com.couchbase.env.timeout.kvTimeout=5s&com.couchbase.env.io.tcpKeepAlive=true", "user", "password"); ``` -------------------------------- ### SDK 2 Query Error Handling Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc In SDK 2, you needed to manually check the query result for errors. This example shows the older approach. ```java N1qlQueryResult result = cluster.query("SELECT count(*) FROM `travel-sample`"); if (!result.errors().isEmpty()) { // errors contain [{"msg":"syntax error - at end of input","code":1000}] } ``` -------------------------------- ### Single Vector Search Query Example Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/vector-searching-with-sdk.adoc Performs a single vector query using the Search Service. This example demonstrates creating a SearchRequest with a VectorSearch component. ```java Cluster cluster = Cluster.connect(connectionString, username, password); // Vector embeddings can be an array of floats or a base64 encoded string. String searchVector = "[0.1, 0.2, 0.3, 0.4, 0.5]"; SearchRequest request = SearchRequest.builder() .vectorSearch( VectorSearch.builder() .field("vector_field") .vector(searchVector) .k(3) .build()) .build(); QueryResult result = cluster.search("my_index", request); for (SearchResult row : result.rows()) { System.out.println(row.fields()); } cluster.disconnect(); ``` -------------------------------- ### Run Java Application with Maven Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/student-record-developer-tutorial.adoc This command executes the `AddEnrollments` Java class using Maven. It's used after compiling and installing dependencies with `mvn install`. ```sh mvn exec:java -Dexec.mainClass="AddEnrollments" -Dexec.cleanupDaemonThreads=false ``` -------------------------------- ### Create a Bucket Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/provisioning-cluster-resources.adoc Use the BucketSettings object to define the parameters for a new bucket and then create it using the BucketManager. ```java BucketSettings bucketSettings = BucketSettings.create("hello"); bucketSettings.ramQuotaMB(100); bucketSettings.numReplicas(1); bucketSettings.bucketType(BucketType.COUCHBASE); bucketManager.createBucket(bucketSettings); ``` -------------------------------- ### Configure and Run a Single Query Transaction Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/transactions-single-query.adoc This example demonstrates how to configure transaction options, such as durability levels, before executing a single query transaction. Adjust settings based on your consistency and performance needs. ```java TransactionConfig config = new TransactionConfig().durabilityLevel(DurabilityLevel.MAJORITY); try (Transaction transaction = transactions.beginAsync(config).block()) { transaction.query(bucketName, "SELECT 1").block(); transaction.commit().block(); } catch (Exception e) { // Handle exception } ``` -------------------------------- ### Get List Element by Index in Couchbase Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Retrieves an item from a list by its index. A PathNotFoundException is thrown if the index is out of range. Use -1 to get the last element. ```java listGet(index); ``` -------------------------------- ### Full Error Handling Example for Transactions Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/transactions-error-handling.adoc A comprehensive example demonstrating best practices for handling various errors during Couchbase transactions, including retries and specific error types. ```java Cluster cluster = Cluster.connect("couchbase://localhost", "user", "password"); // Configure transaction options TransactionConfig.Builder txnConfigBuilder = TransactionConfig.builder() .expiration(Duration.ofSeconds(15)); // Set expiration to 15 seconds // Use a try-with-resources block for automatic cleanup try (Transaction transaction = cluster.transactions().beginשית(txnConfigBuilder.build())) { // Perform operations within the transaction // ... your transaction logic here ... // Commit the transaction transaction.commit(); } catch (TransactionCommitAmbiguousException e) { // The commit was attempted, but its outcome is unknown. The transaction might have committed or failed. // The SDK will automatically retry the transaction if possible. System.err.println("Transaction commit ambiguous: " + e.getMessage()); // Consider logging or alerting here. } catch (TransactionFailedException e) { // The transaction failed and could not be committed. // The SDK will automatically retry the transaction if possible. System.err.println("Transaction failed: " + e.getMessage()); // Consider logging or alerting here. } catch (Exception e) { // Handle other potential exceptions during transaction execution System.err.println("An unexpected error occurred: " + e.getMessage()); // Consider logging or alerting here. } // Close the cluster connection when done cluster.disconnect(); ``` -------------------------------- ### Configure Environment via System Properties Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Shows how to configure the Couchbase SDK environment using system properties. This allows for flexible, external configuration of various settings. ```java System.setProperty("com.couchbase.env.timeout.kvTimeout", "5s"); System.setProperty("com.couchbase.env.io.tcpKeepAlive", "true"); Cluster cluster = Cluster.connect("couchbase://localhost", "user", "password"); ``` -------------------------------- ### ParsingFailedException Example with Error Context Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc This example demonstrates the structure of a ParsingFailedException, including the detailed error context provided by the SDK when a query has invalid syntax. The context includes error codes, messages, and request details. ```java Exception in thread "main" com.couchbase.client.core.error.ParsingFailedException: Parsing of the input failed {"completed":true,"coreId":1,"errors":[{"code":3000,"message":"syntax error - at from"}],"idempotent":false,"lastDispatchedFrom":"127.0.0.1:62253","lastDispatchedTo":"127.0.0.1:8093","requestId":3,"requestType":"QueryRequest","retried":11,"retryReasons":["ENDPOINT_TEMPORARILY_NOT_AVAILABLE","BUCKET_OPEN_IN_PROGRESS"],"service":{"operationId":"9111b961-e585-42f2-9cab-e1501da7a40b","statement":"select 1= from","type":"query"},"timeoutMs":75000,"timings":{"dispatchMicros":15599,"totalMicros":1641134}} ``` -------------------------------- ### Create Cluster with Custom Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc Use the `ClusterEnvironment.Builder` to configure custom client settings and then create a cluster instance. ```java ClusterEnvironment env = ClusterEnvironment.builder() .timeoutConfig(TimeoutConfig.kvTimeout(Duration.ofSeconds(10))) .build(); Cluster cluster = Cluster.connect("localhost", ClusterOptions.clusterOptions(username, password).environment(env)); ``` -------------------------------- ### Get Replica from Preferred Server Group with Transactions Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/data-durability-acid-transactions.adoc Demonstrates how to attempt to read a document from a preferred server group within a transaction. If the document is unretrievable from the preferred group, it falls back to a regular get operation. ```java cluster.transactions().run((ctx) -> { TransactionGetResult getResult; try { getResult = ctx.getReplicaFromPreferredServerGroup(collection, id); } catch (DocumentUnretrievableException err) { getResult = ctx.get(collection, id); } }); ``` -------------------------------- ### Execute a Simple Reactive SQL++ Query Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc This example shows how to execute a SQL++ query using the reactive API, which streams results as they become available and supports backpressure. ```java ReactiveCluster reactiveCluster = ReactiveCluster.connect(connectionString, username, password); reactiveCluster.query("SELECT " + ""name"" FROM `travel-sample`.inventory.airline WHERE iataCode = \"AA\"") .flatMapMany(result -> result.rows()) .subscribe( row -> System.out.println(row.toMap()), error -> System.err.println("Error: " + error), () -> System.out.println("Query finished") ); // Give the reactive stream time to complete Thread.sleep(5000); reactiveCluster.disconnect(); ``` -------------------------------- ### Getting a User Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/management-api.adoc Retrieves an existing user by their ID. ```APIDOC ## Getting a User ### Description Retrieves an existing user by their ID. ### Method Signature User getUser (String userid) ### Parameters #### Path Parameters - **userid** (String) - Required - The ID of the user to retrieve. ### Returns - **User** - An object containing the user's details (name, id, domain, roles). ``` -------------------------------- ### Get ViewIndexManager Instance Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/provisioning-cluster-resources.adoc Obtain an instance of ViewIndexManager to perform operations on design documents. ```java ViewIndexManager viewIndexManager = cluster.viewIndexes(); ``` -------------------------------- ### Configure Client Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc Use this template to configure general client settings directly on the ClusterEnvironment.Builder. ```java ClusterEnvironment env = ClusterEnvironment.builder() .compressionConfig(config -> config.enable(true).minSize(1024).minRatio(0.5)) .retryStrategy(BestEffortRetryStrategy.INSTANCE) .build(); ``` -------------------------------- ### Get Bucket Manager Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/provisioning-cluster-resources.adoc Instantiate the BucketManager interface through the Cluster.buckets() method to manage buckets. ```java Cluster cluster = Cluster.connect(connectionString, username, password); BucketManager bucketManager = cluster.buckets(); ``` -------------------------------- ### Basic XATTR Operations Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/xattr.adoc Demonstrates basic operations for getting and setting extended attributes. ```java String upsertJson = "{\"name\": \"widget\", \"color\": \"red\"}"; // Upsert a document with extended attributes MutationResult upsertResult = collection.mutateIn("doc1") .upsert("name", "widget") .upsert("color", "red") .execute(); // Get a document with extended attributes GetResult getResult = collection.get("doc1"); // Access extended attributes System.out.println("Name: " + getResult.content("name").toString()); System.out.println("Color: " + getResult.content("color").toString()); // Remove an extended attribute collection.mutateIn("doc1") .remove("color") .execute(); ``` -------------------------------- ### Simple N1QL Query in SDK 2 vs SDK 3 Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Illustrates the difference in executing a simple N1QL query. SDK 3 moves query options to a dedicated options object. ```java // SDK 2 simple query N1qlQueryResult queryResult = bucket.query(N1qlQuery.simple("select * from `travel-sample` limit 10")); for (N1qlQueryRow row : queryResult) { JsonObject value = row.value(); // ... } ``` ```java import com.couchbase.client.java.query.QueryOptions; // SDK 3 simple query QueryResult queryResult = collection.query("select * from `travel-sample` limit 10", QueryOptions.queryOptions()); for (Row row : queryResult) { JsonObject value = row.contentAs(JsonObject.class); // ... } ``` -------------------------------- ### Execute a Full-Text Search Query Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/full-text-searching-with-sdk.adoc This snippet demonstrates how to execute a basic full-text search query using the SDK. Ensure you have a Search index configured. ```java try { SearchQuery sq = SearchQuery.newBuilder("{\"query\": {\"match\": {\"content\": \"the quick brown fox\"}}}") .build(); SearchPager pager = cluster.searchQuery("travel-sample", sq); while (pager.hasNext()) { SearchRow row = pager.next(); System.out.println(row.id()); } } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Accessing Query Results as JsonObject Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/sqlpp-queries-with-sdk.adoc Example of how to retrieve and process query results as JsonObject instances. ```java include::devguide:example$java/Queries.java[tag=rowsasobject,indent=0] ``` -------------------------------- ### Get Document with Expiry Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/kv-operations.adoc Retrieve a document and its expiry information by setting the `withExpiry` option to true. ```java Bucket bucket = cluster.bucket("myBucket"); Collection collection = bucket.defaultCollection(); // Get document and its expiry GetResult getResult = collection.get("myDoc", GetOptions.getOptions().withExpiry(true)); System.out.println("Document Expiry: " + getResult.expiry()); ``` -------------------------------- ### Get JSON as Person Object Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/json.adoc Retrieve JSON data directly as a strongly-typed Java object. ```java Person person = result.contentAs(Person.class); System.out.println(person.name); System.out.println(person.age); ``` -------------------------------- ### Execute N1QL Query in SDK 3.x Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Example of executing a N1QL query using the SDK 3.x API. This shows the structure for query execution and handling results. ```java N1qlQueryResult result = n1qlBucket.query( N1qlQuery.simple("SELECT count(*) FROM `travel-sample`") ); for (N1qlQueryRow row : result) { // Process row } ``` -------------------------------- ### Configure via System Property Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc Configure client settings using Java system properties. These properties take precedence over connection string parameters and builder settings. ```java System.setProperty("com.couchbase.env.timeout.kvTimeout", "10s"); System.setProperty("com.couchbase.env.timeout.queryTimeout", "15s"); Cluster cluster = Cluster.connect("localhost", ClusterOptions.clusterOptions(username, password)); ``` -------------------------------- ### Get User Method Signature Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/management-api.adoc Signature for the method used to retrieve an existing user by their ID. ```java User getUser (String userid) ``` -------------------------------- ### Run Java Application with Parameters to Retrieve Records Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/hello-world/pages/student-record-developer-tutorial.adoc This console command executes a Java application that retrieves course records based on specified parameters. It requires Maven to be installed and configured. ```console mvn exec:java -Dexec.mainClass="ArtSchoolRetrieverParameters" -Dexec.cleanupDaemonThreads=false ``` -------------------------------- ### Fetch Key-Value Document in SDK 3.x Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/project-docs/pages/migrating-sdk-code-to-3.n.adoc Example of fetching a key-value document using the SDK 3.x API. This demonstrates the new Result object returned instead of the old Document class. ```java try { GetResult result = kvBucket.get("my_key", JsonDocument.class); // Process result } catch (DocumentNotFoundException e) { // Handle missing document } ``` -------------------------------- ### Retrieve Documents with N1QL Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/concept-docs/pages/documents.adoc These N1QL examples demonstrate how to retrieve documents using either their keys or by specifying a WHERE clause. This is useful for fetching specific documents or sets of documents. ```sql SELECT * FROM `travel-sample`.inventory.airport USE KEYS ["airport_1254"]; ``` ```sql SELECT * FROM `travel-sample`.inventory.airport WHERE META().id = "airport_1254"; ``` -------------------------------- ### Get and Touch Document Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/kv-operations.adoc Fetch a document while simultaneously updating its expiry field using the `getAndTouch` operation. ```java Bucket bucket = cluster.bucket("myBucket"); Collection collection = bucket.defaultCollection(); // Get document and update its expiry to 1 hour from now TouchResult touchResult = collection.getAndTouch("myDoc", Duration.ofHours(1))); System.out.println("New Document Expiry: " + touchResult.expiry()); ``` -------------------------------- ### Configure Timeouts and I/O Settings Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/client-settings.adoc Configure nested settings like timeouts and I/O using their respective builders, accessed via the main `ClusterEnvironment.Builder`. ```java ClusterEnvironment env = ClusterEnvironment.builder() .timeoutConfig(TimeoutConfig.kvTimeout(Duration.ofSeconds(10))) .ioConfig(IoConfig.numKvConnections(10)) .build(); ``` -------------------------------- ### Prometheus Configuration for OpenTelemetry Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/observability-metrics.adoc Configure Prometheus to scrape metrics from the OpenTelemetry Collector. This setup is for local testing. ```yaml scrape_configs: - job_name: 'otel-collector' scrape_interval: 1s static_configs: - targets: ['otel:10000'] labels: group: 'production' ``` -------------------------------- ### Explicit ClusterEnvironment Configuration Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Demonstrates how to explicitly create and manage a `ClusterEnvironment` for configuring transactions globally when creating a `Cluster` instance. This provides fine-grained control over transaction settings. ```java { // tag::config[] ClusterEnvironment env = ClusterEnvironment.builder() .transactionsConfig(TransactionsConfig.defaultConfig()) .build(); Cluster cluster = Cluster.connect("couchbase://localhost", ClusterOptions.clusterOptions(username, password).environment(env)); // end::config[] } ``` -------------------------------- ### Log Successful Transaction Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/howtos/pages/distributed-acid-transactions-from-the-sdk.adoc Log successful transactions to track their completion. This example shows how to log a successful transaction. ```java cluster.transactions().run((Action) ctx -> { // ... operations ... return TransactionResult.success(); }); // Log successful transaction logger.info("Transaction completed successfully."); ``` -------------------------------- ### Get Item from Map in Couchbase Source: https://github.com/couchbase/docs-sdk-java/blob/release/3.12/modules/ref/pages/data-structures.adoc Retrieves an item from a map using its key. A PathNotFoundException is raised if the key does not exist. ```java mapGet(key); ```