Class Cluster

java.lang.Object
com.couchbase.client.java.Cluster
All Implemented Interfaces:
Closeable, AutoCloseable

public class Cluster extends Object implements Closeable
The Cluster is the main entry point when connecting to a Couchbase cluster.

Most likely you want to start out by using the connect(String, String, String) entry point. For more advanced options you want to use the connect(String, ClusterOptions) method. The entry point that allows overriding the seed nodes (connect(Set, ClusterOptions) is only needed if you run a couchbase cluster at non-standard ports.

See the individual connect methods for more information, but here is a snippet to get you off the ground quickly. It assumes you have Couchbase running locally and the "travel-sample" sample bucket loaded:

 //Connect and open a bucket
 Cluster cluster = Cluster.connect("127.0.0.1","Administrator","password");
 Bucket bucket = cluster.bucket("travel-sample");
 Collection collection = bucket.defaultCollection();

 // Perform a N1QL query
 QueryResult queryResult = cluster.query("select * from `travel-sample` limit 5");
 System.out.println(queryResult.rowsAsObject());

 // Perform a KV request and load a document
 GetResult getResult = collection.get("airline_10");
 System.out.println(getResult);
 

When the application shuts down (or the SDK is not needed anymore), you are required to call disconnect(). If you omit this step, the application will terminate (all spawned threads are daemon threads) but any operations or work in-flight will not be able to complete and lead to undesired side-effects. Note that disconnect will also shutdown all associated buckets.

Cluster-level operations like query(String) will not work unless at leas one bucket is opened against a pre 6.5 cluster. If you are using 6.5 or later, you can run cluster-level queries without opening a bucket. All of these operations are lazy, so the SDK will bootstrap in the background and service queries as quickly as possible. This also means that the first operations might be a bit slower until all sockets are opened in the background and the configuration is loaded. If you want to wait explicitly, you can utilize the waitUntilReady(Duration) method before performing your first query.

The SDK will only work against Couchbase Server 5.0 and later, because RBAC (role-based access control) is a first class concept since 3.0 and therefore required.

  • Method Details

    • connect

      public static Cluster connect(String connectionString, String username, String password)
      Connect to a Couchbase cluster with a username and a password as credentials.

      This is the simplest (and recommended) method to connect to the cluster if you do not need to provide any custom options.

      The first argument (the connection string in its simplest form) is used to supply the hostnames of the cluster. In development it is OK to only pass in one hostname (or IP address), but in production we recommend passing in at least 3 nodes of the cluster (comma separated). The reason is that if one or more of the nodes are not reachable the client will still be able to bootstrap (and your application will become more resilient as a result).

      Here is how you specify one node to use for bootstrapping:

       Cluster cluster = Cluster.connect("127.0.0.1", "user", "password"); // ok during development
       
      This is what we recommend in production:
       Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password"); // recommended in production
       
      It is important to understand that the SDK will only use the bootstrap ("seed nodes") host list to establish an initial contact with the cluster. Once the configuration is loaded this list is discarded and the client will connect to all nodes based on this configuration.

      This method will return immediately and the SDK will try to establish all the necessary resources and connections in the background. This means that depending on how fast it can be bootstrapped, the first couple cluster-level operations like query(String) will take a bit longer. If you want to wait explicitly until those resources are available, you can use the waitUntilReady(Duration) method before running any of them:

       Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password");
       cluster.waitUntilReady(Duration.ofSeconds(5));
       QueryResult result = cluster.query("select * from bucket limit 1");
       
      Parameters:
      connectionString - connection string used to locate the Couchbase cluster.
      username - the name of the user with appropriate permissions on the cluster.
      password - the password of the user with appropriate permissions on the cluster.
      Returns:
      the instantiated Cluster.
    • connect

      public static Cluster connect(String connectionString, ClusterOptions options)
      Connect to a Couchbase cluster with custom options.

      You likely want to use this over the simpler connect(String, String, String) if:

      needs to be provided.

      A custom environment can be passed in like this:

       // on bootstrap:
       ClusterEnvironment environment = ClusterEnvironment.builder().build();
       Cluster cluster = Cluster.connect(
         "127.0.0.1",
         clusterOptions("user", "password").environment(environment)
       );
      
       // on shutdown:
       cluster.disconnect();
       environment.shutdown();
       
      It is VERY important to shut down the environment when being passed in separately (as shown in the code sample above) and AFTER the cluster is disconnected. This will ensure an orderly shutdown and makes sure that no resources are left lingering.

      If you want to pass in a custom Authenticator, it is likely because you are setting up certificate-based authentication instead of using a username and a password directly. Remember to also enable TLS.

       ClusterEnvironment environment = ClusterEnvironment
         .builder()
         .securityConfig(SecurityConfig.enableTls(true))
         .build();
      
       Authenticator authenticator = CertificateAuthenticator.fromKey(...);
      
       Cluster cluster = Cluster.connect(
         "127.0.0.1",
         clusterOptions(authenticator).environment(environment)
       );
       
      This method will return immediately and the SDK will try to establish all the necessary resources and connections in the background. This means that depending on how fast it can be bootstrapped, the first couple cluster-level operations like query(String) will take a bit longer. If you want to wait explicitly until those resources are available, you can use the waitUntilReady(Duration) method before running any of them:
       Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password");
       cluster.waitUntilReady(Duration.ofSeconds(5));
       QueryResult result = cluster.query("select * from bucket limit 1");
       
      Parameters:
      connectionString - connection string used to locate the Couchbase cluster.
      options - custom options when creating the cluster.
      Returns:
      the instantiated Cluster.
    • connect

      public static Cluster connect(Set<SeedNode> seedNodes, ClusterOptions options)
      Connect to a Couchbase cluster with a list of seed nodes and custom options.

      Note that you likely only want to use this method if you need to pass in custom ports for specific seed nodes during bootstrap. Otherwise we recommend relying on the simpler connect(String, String, String) method instead.

      The following example shows how to bootstrap against a node with custom KV and management ports:

       var seedNodes = Set.of(
         SeedNode.create("127.0.0.1")
           .withKvPort(12000)
           .withManagerPort(9000)
       );
       Cluster cluster Cluster.connect(seedNodes, clusterOptions("user", "password"));
       
      Parameters:
      seedNodes - the seed nodes used to connect to the cluster.
      options - custom options when creating the cluster.
      Returns:
      the instantiated Cluster.
    • maxAllowedInstances

      @Uncommitted public static void maxAllowedInstances(int maxAllowedInstances)
      Configures the maximum allowed core instances before warning/failing.
      Parameters:
      maxAllowedInstances - the number of max allowed core instances.
    • failIfInstanceLimitReached

      @Uncommitted public static void failIfInstanceLimitReached(boolean failIfInstanceLimitReached)
      Configures if the SDK should fail to create instead of warn if the instance limit is reached.
      Parameters:
      failIfInstanceLimitReached - true if it should throw an exception instead of warn.
    • async

      public AsyncCluster async()
      Provides access to the related AsyncCluster.

      Note that the AsyncCluster is considered advanced API and should only be used to get the last drop of performance or if you are building higher-level abstractions on top. If in doubt, we recommend using the reactive() API instead.

    • reactive

      public ReactiveCluster reactive()
      Provides access to the related ReactiveCluster.
    • core

      @Volatile public Core core()
      Provides access to the underlying Core.

      This is advanced and volatile API - it might change any time without notice. Use with care!

    • httpClient

      @Volatile public CouchbaseHttpClient httpClient()
      Returns a specialized HTTP client for making requests to the Couchbase Server REST API.
    • users

      public UserManager users()
      The user manager allows to manage users and groups.
    • buckets

      public BucketManager buckets()
      The bucket manager allows to perform administrative tasks on buckets and their resources.
    • analyticsIndexes

      public AnalyticsIndexManager analyticsIndexes()
      The analytics index manager allows to modify and create indexes for the analytics service.
    • queryIndexes

      public QueryIndexManager queryIndexes()
      The query index manager allows to modify and create indexes for the query service.
    • searchIndexes

      public SearchIndexManager searchIndexes()
      The search index manager allows to modify and create indexes for the search service.
    • eventingFunctions

      @Uncommitted public EventingFunctionManager eventingFunctions()
      Provides access to the eventing function management services for functions in the admin scope.
    • environment

      public ClusterEnvironment environment()
      Provides access to the used ClusterEnvironment.
    • query

      public QueryResult query(String statement)
      Performs a query against the query (N1QL) services.
      Parameters:
      statement - the N1QL query statement.
      Returns:
      the QueryResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • query

      public QueryResult query(String statement, QueryOptions options)
      Performs a query against the query (N1QL) services with custom options.
      Parameters:
      statement - the N1QL query statement as a raw string.
      options - the custom options for this query.
      Returns:
      the QueryResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • analyticsQuery

      public AnalyticsResult analyticsQuery(String statement)
      Performs an analytics query with default AnalyticsOptions.
      Parameters:
      statement - the query statement as a raw string.
      Returns:
      the AnalyticsResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • analyticsQuery

      public AnalyticsResult analyticsQuery(String statement, AnalyticsOptions options)
      Performs an analytics query with custom AnalyticsOptions.
      Parameters:
      statement - the query statement as a raw string.
      options - the custom options for this query.
      Returns:
      the AnalyticsResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • search

      public SearchResult search(String indexName, SearchRequest searchRequest)
      Performs a request against the Full Text Search (FTS) service, with default SearchOptions.

      This can be used to perform a traditional FTS query, and/or a vector search.

      This method is for global FTS indexes. For scoped indexes, use Scope instead.

      Parameters:
      searchRequest - the request, in the form of a SearchRequest
      Returns:
      the SearchResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • search

      public SearchResult search(String indexName, SearchRequest searchRequest, SearchOptions options)
      Performs a request against the Full Text Search (FTS) service, with custom SearchOptions.

      This can be used to perform a traditional FTS query, and/or a vector search.

      This method is for global FTS indexes. For scoped indexes, use Scope instead.

      Parameters:
      searchRequest - the request, in the form of a SearchRequest
      Returns:
      the SearchResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • searchQuery

      public SearchResult searchQuery(String indexName, SearchQuery query)
      Performs a Full Text Search (FTS) query with default SearchOptions.

      This method is for global FTS indexes. For scoped indexes, use Scope instead.

      New users should consider the newer search(String, SearchRequest) interface instead, which can do both the traditional FTS SearchQuery that this method performs, and/or can also be used to perform a VectorSearch.

      Parameters:
      query - the query, in the form of a SearchQuery
      Returns:
      the SearchResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • searchQuery

      public SearchResult searchQuery(String indexName, SearchQuery query, SearchOptions options)
      Performs a Full Text Search (FTS) query with custom SearchOptions.

      This method is for global FTS indexes. For scoped indexes, use Scope instead.

      New users should consider the newer search(String, SearchRequest) interface instead, which can do both the traditional FTS SearchQuery that this method performs, and/or can also be used to perform a VectorSearch.

      Parameters:
      query - the query, in the form of a SearchQuery
      options - the custom options for this query.
      Returns:
      the SearchResult once the response arrives successfully.
      Throws:
      TimeoutException - if the operation times out before getting a result.
      CouchbaseException - for all other error reasons (acts as a base type and catch-all).
    • bucket

      public Bucket bucket(String bucketName)
      Opens a Bucket with the given name.
      Parameters:
      bucketName - the name of the bucket to open.
      Returns:
      a Bucket once opened.
    • disconnect

      public void disconnect()
      Performs a non-reversible disconnect of this Cluster.

      If this method is used, the default disconnect timeout on the environment is used. Please use the companion overload (disconnect(Duration) if you want to provide a custom duration.

      If a custom ClusterEnvironment has been passed in during connect, it is VERY important to shut it down after calling this method. This will prevent any in-flight tasks to be stopped prematurely.

    • disconnect

      public void disconnect(Duration timeout)
      Performs a non-reversible disconnect of this Cluster.

      If a custom ClusterEnvironment has been passed in during connect, it is VERY important to shut it down after calling this method. This will prevent any in-flight tasks to be stopped prematurely.

      Parameters:
      timeout - allows to override the default disconnect duration.
    • diagnostics

      public DiagnosticsResult diagnostics()
      Runs a diagnostic report on the current state of the cluster from the SDKs point of view.

      Please note that it does not perform any I/O to do this, it will only use the current known state of the cluster to assemble the report (so, if for example no N1QL query has been run the socket pool might be empty and as result not show up in the report).

      Returns:
      the DiagnosticsResult once complete.
    • diagnostics

      public DiagnosticsResult diagnostics(DiagnosticsOptions options)
      Runs a diagnostic report with custom options on the current state of the cluster from the SDKs point of view.

      Please note that it does not perform any I/O to do this, it will only use the current known state of the cluster to assemble the report (so, if for example no N1QL query has been run the socket pool might be empty and as result not show up in the report).

      Parameters:
      options - options that allow to customize the report.
      Returns:
      the DiagnosticsResult once complete.
    • ping

      public PingResult ping()
      Performs application-level ping requests against services in the couchbase cluster.

      Note that this operation performs active I/O against services and endpoints to assess their health. If you do not wish to perform I/O, consider using the diagnostics() instead. You can also combine the functionality of both APIs as needed, which is waitUntilReady(Duration) is doing in its implementation as well.

      Returns:
      the PingResult once complete.
    • ping

      public PingResult ping(PingOptions options)
      Performs application-level ping requests with custom options against services in the couchbase cluster.

      Note that this operation performs active I/O against services and endpoints to assess their health. If you do not wish to perform I/O, consider using the diagnostics(DiagnosticsOptions) instead. You can also combine the functionality of both APIs as needed, which is waitUntilReady(Duration) is doing in its implementation as well.

      Returns:
      the PingResult once complete.
    • waitUntilReady

      public void waitUntilReady(Duration timeout)
      Waits until the desired ClusterState is reached.

      This method will wait until either the cluster state is "online", or the timeout is reached. Since the SDK is bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online and usable before moving on.

      Parameters:
      timeout - the maximum time to wait until readiness.
    • waitUntilReady

      public void waitUntilReady(Duration timeout, WaitUntilReadyOptions options)
      Waits until the desired ClusterState is reached.

      This method will wait until either the cluster state is "online" by default, or the timeout is reached. Since the SDK is bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online and usable before moving on. You can tune the properties through WaitUntilReadyOptions.

      Parameters:
      timeout - the maximum time to wait until readiness.
      options - the options to customize the readiness waiting.
    • transactions

      @Uncommitted public Transactions transactions()
      Allows access to transactions.
      Returns:
      the Transactions interface.
    • close

      public void close()
      Implementing the Closeable interface for try-with-resources support.

      Calls disconnect() and as such behaves with similar semantics.

      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable