Cluster

class couchbase.cluster.Cluster(connstr: str, *options: ClusterOptions, **kwargs: Unpack[ClusterKwargs])

Create a Couchbase Cluster instance.

The cluster instance exposes the operations which are available to be performed against a cluster.

Note

Although creating an instance of Cluster is allowed, it is recommended to use the Cluster’s static Cluster.connect() method. See Cluster.connect() for connect for examples.

Parameters:
  • connstr (str) –

    The connection string to use for connecting to the cluster. This is a URI-like string allowing specifying multiple hosts.

    The format of the connection string is the scheme (couchbase for normal connections, couchbases for SSL enabled connections); a list of one or more hostnames delimited by commas

  • options (ClusterOptions) – Global options to set for the cluster. Some operations allow the global options to be overriden by passing in options to the operation.

  • **kwargs – keyword arguments that can be used in place or to overrride provided ClusterOptions

Raises:
analytics_indexes() → AnalyticsIndexManager

Get a manager for the analytics dataverses, datasets, indexes and links of this cluster.

Returns:

An AnalyticsIndexManager instance.

Return type:

AnalyticsIndexManager

analytics_query(statement: str, *options: AnalyticsOptions | str | int | float | bool | None | Mapping[str, Any] | Sequence[Any], **kwargs: Any) → AnalyticsResult

Executes an analaytics query against the cluster.

Note

The analytics query is executed lazily in that it is executed once iteration over the AnalyticsResult begins.

See also

Parameters:
  • statement (str) – The analytics SQL++ statement to execute.

  • options (AnalyticsOptions) – Optional parameters for the analytics query operation.

  • **kwargs – keyword arguments that can be used in place or to override provided AnalyticsOptions. A keyword that is not one of its options is sent as a named parameter; prefer AnalyticsOptions(named_parameters=...), which cannot collide with an option name.

Returns:

An instance of a AnalyticsResult which provides access to iterate over the analytics query results and access metadata and metrics about the analytics query.

Return type:

AnalyticsResult

Examples

Note

Be sure to setup the necessary dataverse(s), dataset(s) for your analytics queries. See Analytics Introduction in Couchbase Server docs.

Simple analytics query:

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $1 LIMIT $2;'
q_res = cluster.analytics_query(q_str)
for row in q_res.rows():
    print(f'Found row: {row}')

Simple analytics query with positional parameters:

from couchbase.options import AnalyticsOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $1 LIMIT $2;'
q_res = cluster.analytics_query(q_str, AnalyticsOptions(positional_parameters=['United%', 5]))
for row in q_res.rows():
    print(f'Found row: {row}')

Simple analytics query with named parameters:

from couchbase.options import AnalyticsOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = cluster.analytics_query(q_str,
                                AnalyticsOptions(named_parameters={'country': 'United%', 'lim':2}))
for row in q_res.rows():
    print(f'Found row: {row}')

Retrieve metadata and/or metrics from analytics query:

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = cluster.analytics_query(q_str)
for row in q_res.rows():
    print(f'Found row: {row}')

print(f'Analytics query metadata: {q_res.metadata()}')
print(f'Analytics query metrics: {q_res.metadata().metrics()}')
bucket(bucket_name: str) → Bucket

Creates a Bucket instance to a specific bucket.

See also

Bucket

Parameters:

bucket_name (str) – Name of the bucket to reference

Returns:

A bucket instance

Return type:

Bucket

Raises:
buckets() → BucketManager

Get a manager for the buckets of this cluster.

Returns:

A BucketManager instance.

Return type:

BucketManager

close() → None

Shuts down this cluster instance. Cleaning up all resources associated with it.

Warning

Use of this method is almost always unnecessary. Cluster resources should be cleaned up once the cluster instance falls out of scope. However, in some applications tuning resources is necessary and in those types of applications, this method might be beneficial.

cluster_info() → ClusterInfoResult

Retrieve the Couchbase cluster information.

Note

If using Couchbase Server version < 6.6, a bucket must be opened prior to calling cluster.cluster_info(). If a bucket is not opened a ServiceUnavailableException will be raised.

Returns:

Information about the connected cluster.

Return type:

ClusterInfoResult

Raises:
static connect(connstr: str, *options: ClusterOptions, **kwargs: Unpack[ClusterKwargs]) → Cluster

Create a cluster and connect to it.

Parameters:
  • connstr (str) –

    The connection string to use for connecting to the cluster. This is a URI-like string allowing specifying multiple hosts.

    The format of the connection string is the scheme (couchbase for normal connections, couchbases for SSL enabled connections); a list of one or more hostnames delimited by commas

  • options (ClusterOptions) – Global options to set for the cluster. Some operations allow the global options to be overriden by passing in options to the operation.

  • **kwargs – keyword arguments that can be used in place or to overrride provided ClusterOptions

Returns:

If successful, a connect Couchbase Cluster instance.

Return type:

Cluster

Raises:

Examples

Initialize cluster using default options:

from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions

auth = PasswordAuthenticator('username', 'password')
cluster = Cluster.connect('couchbase://localhost', ClusterOptions(auth))

Connect using SSL:

from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions

auth = PasswordAuthenticator('username', 'password', cert_path='/path/to/cert')
cluster = Cluster.connect('couchbases://localhost', ClusterOptions(auth))

Initialize cluster using with global timeout options:

from datetime import timedelta

from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions, ClusterTimeoutOptions

auth = PasswordAuthenticator('username', 'password')
timeout_opts = ClusterTimeoutOptions(kv_timeout=timedelta(seconds=10),
                                    query_timeout=timedelta(seconds=120))
cluster = Cluster.connect('couchbase://localhost', ClusterOptions(auth, timeout_options=timeout_opts))
diagnostics(opts: DiagnosticsOptions | None = None, **kwargs: Unpack[DiagnosticsOptionsKwargs]) → DiagnosticsResult

Performs a diagnostic operation against the cluster.

The diagnostic operations returns a report about the current active connections with the cluster. Includes information about remote and local addresses, last activity, and other diagnostics information.

Parameters:
Returns:

A report which describes current active connections with the cluster.

Return type:

DiagnosticsResult

eventing_functions() → EventingFunctionManager

Get a manager for the eventing functions of this cluster.

Note

Eventing function management is an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Returns:

An EventingFunctionManager instance.

Return type:

EventingFunctionManager

ping(opts: PingOptions | None = None, **kwargs: Unpack[PingOptionsKwargs]) → PingResult

Performs a ping operation against the cluster.

The ping operation pings the services which are specified (or all services if none are specified). Returns a report which describes the outcome of the ping operations which were performed.

Parameters:
  • opts (PingOptions) – Optional parameters for this operation.

  • **kwargs – keyword arguments that can be used in place or to override provided PingOptions

Returns:

A report which describes the outcome of the ping operations which were performed.

Return type:

PingResult

query(statement: str, *options: QueryOptions | str | int | float | bool | None | Mapping[str, Any] | Sequence[Any], **kwargs: Any) → QueryResult

Executes a N1QL query against the cluster.

Note

The query is executed lazily in that it is executed once iteration over the QueryResult begins.

See also

Parameters:
  • statement (str) – The N1QL statement to execute.

  • options (QueryOptions) – Optional parameters for the query operation.

  • **kwargs – keyword arguments that can be used in place or to override provided QueryOptions. A keyword that is not one of its options is sent as a named parameter; prefer QueryOptions(named_parameters=...), which cannot collide with an option name.

Returns:

An instance of a QueryResult which provides access to iterate over the query results and access metadata and metrics about the query.

Return type:

QueryResult

Examples

Simple query:

q_res = cluster.query('SELECT * FROM `travel-sample` WHERE country LIKE 'United%' LIMIT 2;')
for row in q_res.rows():
    print(f'Found row: {row}')

Simple query with positional parameters:

from couchbase.options import QueryOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $1 LIMIT $2;'
q_res = cluster.query(q_str, QueryOptions(positional_parameters=['United%', 5]))
for row in q_res.rows():
    print(f'Found row: {row}')

Simple query with named parameters:

from couchbase.options import QueryOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = cluster.query(q_str, QueryOptions(named_parameters={'country': 'United%', 'lim':2}))
for row in q_res.rows():
    print(f'Found row: {row}')

Retrieve metadata and/or metrics from query:

from couchbase.options import QueryOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = cluster.query(q_str, QueryOptions(metrics=True))
for row in q_res.rows():
    print(f'Found row: {row}')

print(f'Query metadata: {q_res.metadata()}')
print(f'Query metrics: {q_res.metadata().metrics()}')
query_indexes() → QueryIndexManager

Get a manager for the query indexes of this cluster.

Returns:

A QueryIndexManager instance.

Return type:

QueryIndexManager

search(index: str, request: SearchRequest | SearchQuery, options: SearchOptions | None = None, **kwargs: Unpack[SearchOptionsKwargs]) → SearchResult

Executes an search against the cluster.

Note

The search is executed lazily in that it is executed once iteration over the SearchResult begins.

See also

Parameters:
  • index (str) – Name of the search index to use.

  • request (SearchRequest | SearchQuery) –

    Type of search request to perform.

    Deprecated since version 4.7.0: Passing a SearchQuery is deprecated; wrap it with create() instead.

  • options (SearchOptions) – Optional parameters for the search query operation.

  • **kwargs – keyword arguments that can be used in place or to override provided SearchOptions

Returns:

An instance of a SearchResult which provides access to iterate over the search query results and access metadata and metrics about the search query.

Return type:

SearchResult

Examples

Note

Be sure to create a search index prior to executing a search. Also, if an application desires to utilize search row locations, highlighting, etc. make sure the search index is setup appropriately. See Creating Indexes in Couchbase Server docs.

Simple search:

import couchbase.search as search
from couchbase.options import SearchOptions

# ... other code ...

request = search.SearchRequest.create(search.TermQuery('home'))
q_res = cluster.search('travel-sample-index',
                       request,
                       SearchOptions(limit=10))

for row in q_res.rows():
    print(f'Found row: {row}')

Simple vector search:

import couchbase.search as search
from couchbase.options import SearchOptions
from couchbase.vector_search import VectorQuery, VectorSearch

# ... other code ...

# NOTE:  the vector is expected to be type list[float], set the vector to the appropriate value,
# this is an example.
vector = [-0.014653487130999565, -0.008658270351588726, 0.017129190266132355, -0.015563474968075752]
vector_search = VectorSearch.from_vector_query(VectorQuery('vector_field', vector))
request = search.SearchRequest.create(vector_search)
q_res = cluster.search('travel-sample-vector-index',
                       request,
                       SearchOptions(limit=10))

for row in q_res.rows():
    print(f'Found row: {row}')

Combine search and vector search:

import couchbase.search as search
from couchbase.options import SearchOptions
from couchbase.vector_search import VectorQuery, VectorSearch

# ... other code ...

# NOTE:  the vector is expected to be type list[float], set the vector to the appropriate value,
# this is an example.
vector_search = VectorSearch.from_vector_query(VectorQuery('vector_field', [-0.014653487130999565,
                                                                            -0.008658270351588726,
                                                                            0.017129190266132355,
                                                                            -0.015563474968075752]))
request = search.SearchRequest.create(search.MatchAllQuery()).with_vector_search(vector_search)
q_res = cluster.search('travel-sample-vector-index',
                       request,
                       SearchOptions(limit=10))

for row in q_res.rows():
    print(f'Found row: {row}')
search_indexes() → SearchIndexManager

Get a manager for the search indexes of this cluster.

Returns:

A SearchIndexManager instance.

Return type:

SearchIndexManager

search_query(index: str, query: SearchQuery, options: SearchOptions | None = None, **kwargs: Unpack[SearchOptionsKwargs]) → SearchResult

Executes an search query against the cluster.

Deprecated since version 4.1.11: Use search() instead.

Note

The search query is executed lazily in that it is executed once iteration over the SearchResult begins.

See also

Parameters:
  • index (str) – Name of the search query to use.

  • query (SearchQuery) – Type of search query to perform.

  • options (SearchOptions) – Optional parameters for the search query operation.

  • **kwargs – keyword arguments that can be used in place or to override provided SearchOptions

Returns:

An instance of a SearchResult which provides access to iterate over the search query results and access metadata and metrics about the search query.

Return type:

SearchResult

Raises:

InvalidArgumentException – If a SearchRequest is provided. Use search() for a search request.

Examples

Note

Be sure to create a search index prior to executing search queries. Also, if an application desires to utilize search row locations, highlighting, etc. make sure the search index is setup appropriately. See Creating Indexes in Couchbase Server docs.

Simple search query:

import couchbase.search as search
from couchbase.options import SearchOptions

# ... other code ...

query = search.TermQuery('home')
q_res = cluster.search_query('travel-sample-index',
                            query,
                            SearchOptions(limit=10))

for row in q_res.rows():
    print(f'Found row: {row}')

Simple search query with facets:

import couchbase.search as search
from couchbase.options import SearchOptions

# ... other code ...

facet_name = 'activity'
facet = search.TermFacet('activity')
query = search.TermQuery('home')
q_res = cluster.search_query('travel-sample-index',
                            query,
                            SearchOptions(limit=10, facets={facet_name: facet}))

for row in q_res.rows():
    print(f'Found row: {row}')

print(f'facets: {q_res.facets()}')

Simple search query with fields and locations:

import couchbase.search as search
from couchbase.options import SearchOptions

# ... other code ...

search_fields = ['name', 'activity']
query = search.TermQuery('home')
q_res = cluster.search_query('travel-sample-index',
                            query,
                            SearchOptions(limit=10,
                                        include_locations=True,
                                        fields=search_fields))

for row in q_res.rows():
    print(f'Found row: {row}')
    print(f'Fields: {row.fields}')
    print(f'Locations: {row.locations}')
set_authenticator(authenticator: CertificateAuthenticator | JwtAuthenticator | PasswordAuthenticator) → None

Replace the authenticator used by this Cluster.

Allows updating credentials without restarting the application. The effect on existing connections depends on the authenticator type:

  • JwtAuthenticator: Live re-auth on existing KV connections via OAUTHBEARER SASL. HTTP requests use the new Bearer token immediately.

  • PasswordAuthenticator: No effect on existing KV connections (they keep old credentials). New HTTP requests use the new Basic auth header.

  • CertificateAuthenticator: No effect on existing connections (TLS handshake already completed). Only new connections use the new certificate.

Parameters:

authenticator – New authenticator to use. Must be the same type as the current authenticator.

Raises:
property transactions: Transactions

Runs transactions on this cluster.

users() → UserManager

Get a manager for the users of this cluster.

Returns:

A UserManager instance.

Return type:

UserManager

wait_until_ready(timeout: timedelta, opts: WaitUntilReadyOptions | None = None, **kwargs: Unpack[WaitUntilReadyKwargs]) → None

Wait until the cluster is ready for use.

Check the current connections to see if the desired state has been reached. If not, perform a ping against the specified services. The ping operation will be performed repeatedly with a slight delay in between until the specified timeout has been reached or the cluster is ready for use, whichever comes first.

Parameters:
Raises:

UnAmbiguousTimeoutException – If the specified timeout is reached prior to the cluster being ready for use.

Example

Wait until the cluster is ready to use KV and query services:

from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.diagnostics import ServiceType
from couchbase.options import WaitUntilReadyOptions

auth = PasswordAuthenticator('username', 'password')
cluster = Cluster.connect('couchbase://localhost', ClusterOptions(auth))

cluster.wait_until_ready(timedelta(seconds=3),
         WaitUntilReadyOptions(service_types=[ServiceType.KeyValue, ServiceType.Query]))