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.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
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 SQL++ 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.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
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.retry.FailFastRetryStrategy
import com.couchbase.client.core.service.ServiceType
import com.couchbase.client.kotlin.Cluster
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 { security ->
            security
                .enableTls(true)
                .trustStore(
                    Paths.get("/path/to/truststore.jks"),
                    "password",
                    Optional.empty()
                )
        }
) 
   //sampleEnd
}

Types

Link copied to clipboard
object Companion

Functions

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

Opens the Bucket with the given name.

Link copied to clipboard
fun diagnostics(reportId: String = UUID.randomUUID().toString()): DiagnosticsResult

Generates a diagnostic report on the current state of the cluster from the SDKs point of view.

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

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

Link copied to clipboard
suspend fun ping(common: CommonOptions = CommonOptions.Default, services: Set<ServiceType> = emptySet(), reportId: String = UUID.randomUUID().toString()): PingResult

Pings the Couchbase cluster's global services. (To ping bucket-level services like KV as well, use Bucket.ping instead.)

Link copied to clipboard
fun query(statement: String, common: CommonOptions = CommonOptions.Default, parameters: QueryParameters = QueryParameters.None, @SinceCouchbase(value = "7.1") preserveExpiry: Boolean = false, 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>

fun query(statement: String, common: CommonOptions = CommonOptions.Default, parameters: QueryParameters = QueryParameters.None, @SinceCouchbase(value = "7.1") preserveExpiry: Boolean = false, 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(), @SinceCouchbase(value = "7.6") useReplica: Boolean? = null): Flow<QueryFlowItem>

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

Link copied to clipboard
fun search(indexName: String, spec: SearchSpec, common: CommonOptions = CommonOptions.Default, page: SearchPage = SearchPage.startAt(offset = 0), limit: Int? = null, sort: SearchSort = SearchSort.byScore(DESCENDING), fields: List<String> = emptyList(), facets: List<SearchFacet> = emptyList(), highlight: Highlight = Highlight.none(), includeLocations: Boolean = false, score: Score = Score.default(), explain: Boolean = false, @SinceCouchbase(value = "7.0") collections: List<String> = emptyList(), consistency: SearchScanConsistency = SearchScanConsistency.notBounded(), serializer: JsonSerializer? = null, raw: Map<String, Any?> = emptyMap()): Flow<SearchFlowItem>

Returns a Flow which can be collected to execute a Full-Text Search (vector, non-vector, or mixed-mode) against a cluster-level index.

Link copied to clipboard
fun searchQuery(indexName: String, query: SearchQuery, common: CommonOptions = CommonOptions.Default, page: SearchPage = SearchPage.startAt(offset = 0), limit: Int? = null, sort: SearchSort = SearchSort.byScore(DESCENDING), fields: List<String> = emptyList(), facets: List<SearchFacet> = emptyList(), highlight: Highlight = Highlight.none(), includeLocations: Boolean = false, score: Score = Score.default(), explain: Boolean = false, @SinceCouchbase(value = "7.0") collections: List<String> = emptyList(), consistency: SearchScanConsistency = SearchScanConsistency.notBounded(), serializer: JsonSerializer? = null, raw: Map<String, Any?> = emptyMap()): Flow<SearchFlowItem>

Returns a Flow which can be collected to execute a non-vector Full-Text Search query against a cluster-level index.

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.

Properties

Link copied to clipboard
val buckets: BucketManager

A manager for administering buckets (create, update, drop, flush, list, etc.)

Link copied to clipboard
@Stability.Volatile
val httpClient: CouchbaseHttpClient

An HTTP client for the Couchbase REST API.

Link copied to clipboard
val queryIndexes: QueryIndexManager

A manager for administering SQL++ indexes.

Link copied to clipboard
val searchIndexes: SearchIndexManager

A manager for administering cluster-level Full-Text Search indexes.

Link copied to clipboard
val users: UserManager

A manager for administering users (create, update, drop, etc.)