### Getting Started with Couchbase Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc This section guides users through the initial steps of using the Couchbase Ruby SDK, including setting up the environment and performing basic operations. ```ruby require 'couchbase' # Connect to Couchbase options = { username: 'user', password: 'password', bucket: 'bucket-name' } cluster = Couchbase.connect(**options) # Access a bucket bucket = cluster.bucket('bucket-name') # Get a document collection = bucket.default_collection result = collection.get('document-id') puts result.value ``` -------------------------------- ### Install Couchbase Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc Command to install the Couchbase Ruby SDK using RubyGems. This is the primary method for obtaining the SDK package. ```console gem install couchbase ``` -------------------------------- ### Connect to Couchbase Capella Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc Example Ruby code for connecting to Couchbase Capella. This snippet demonstrates establishing a connection to a Couchbase cluster hosted on Couchbase Capella. ```ruby include::hello-world:example$cloud.rb[tags=**] ``` -------------------------------- ### Upserting and Getting a Document Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc This example shows how to create (upsert) a new document with specific content in a collection and then retrieve it. It highlights basic Key-Value operations. ```ruby result = collection.upsert("user::dustin", { "name" => "dustin", "email" => "dustin@example.com" }) puts "Upserted document with ID: #{result.id}" get_result = collection.get("user::dustin") puts "Retrieved document: #{get_result.content}" ``` -------------------------------- ### Connect to Local Couchbase Server Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc Example Ruby code for connecting to a local Couchbase Server instance. This snippet shows how to establish a connection to a self-hosted Couchbase cluster. ```ruby include::hello-world:example$start_using.rb[tags=**] ``` -------------------------------- ### Couchbase Ruby SDK Log Output Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/collecting-information-and-logging.adoc Provides an example of the detailed log output generated by the Couchbase Ruby SDK when running with a debug log level. This output includes initialization details, connection attempts, and configuration information. ```console [2020-09-07 14:30:26.311] [186383,186383] [info] 0ms, couchbase backend has been initialized: {:sdk=>"3.0.0.snapshot", :backend=>"0.5.0", :build_timestamp=>"2020-09-07 11:24:46", :revision=>"fa3ce49b6b142e2c2e6d03ab16d33b37da3f8c55", :platform=>"Linux-5.7.10-201.fc32.x86_64", :cpu=>"x86_64", :cc=>"GNU 10.2.1", :cxx=>"GNU 10.2.1", :ruby=>"2.7.0", :spdlog=>"1.6.0", :asio=>"1.16.1", :snappy=>"1.1.8", :http_parser=>"2.9.4", :openssl_headers=>"OpenSSL 1.1.1g FIPS 21 Apr 2020", :openssl_runtime=>"OpenSSL 1.1.1g FIPS 21 Apr 2020"} [2020-09-07 14:30:26.358] [186383,186390] [warning] 47ms, DNS SRV query returned 0 records for "localhost", assuming that cluster is listening this address [2020-09-07 14:30:26.358] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] attempt to establish MCBP connection [2020-09-07 14:30:26.359] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] connecting to ::1:11210 [2020-09-07 14:30:26.360] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] connected to ::1:11210 [2020-09-07 14:30:26.360] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] user_agent={"a":"ruby/0.5.0/fa3ce49b6b142e2c2e6d03ab16d33b37da3f8c55","i":"8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb"}, requested_features=[tcp_nodelay, mutation_seqno, xattr, xerror, select_bucket, snappy, json, duplex, clustermap_change_notification, unordered_execution, alt_request_support, tracing, sync_replication, vattr, collections] [2020-09-07 14:30:26.361] [186383,186390] [debug] 1ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] supported_features=[tcp_nodelay, mutation_seqno, xattr, xerror, select_bucket, snappy, json, duplex, clustermap_change_notification, unordered_execution, tracing, alt_request_support, sync_replication, collections, vattr] [2020-09-07 14:30:26.372] [186383,186390] [debug] 10ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] received new configuration: #]> [2020-09-07 14:30:26.372] [186383,186390] [info] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/d5a8f89d-8c9c-4253-f390-754ff8cdaeeb/-] detected network is "default" [2020-09-07 14:30:26.372] [186383,186383] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/9c6f61d7-b2f7-42c8-d507-b3af3fa3fe6c/default] attempt to establish MCBP connection [2020-09-07 14:30:26.372] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/9c6f61d7-b2f7-42c8-d507-b3af3fa3fe6c/default] connecting to ::1:11210 [2020-09-07 14:30:26.372] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/9c6f61d7-b2f7-42c8-d507-b3af3fa3fe6c/default] connected to ::1:11210 [2020-09-07 14:30:26.372] [186383,186390] [debug] 0ms, [plain/8447ccca-720c-4fd0-c49f-359487f4fbab/9c6f61d7-b2f7-42c8-d507-b3af3fa3fe6c/default] user_agent={"a":"ruby/0.5.0/fa3ce49b6b142e2c2e6d03ab16d33b37da3f8c55","i":"8447ccca-720c-4fd0-c49f-359487f4fbab/9c6f61d7-b2f7-42c8-d507-b3af3fa3fe6c"}, requested_features=[tcp_nodelay, mutation_seqno, xattr, xerror, select_bucket, snappy, json, duplex, clustermap_change_notification, unordered_execution, alt_request_support, tracing, sync_replication, vattr, collections] ``` -------------------------------- ### Importing the Couchbase SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc This snippet shows the necessary 'require' statement to import the Couchbase SDK at the beginning of your Ruby program. ```ruby require "couchbase" ``` -------------------------------- ### Accessing a Couchbase Bucket Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc After connecting to the cluster, this snippet illustrates how to access a specific bucket, which is necessary for performing operations on its data. ```ruby bucket = cluster.bucket("travel-sample") ``` -------------------------------- ### TLS Certificate Loading Message Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc An example log message indicating the loading of CA certificates from the Mozilla bundle, including the update date and SHA256 hash. This message appears with debug-level logging enabled. ```console loading 137 CA certificates from Mozilla bundle. Update date: "Tue Jan 10 04:12:06 2023 GMT", SHA256: "fb1ecd641d0a02c01bc9036d513cb658bbda62a75e246bedbc01764560a639f0" ``` -------------------------------- ### Example Connection String with Query Timeout Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ref/pages/client-settings.adoc Demonstrates how to set a custom query timeout using a connection string. ```ruby couchbase://localhost?query_timeout=10000 ``` -------------------------------- ### N1QL Queries with Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Provides examples of executing N1QL (SQL for JSON) queries against Couchbase using the Ruby SDK, including parameter binding. ```ruby # Execute a N1QL query query = Couchbase::N1qlQuery.new('SELECT name FROM `bucket-name` WHERE age > $1') result = bucket.execute(query, 25) result.rows.each do |row| puts row['name'] end ``` -------------------------------- ### Connecting to a Local Couchbase Server Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc Shows how to establish a connection to a local Couchbase Server instance using `couchbase://localhost`. For production, it recommends using `couchbases://` for secure connections. ```ruby cluster = Couchbase.connect("couchbase://localhost?username=Administrator&password=password") ``` -------------------------------- ### Connecting to Couchbase Capella Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc Demonstrates how to connect to Couchbase Capella using the `couchbases://` URI, which enables TLS by default. It also mentions the `wan_development` configuration profile for high-latency environments. ```ruby cluster = Couchbase.connect("couchbases://your-capella-domain.com?username=your-user&password=your-password") ``` -------------------------------- ### Couchbase Ruby SDK Initialization and Operation Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/collecting-information-and-logging.adoc Demonstrates connecting to a Couchbase cluster, accessing a bucket, scope, and collection, and performing an upsert operation. This is a basic usage example of the Ruby SDK. ```ruby require 'couchbase' cluster = Couchbase.Cluster.connect('couchbase://localhost', 'Administrator', 'password') cluster.bucket('travel-sample') .scope('inventory') .collection('airport') .upsert('foo', { 'bar' => 42 }) ``` -------------------------------- ### Connect to Couchbase Cluster Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc Establishes a connection to a Couchbase cluster using a connection string, username, and password. It demonstrates the basic setup for interacting with Couchbase. ```ruby require "couchbase" include Couchbase # to avoid repeating module name options = Cluster::ClusterOptions.new options.authenticate("Administrator", "password") cluster = Cluster.connect("couchbase://localhost", options) ``` -------------------------------- ### Simple Document Get Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/kv-operations.adoc Retrieves a complete document from Couchbase using its key with the `.get()` method. ```ruby result = collection.get("my_key") data = result.value ``` -------------------------------- ### Managing Connections in Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Guides users on how to establish, manage, and configure connections to a Couchbase cluster using the Ruby SDK, including connection pooling and timeouts. ```ruby # Connection options options = { username: 'admin', password: 'password', bucket: 'my-bucket', # Connection pooling settings pool_size: 10, pool_timeout: 5.0, # Other settings like TLS, timeouts etc. connect_timeout: 10.0 } cluster = Couchbase.connect(**options) # Ensure the cluster connection is closed when done # cluster.close ``` -------------------------------- ### Executing a N1QL Query Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc This snippet demonstrates how to execute a N1QL query at the scope level. It shows querying the `airline` collection within the `inventory` scope of the `travel-sample` bucket. ```ruby rows = bucket.scope("inventory").query("SELECT airline.name FROM `travel-sample`.inventory.airline WHERE airline.iataCode = $1", "AA") rows.each do |row| puts "Airline name: #{row['name']}" end ``` -------------------------------- ### Disconnecting from Couchbase Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc This code snippet shows how to properly close the connection to the Couchbase cluster, releasing resources. It's recommended to do this when your application finishes its operations. ```ruby cluster.disconnect() ``` -------------------------------- ### Key-Value Operations in Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Demonstrates fundamental Key-Value (KV) operations such as getting, inserting, upserting, and removing documents using the Couchbase Ruby SDK. ```ruby # Insert a document collection.insert('new-doc-id', {'name' => 'Alice', 'age' => 30}) # Upsert a document (insert or update) collection.upsert('existing-doc-id', {'name' => 'Bob', 'age' => 25}) # Remove a document collection.remove('doc-to-remove-id') ``` -------------------------------- ### Retrieving Couchbase Bucket Settings Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/provisioning-cluster-resources.adoc This example shows how to retrieve the settings of an existing Couchbase bucket using the BucketManager. It fetches the bucket's configuration and prints specific details like its name, type, and flush status. ```ruby require 'couchbase' include Couchbase::Management # Connect to Couchbase cluster = Couchbase.connect(username: "Administrator", password: "password", hosts: ["127.0.0.1"]) # Get the BucketManager bucket_manager = cluster.buckets # Get bucket settings begin settings = bucket_manager.get_bucket("my_new_bucket") puts "Bucket Name: #{settings.name}" puts "Bucket Type: #{settings.bucket_type}" puts "Flush Enabled: #{settings.flush_enabled}" rescue Error::BucketNotFound => e puts "Bucket 'my_new_bucket' not found: #{e.message}" rescue => e puts "Error retrieving bucket settings: #{e.message}" end ``` -------------------------------- ### Accessing a Collection within a Scope Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/start-using-sdk.adoc This code demonstrates how to access a specific collection (`users`) within a scope (`tenant_agent_00`) in the `travel-sample` bucket. This is a prerequisite for document operations. ```ruby collection = bucket.scope("tenant_agent_00").collection("users") ``` -------------------------------- ### Couchbase Server TLS Certificate Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc A sample of a Couchbase Server TLS certificate, typically copied from the admin UI. This certificate is used for manual TLS configuration on the client side. ```text -----BEGIN CERTIFICATE----- MIICmDCCAYKgAwIBAgIIE4FSjsc3nyIwCwYJKoZIhvcNAQEFMAwxCjAIBgNVBAMT ASowHhcNMTMwMTAxMDAwMDAwWhcNNDkxMjMxMjM1OTU5WjAMMQowCAYDVQQDEwEq ``` -------------------------------- ### TLS Encryption Setup Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc Enables TLS encryption by connecting to a cluster using the 'couchbases://' protocol and providing the path to the certificate file via the 'trust_certificate' parameter in the connection string. ```ruby require "couchbase" options = Couchbase::Cluster::ClusterOptions.new options.certificates("/path/to/your/certificate.pem") cluster = Couchbase.connect("couchbases://localhost?trust_certificate=true", options) ``` -------------------------------- ### Durability Observed Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/kv-operations.adoc Demonstrates client-verified durability for older Couchbase Server versions (prior to 6.5). The SDK polls replicas until the requested durability level is achieved. ```ruby collection.upsert("my_key", {"value" => "some data"}, durability: :client_verified) ``` -------------------------------- ### Analytics Data Definition Language (DDL) Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/analytics-using-sdk.adoc Provides an example of creating an analytics dataset using N1QL, linking it to a specific collection within a bucket. This is a prerequisite for running analytics queries on structured data. ```n1ql CREATE DATASET `airports-collection` ON `travel-sample`.inventory.airport; ``` -------------------------------- ### Couchbase Ruby SDK Management APIs Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/provisioning-cluster-resources.adoc Provides links to the API guides for various management functionalities within the Couchbase Ruby SDK, including BucketManager, UserManager, QueryIndexManager, AnalyticsIndexManager, SearchIndexManager, CollectionManager, and ViewIndexManager. ```APIDOC BucketManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/BucketManager.html Description: Manages buckets within the Couchbase cluster. UserManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/UserManager.html Description: Manages users and their permissions. QueryIndexManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/QueryIndexManager.html Description: Manages N1QL query indexes. AnalyticsIndexManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/AnalyticsIndexManager.html Description: Manages Analytics indexes. SearchIndexManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/SearchIndexManager.html Description: Manages FTS (Full-Text Search) indexes. CollectionManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/CollectionManager.html Description: Manages scopes and collections. ViewIndexManager: URL: https://docs.couchbase.com/sdk-api/couchbase-ruby-client/Couchbase/Management/ViewIndexManager.html Description: Manages design documents and views. ``` -------------------------------- ### Get Couchbase Build Information Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc Retrieves metadata about the Couchbase C++ client's bundled CA certificates and OpenSSL configuration. This is useful for understanding the SDK's TLS capabilities and certificate sources. ```console $ ruby -r couchbase -e 'pp Couchbase::BUILD_INFO[:cxx_client].select{|k, _| k =~ /^(mozilla|openssl_default)/}' ``` ```ruby { :mozilla_ca_bundle_date=>"Tue Jan 10 04:12:06 2023 GMT", :mozilla_ca_bundle_embedded=>true, :mozilla_ca_bundle_sha256=>"fb1ecd641d0a02c01bc9036d513cb658bbda62a75e246bedbc01764560a639f0", :mozilla_ca_bundle_size=>137, :openssl_default_cert_dir=>"/etc/pki/tls/certs", :openssl_default_cert_dir_env=>"SSL_CERT_DIR", :openssl_default_cert_file=>"/etc/pki/tls/cert.pem", :openssl_default_cert_file_env=>"SSL_CERT_FILE" } ``` -------------------------------- ### Creating a Scope in Couchbase Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/provisioning-cluster-resources.adoc This example demonstrates how to create a new scope within a Couchbase bucket using the CollectionManager. It requires a bucket instance and the name of the scope to be created. Proper permissions are necessary for this operation. ```ruby require 'couchbase' # Assuming 'bucket' is an established Couchbase::Bucket object. scope_name = "my_new_scope" begin bucket.collections.create_scope(scope_name) puts "Scope '#{scope_name}' created successfully." rescue Error::ScopeExists => e puts "Scope '#{scope_name}' already exists: #{e.message}" rescue => e puts "Error creating scope '#{scope_name}': #{e.message}" end ``` -------------------------------- ### Scan Consistency Query Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/n1ql-queries-with-sdk.adoc Demonstrates how to use the 'request_plus' scan consistency option for queries in the Couchbase Ruby SDK. This ensures that all document changes and index updates are processed before the query runs, prioritizing consistency over performance. ```ruby require "couchbase" options = Couchbase::Options::Query.new options.scan_consistency = :request_plus result = bucket.query("SELECT count(*) FROM `travel-sample`", options) puts "Query result: #{result.rows}" ``` -------------------------------- ### Gson Deserialization Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Demonstrates deserializing data using Gson, a popular Java library for JSON processing. This snippet is part of the transcoding examples. ```java String json = "{\"name\": \"John Doe\", \"age\": 30}"; User user = gson.fromJson(json, User.class); ``` -------------------------------- ### Get with Projections (Lookup) Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/concept-docs/pages/documents.adoc Retrieves specific parts of a document using the 'get with projections' feature in the Couchbase Ruby SDK. This offers an alternative to sub-document lookups for retrieving specific fields. ```ruby include::example$documents.rb[tag=lookup-in-projections] ``` -------------------------------- ### Document Get with Field Filtering Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/kv-operations.adoc Retrieves a document and then filters on specific fields within the returned data. ```ruby result = collection.get("my_key") data = result.value filtered_value = data["field_to_filter"] ``` -------------------------------- ### Creating a Couchbase Bucket Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/provisioning-cluster-resources.adoc This example demonstrates how to create a new bucket in Couchbase using the BucketManager. It includes setting various bucket properties such as the bucket name, memory allocation, replica count, and flushability. The BucketSettings class is used to configure these properties. ```ruby require 'couchbase' include Couchbase::Management # Connect to Couchbase cluster = Couchbase.connect(username: "Administrator", password: "password", hosts: ["127.0.0.1"]) # Get the BucketManager bucket_manager = cluster.buckets # Define bucket settings bucket_settings = BucketSettings.new bucket_settings.name = "my_new_bucket" bucket_settings.memory_allocation = 100 # MB bucket_settings.num_replicas = 1 bucket_settings.flush_enabled = true # Create the bucket begin bucket_manager.create_bucket(bucket_settings) puts "Bucket 'my_new_bucket' created successfully." rescue Error::BucketExists => e puts "Bucket 'my_new_bucket' already exists: #{e.message}" rescue => e puts "Error creating bucket: #{e.message}" end ``` -------------------------------- ### Example Document for Path Mismatch Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/subdocument-operations.adoc A JSON document containing an array, used to illustrate a path mismatch scenario. ```json { "tags": [ "reno", "nevada", "west", "sierra" ] } ``` -------------------------------- ### Deferred Index Creation and Building (SQL) Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/concept-docs/pages/n1ql-query.adoc Shows how to create deferred indexes using SQL syntax, which allows for background building. The `BUILD INDEX` statement is then used to initiate the index construction process for specified indexes. ```sql CREATE PRIMARY INDEX ON `travel-sample` WITH {"defer_build": true}; CREATE INDEX ix_name ON `travel-sample`(name) WITH {"defer_build": true}; CREATE INDEX ix_email ON `travel-sample`(email) WITH {"defer_build": true}; BUILD INDEX ON `travel-sample`("#primary", "ix_name", "ix_email"); ``` -------------------------------- ### REST API Documentation Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/hello-world/pages/sample-application.adoc Provides access to the REST API documentation for the Travel Sample Application. This can be explored in read-only mode or directly from the running application at the `/apidocs` endpoint. ```APIDOC swagger_ui::https://raw.githubusercontent.com/couchbaselabs/try-cb-ruby/7.0/swagger.json[] ``` -------------------------------- ### Example Document with Array Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/subdocument-operations.adoc A JSON document containing an array, used to illustrate path syntax for accessing array elements. ```json { "some": { "array": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] } } ``` -------------------------------- ### Custom Gson Deserialization Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Shows how to use a custom Gson serializer for deserializing data from Couchbase into objects. ```java GsonSerializer gsonSerializer = new GsonSerializer(); byte[] data = ... // data retrieved from Couchbase MyObject obj = gsonSerializer.deserialize(data, new TypeRef() {}); ``` -------------------------------- ### Accessing Data with a User Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/sdk-user-management-example.adoc Illustrates how to use a previously created user's credentials to connect to Couchbase and access data. This highlights the practical application of user management for data operations. ```ruby options = { username: "testuser", password: "password", // ... other connection options } cluster = Couchbase.connect(**options) # Now you can interact with the cluster using the authenticated user ``` -------------------------------- ### Handling Durability Ambiguous Errors Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/error-handling.adoc Provides an example of how to handle `DurabilityAmbiguous` errors, which can occur when the durability requirements for an operation are not met. ```ruby begin # Operation with durability requirements bucket.insert("my_key", { "content": "data" }, durability: :majority) rescue Couchbase::Error::DurabilityAmbiguous => e puts "Durability ambiguous: #{e.message}" end ``` -------------------------------- ### Example Document with Special Characters in Path Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/subdocument-operations.adoc A JSON document demonstrating paths with literal quotes and brackets, requiring specific escaping. ```json { "literal\"quote": { "array": [] } } ``` ```json { "literal[]bracket": { "literal.dot": true } } ``` -------------------------------- ### Creating Users Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/sdk-user-management-example.adoc Demonstrates how to create new users within the Couchbase system using the UserManager API. This typically involves specifying a username, password, and associated roles. ```ruby user_manager.upsert_user( Couchbase::Management::User.new( username: "testuser", password: "password", roles: [Couchbase::Management::Role.new(name: "data_reader", bucket: "mybucket")] ) ) ``` -------------------------------- ### Deferred Index Management via SDK (Ruby) Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/concept-docs/pages/n1ql-query.adoc Illustrates the creation and management of deferred indexes using the Couchbase Ruby SDK. It includes creating primary and field indexes with deferral, building them, and then watching for their completion. ```ruby manager = cluster.query_indexes options = Management::QueryIndexManager::CreatePrimaryIndexOptions.new options.defer = true manager.create_primary_index("travel-sample", options); options = Management::QueryIndexManager::CreateIndexOptions.new options.defer = true manager.create_index("travel-sample", "ix_name", ["name"], options); manager.create_index("travel-sample", "ix_email", ["email"], options); manager.build_deferred_indexes("travel-sample") manager.watch_indexes("travel-sample", ["ix_name", "ix_email", "#primary"], 2_000) # wait for 2 seconds ``` -------------------------------- ### Creating a MessagePack Serializer Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Provides an example of creating a custom serializer for MessagePack, a binary serialization format, for use with Couchbase. ```java import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import java.io.ByteArrayOutputStream; import java.io.IOException; public class MessagePackSerializer implements JsonSerializer { @Override public byte[] serialize(Object object) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker packer = MessagePack.newDefaultPacker(out); // Logic to pack the object using MessagePack // Example: packer.packString(object.toString()); packer.close(); return out.toByteArray(); } @Override public T deserialize(byte[] bytes, TypeRef typeRef) throws IOException { // Logic to unpack the data using MessagePack // This part would typically involve a MessageUnpacker throw new UnsupportedOperationException("Deserialization not implemented for MessagePack"); } } ``` -------------------------------- ### N1QL SELECT Statement Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/concept-docs/pages/documents.adoc Retrieves documents from Couchbase using N1QL. Examples show fetching entire documents by ID and by a specific field. ```sql SELECT * FROM `travel-sample`.inventory.airport USE KEYS ["airport_1254"]; SELECT * FROM `travel-sample`.inventory.airport WHERE META().id = "airport_1254"; ``` -------------------------------- ### Client Settings in Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Details the various client settings and configuration options available in the Couchbase Ruby SDK, covering connection, security, and operational parameters. ```ruby # Common client settings: options = { username: 'user', password: 'password', bucket: 'bucket-name', # TLS/SSL settings ssl: true, # Connection timeouts connect_timeout: 5000, # Operation timeouts operation_timeout: 2500, # Keep-alive settings keep_alive_interval: 30000 } cluster = Couchbase.connect(**options) ``` -------------------------------- ### Get and Touch Document Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/kv-operations.adoc Fetches a document and simultaneously updates its expiry field. Useful for extending the lifetime of frequently accessed documents. ```ruby result = collection.get_and_touch("my_key", expiry: 7200) # Update expiry to 2 hours ``` -------------------------------- ### Ruby API Reference Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Provides a link to the official API reference documentation for the Couchbase Ruby SDK, detailing all classes, methods, and their usage. ```ruby https://docs.couchbase.com/sdk-api/couchbase-ruby-client/ ``` -------------------------------- ### Custom Gson Serialization Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Demonstrates how to use a custom Gson serializer for encoding objects into JSON format for Couchbase storage. ```java GsonSerializer gsonSerializer = new GsonSerializer(); MyObject obj = new MyObject("value"); byte[] data = gsonSerializer.serialize(obj); ``` -------------------------------- ### Gson Serialization Example Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Demonstrates how to use `RawJsonTranscoder` with Google Gson for JSON serialization and deserialization, avoiding default Jackson processing. ```java ClusterEnvironment env = ClusterEnvironment.builder() .transcoder(RawJsonTranscoder.INSTANCE) .serializer(new GsonSerializer()) .build(); Cluster cluster = Cluster.connect("couchbase://localhost", "username", "password", ClusterOptions.clusterOptions(env)); // ... use cluster ... // On retrieval, the raw JSON bytes are returned as a String // without further deserialization by the SDK's default transcoder. ``` -------------------------------- ### N1QL UPDATE Statement Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/concept-docs/pages/documents.adoc Updates documents in Couchbase using the N1QL query language. This example shows how to modify a specific field based on a condition. ```sql UPDATE `travel-sample`.inventory.airline SET sale_price = msrp * 0.75 WHERE msrp < 19.95; ``` -------------------------------- ### View Queries with Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Demonstrates how to query Couchbase Views using the Ruby SDK, including designing and executing view queries. ```ruby # Execute a View query view_query = Couchbase::ViewQuery.new('design_doc', 'view_name') view_result = bucket.execute(view_query) view_result.rows.each do |row| puts row end ``` -------------------------------- ### Get Document Expiry Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/kv-operations.adoc Retrieves a document and also requests its expiry time. The expiry time is returned as a `Time` object representing absolute time. ```ruby result = collection.get("my_key", with_exp: true) expiry_time = result.expiry_time ``` -------------------------------- ### Listing Scopes and Collections Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/provisioning-cluster-resources.adoc Demonstrates how to enumerate Scopes and Collections using the `CollectionManager.get_all_scopes()` method and the `Scope.collections` property in the Ruby SDK. ```ruby require 'couchbase' # Assuming 'cluster' is an initialized Couchbase Cluster object # Get the CollectionManager collection_manager = cluster.collections # Get all scopes all_scopes = collection_manager.get_all_scopes # Iterate through scopes and their collections all_scopes.each do |scope| puts "Scope: #{scope.name}" scope.collections.each do |collection| puts " Collection: #{collection.name}" end end ``` -------------------------------- ### Full-Text Searching with Ruby SDK Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/ROOT/nav.adoc Illustrates how to perform full-text searches (FTS) using the Couchbase Ruby SDK, including creating and executing search queries. ```ruby # Perform a full-text search search_request = Couchbase::SearchRequest.new('my-index', 'search term') search_result = cluster.search('bucket-name', search_request) search_result.rows.each do |row| puts row['id'] end ``` -------------------------------- ### DNS SRV Bootstrapping Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/managing-connections.adoc Enables DNS SRV bootstrapping in the Ruby SDK (version 3.0 and later) by passing the hostname from DNS SRV records to the SDK. If DNS SRV records fail to load, a warning is logged, and the provided hostname is used for A record lookup. ```ruby require "couchbase" cluster = Couchbase.connect("couchbase://example.com") ``` -------------------------------- ### Creating a Custom Gson Serializer Source: https://github.com/couchbase/docs-sdk-ruby/blob/release/3.4/modules/howtos/pages/transcoders-nonjson.adoc Provides an example of implementing a custom Gson serializer by implementing the JsonSerializer interface. This allows for custom JSON serialization logic. ```java public class GsonSerializer implements JsonSerializer { private final Gson gson = new Gson(); @Override public byte[] serialize(Object object) { return gson.toJson(object).getBytes(StandardCharsets.UTF_8); } @Override public T deserialize(byte[] bytes, TypeRef typeRef) { String json = new String(bytes, StandardCharsets.UTF_8); return gson.fromJson(json, typeRef.type()); } } ```