Cluster
- class acouchbase.cluster.AsyncCluster(connstr: str, *options: ClusterOptions, loop: AbstractEventLoop | None = None, **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
AsyncClusteris allowed, it is recommended to use the AsyncCluster’s staticAsyncCluster.connect()method. SeeAsyncCluster.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 (
couchbasefor normal connections,couchbasesfor SSL enabled connections); a list of one or more hostnames delimited by commasoptions (
ClusterOptions) – Global options to set for the cluster. Some operations allow the global options to be overriden by passing in options to the operation.loop (
asyncio.AbstractEventLoop, optional) – The event loop the cluster runs on. It must be running when the cluster is created. If not provided, the running loop is used. Any loop type is accepted.**kwargs – keyword arguments that can be used in place or to overrride provided
ClusterOptions
- Raises:
InvalidArgumentException – If no
Authenticatoris provided. Also raised if an invalid ClusterOption is provided.AuthenticationException – If provided
Authenticatorhas incorrect credentials.
- analytics_indexes() AnalyticsIndexManager
Get a manager for the analytics dataverses, datasets, indexes and links of this cluster.
- Returns:
An
AnalyticsIndexManagerinstance.- Return type:
- analytics_query(statement: str, *options: AnalyticsOptions | str | int | float | bool | None | Mapping[str, Any] | Sequence[Any], **kwargs: Any) AsyncAnalyticsResult
Executes an analaytics query against the cluster.
Note
The analytics query is executed lazily in that it is executed once iteration over the
AsyncAnalyticsResultbegins.See also
AnalyticsIndexManager: for how to manage analytics dataverses, datasets, indexes and links.analytics_query(): for how to execute scope-level analytics queries
- 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; preferAnalyticsOptions(named_parameters=...), which cannot collide with an option name.
- Returns:
An instance of a
AsyncAnalyticsResultwhich provides access to iterate over the analytics query results and access metadata and metrics about the analytics query.- Return type:
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) async for row in q_res.rows(): print(f'Found row: {row}')
Simple analytics query with positional parameters:
from acouchbase.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])) async for row in q_res.rows(): print(f'Found row: {row}')
Simple analytics query with named parameters:
from acouchbase.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})) async 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) async 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) AsyncBucket
Creates a Bucket instance to a specific bucket.
See also
- Parameters:
bucket_name (str) – Name of the bucket to reference
- Returns:
A bucket instance
- Return type:
The bucket opens on the event loop once the cluster is connected, so this call does not raise. A bucket that cannot be opened, such as one that does not exist, fails the first operation awaited on it, or
on_connect().
- buckets() BucketManager
Get a manager for the buckets of this cluster.
- Returns:
A
BucketManagerinstance.- Return type:
- async 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.
- async 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
ServiceUnavailableExceptionwill be raised.- Returns:
Information about the connected cluster.
- Return type:
Awaitable[
ClusterInfoResult]- Raises:
ServiceUnavailableException – If called prior to connecting to a bucket if using server version < 6.6.
- async static connect(connstr: str, *options: ClusterOptions, loop: AbstractEventLoop | None = None, **kwargs: Unpack[ClusterKwargs]) AsyncCluster
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 (
couchbasefor normal connections,couchbasesfor SSL enabled connections); a list of one or more hostnames delimited by commasoptions (
ClusterOptions) – Global options to set for the cluster. Some operations allow the global options to be overriden by passing in options to the operation.loop (
asyncio.AbstractEventLoop, optional) – The event loop the cluster runs on. It must be the running loop. If not provided, the running loop is used.**kwargs – keyword arguments that can be used in place or to overrride provided
ClusterOptions
- Returns:
If successful, a connect Couchbase Cluster instance.
- Return type:
- Raises:
InvalidArgumentException – If no
Authenticatoris provided. Also raised if an invalid ClusterOption is provided.AuthenticationException – If provided
Authenticatorhas incorrect credentials.
Examples
Initialize cluster using default options:
from acouchbase.cluster import Cluster from acouchbase.auth import PasswordAuthenticator from acouchbase.options import ClusterOptions auth = PasswordAuthenticator('username', 'password') cluster = await Cluster.connect('couchbase://localhost', ClusterOptions(auth))
Connect using SSL:
from acouchbase.cluster import Cluster from acouchbase.auth import PasswordAuthenticator from acouchbase.options import ClusterOptions auth = PasswordAuthenticator('username', 'password', cert_path='/path/to/cert') cluster = await Cluster.connect('couchbases://localhost', ClusterOptions(auth))
Initialize cluster using with global timeout options:
from datetime import timedelta from acouchbase.cluster import Cluster from acouchbase.auth import PasswordAuthenticator from acouchbase.options import ClusterOptions, ClusterTimeoutOptions auth = PasswordAuthenticator('username', 'password') timeout_opts = ClusterTimeoutOptions(kv_timeout=timedelta(seconds=10), query_timeout=timedelta(seconds=120)) cluster = await Cluster.connect('couchbase://localhost', ClusterOptions(auth, timeout_options=timeout_opts))
- async 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:
opts (
DiagnosticsOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
DiagnosticsOptions
- Returns:
A report which describes current active connections with the cluster.
- Return type:
Awaitable[
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
EventingFunctionManagerinstance.- Return type:
- async on_connect() None
Waits until the AsyncCluster connection has been established.
Note
It is recommended to use the AsyncCluster’s static
AsyncCluster.connect()method. SeeAsyncCluster.connect()for connect for examples.- Raises:
UnAmbiguousTimeoutException – If an error occured while trying to connect.
- async 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:
Awaitable[
PingResult]
- query(statement: str, *options: QueryOptions | str | int | float | bool | None | Mapping[str, Any] | Sequence[Any], **kwargs: Any) AsyncQueryResult
Executes a N1QL query against the cluster.
Note
The query is executed lazily in that it is executed once iteration over the
AsyncQueryResultbegins.See also
QueryIndexManager: for how to manage query indexesquery(): For how to execute scope-level queries.
- 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; preferQueryOptions(named_parameters=...), which cannot collide with an option name.
- Returns:
An instance of a
AsyncQueryResultwhich provides access to iterate over the query results and access metadata and metrics about the query.- Return type:
Examples
Simple query:
q_res = cluster.query('SELECT * FROM `travel-sample` WHERE country LIKE 'United%' LIMIT 2;') async for row in q_res.rows(): print(f'Found row: {row}')
Simple query with positional parameters:
from acouchbase.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])) async for row in q_res.rows(): print(f'Found row: {row}')
Simple query with named parameters:
from acouchbase.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})) async for row in q_res.rows(): print(f'Found row: {row}')
Retrieve metadata and/or metrics from query:
from acouchbase.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)) async 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
QueryIndexManagerinstance.- Return type:
- search(index: str, request: SearchRequest | SearchQuery, options: SearchOptions | None = None, **kwargs: Unpack[SearchOptionsKwargs]) AsyncSearchResult
Executes an search against the cluster.
Note
The search is executed lazily in that it is executed once iteration over the
AsyncSearchResultbegins.See also
SearchIndexManager: for how to manage search indexes.search(): for how to execute scope-level search
- 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
SearchQueryis deprecated; wrap it withcreate()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
AsyncSearchResultwhich provides access to iterate over the search query results and access metadata and metrics about the search query.- Return type:
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 acouchbase.options import SearchOptions # ... other code ... request = search.SearchRequest.create(search.TermQuery('home')) q_res = cluster.search('travel-sample-index', request, SearchOptions(limit=10)) async for row in q_res.rows(): print(f'Found row: {row}')
Simple vector search:
import couchbase.search as search from acouchbase.options import SearchOptions from acouchbase.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)) async for row in q_res.rows(): print(f'Found row: {row}')
Combine search and vector search:
import couchbase.search as search from acouchbase.options import SearchOptions from acouchbase.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)) async 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
SearchIndexManagerinstance.- Return type:
- search_query(index: str, query: SearchQuery, options: SearchOptions | None = None, **kwargs: Unpack[SearchOptionsKwargs]) AsyncSearchResult
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
AsyncSearchResultbegins.See also
SearchIndexManager: for how to manage search indexes.search_query(): for how to execute scope-level search queries
- 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
AsyncSearchResultwhich provides access to iterate over the search query results and access metadata and metrics about the search query.- Return type:
- Raises:
InvalidArgumentException – If a
SearchRequestis provided. Usesearch()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 acouchbase.options import SearchOptions # ... other code ... query = search.TermQuery('home') q_res = cluster.search_query('travel-sample-index', query, SearchOptions(limit=10)) async for row in q_res.rows(): print(f'Found row: {row}')
Simple search query with facets:
import couchbase.search as search from acouchbase.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})) async 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 acouchbase.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)) async 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:
RuntimeError – If the cluster has been closed.
InvalidArgumentException – If authenticator is not the same type as the current authenticator.
- property transactions: Transactions
Runs transactions on this cluster.
- users() UserManager
Get a manager for the users of this cluster.
- Returns:
A
UserManagerinstance.- Return type:
- async 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.
See also
- Parameters:
timeout (timedelta) – Amount of time to wait for cluster to be ready before a
UnAmbiguousTimeoutExceptionis raised.opts (
WaitUntilReadyOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
WaitUntilReadyOptions
- 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 acouchbase.cluster import Cluster from acouchbase.auth import PasswordAuthenticator from acouchbase.diagnostics import ServiceType from acouchbase.options import WaitUntilReadyOptions auth = PasswordAuthenticator('username', 'password') cluster = Cluster.connect('couchbase://localhost', ClusterOptions(auth)) await cluster.wait_until_ready(timedelta(seconds=3), WaitUntilReadyOptions(service_types=[ServiceType.KeyValue, ServiceType.Query]))
- acouchbase.cluster.Cluster
alias of
AsyncCluster
This module also publishes these, described where they are first documented: