Cluster

class Cluster

Main entry point for interacting with a Couchbase Server cluster.

Start by calling one of the Cluster.connect factory methods. The sample code linked below should help get you off the ground quickly.

IMPORTANT: If you are connecting to a version of Couchbase Server prior to 6.5, you must open at least one bucket before doing cluster-level operations like query.

The connect and bucket methods return immediately; the actual work of opening sockets and loading bucket configuration happens asynchronously in the background. Your first requests after connecting might take longer than usual, since they need to wait for this background work to finish. If you want to wait explicitly instead, call the waitUntilReady method before issuing your first request.

When your application is ready to shut down, be sure to call disconnect. This gives any in-flight requests a chance to complete, avoiding undesired side-effects. Disconnecting the cluster also disconnects all Bucket and Collection objects acquired from the cluster.

If you are sharing a ClusterEnvironment between clusters, be sure to shut down the environment by calling ClusterEnvironment.shutdownSuspend (or one of its "shutdown*" cousins) after disconnecting the clusters.

Samples

import com.couchbase.client.core.env.NetworkResolution
import com.couchbase.client.core.env.SecurityConfig
import com.couchbase.client.core.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
import com.couchbase.client.kotlin.annotations.VolatileCouchbaseApi
import com.couchbase.client.kotlin.codec.RawJsonTranscoder
import com.couchbase.client.kotlin.env.ClusterEnvironment
import com.couchbase.client.kotlin.env.dsl.TrustSource
import com.couchbase.client.kotlin.query.execute
import kotlinx.coroutines.runBlocking
import java.nio.file.Paths
import java.util.*
import kotlin.time.Duration.Companion.seconds
fun main() { 
   //sampleStart 
   // Quickstart

// Assumes you have Couchbase running locally
// and the "travel-sample" sample bucket loaded.

// Connect and open a bucket
val cluster = Cluster.connect("127.0.0.1", "Administrator", "password")
try {
    val bucket = cluster.bucket("travel-sample")
    val collection = bucket.defaultCollection()

    runBlocking {
        // Perform a N1QL query
        val queryResult = cluster
            .query("select * from `travel-sample` limit 3")
            .execute()
        queryResult.rows.forEach { println(it) }
        println(queryResult.metadata)

        // Get a document from the K/V service
        val getResult = collection.get("airline_10")
        println(getResult)
        println(getResult.contentAs<Map<String, Any?>>())
    }
} finally {
    runBlocking { cluster.disconnect() }
} 
   //sampleEnd
}
import com.couchbase.client.core.env.NetworkResolution
import com.couchbase.client.core.env.SecurityConfig
import com.couchbase.client.core.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
import com.couchbase.client.kotlin.annotations.VolatileCouchbaseApi
import com.couchbase.client.kotlin.codec.RawJsonTranscoder
import com.couchbase.client.kotlin.env.ClusterEnvironment
import com.couchbase.client.kotlin.env.dsl.TrustSource
import com.couchbase.client.kotlin.query.execute
import kotlinx.coroutines.runBlocking
import java.nio.file.Paths
import java.util.*
import kotlin.time.Duration.Companion.seconds
fun main() { 
   //sampleStart 
   // Configure TLS using DSL
val cluster = Cluster.connect("localhost", "Administrator", "password") {
    security {
        enableTls = true

        // see TrustSource for more ways to specify trusted certificates
        trust = TrustSource.trustStore(
            Paths.get("/path/to/truststore.jks"),
            "password"
        )
    }
} 
   //sampleEnd
}
import com.couchbase.client.core.env.NetworkResolution
import com.couchbase.client.core.env.SecurityConfig
import com.couchbase.client.core.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
import com.couchbase.client.kotlin.annotations.VolatileCouchbaseApi
import com.couchbase.client.kotlin.codec.RawJsonTranscoder
import com.couchbase.client.kotlin.env.ClusterEnvironment
import com.couchbase.client.kotlin.env.dsl.TrustSource
import com.couchbase.client.kotlin.query.execute
import kotlinx.coroutines.runBlocking
import java.nio.file.Paths
import java.util.*
import kotlin.time.Duration.Companion.seconds
fun main() { 
   //sampleStart 
   // Configure TLS using builder

// connect() has overloads that accept ClusterEnvironment.Builder
// in case you don't want to use the cluster environment config DSL.
val cluster = Cluster.connect(
    "localhost", "Administrator", "password",
    ClusterEnvironment.builder()
        .securityConfig(
            SecurityConfig
                .enableTls(true)
                .trustStore(
                    Paths.get("/path/to/truststore.jks"),
                    "password",
                    Optional.empty()
                )
        )
) 
   //sampleEnd
}

Types

Companion
Link copied to clipboard
object Companion

Functions

analyticsQuery
Link copied to clipboard
fun analyticsQuery(statement: String, common: CommonOptions = CommonOptions.Default, parameters: AnalyticsParameters = AnalyticsParameters.None, serializer: JsonSerializer? = null, consistency: AnalyticsScanConsistency = AnalyticsScanConsistency.notBounded(), readonly: Boolean = false, priority: AnalyticsPriority = AnalyticsPriority.normal(), clientContextId: String? = UUID.randomUUID().toString(), raw: Map<String, Any?> = emptyMap()): Flow<AnalyticsFlowItem>
bucket
Link copied to clipboard
fun bucket(name: String): Bucket

Opens the Bucket with the given name.

disconnect
Link copied to clipboard
suspend fun disconnect(timeout: Duration = core.context().environment().timeoutConfig().disconnectTimeout().toKotlinDuration())

Gives any in-flight requests a chance to complete, then disposes of resources allocated to the cluster.

query
Link copied to clipboard
fun query(statement: String, common: CommonOptions = CommonOptions.Default, parameters: QueryParameters = QueryParameters.None, serializer: JsonSerializer? = null, consistency: QueryScanConsistency = QueryScanConsistency.notBounded(), readonly: Boolean = false, adhoc: Boolean = true, flexIndex: Boolean = false, metrics: Boolean = false, profile: QueryProfile = QueryProfile.OFF, maxParallelism: Int? = null, scanCap: Int? = null, pipelineBatch: Int? = null, pipelineCap: Int? = null, clientContextId: String? = UUID.randomUUID().toString(), raw: Map<String, Any?> = emptyMap()): Flow<QueryFlowItem>

Returns a Flow which may be collected to execute a cluster-level N1QL query and process the results.

waitUntilReady
Link copied to clipboard
suspend fun waitUntilReady(timeout: Duration, services: Set<ServiceType> = emptySet(), desiredState: ClusterState = ClusterState.ONLINE): Cluster

Waits until SDK bootstrap is complete and the desired ClusterState is observed.