Asyncio (acouchbase) Core API

Note

Further updates to the acouchbase docs will come with future 4.x releases. In the meantime, check out the provided examples in the Github repo.

Cluster

acouchbase.cluster.Cluster

alias of AsyncCluster

class acouchbase.cluster.AsyncCluster(connstr, *options, **kwargs)

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 AsyncCluster is allowed, it is recommended to use the AsyncCluster’s static AsyncCluster.connect() method. See AsyncCluster.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 (Dict[str, Any]) – keyword arguments that can be used in place or to overrride provided ClusterOptions

Raises:
async static connect(connstr, *options, **kwargs) AsyncCluster

Create a Couchbase Cluster and connect

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 (Dict[str, Any]) – keyword arguments that can be used in place or to overrride provided ClusterOptions

Returns:

If successful, a connect Couchbase Cluster instance.

Return type:

AsyncCluster

Raises:

Examples

Initialize cluster using default options:

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

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

Connect using SSL:

from acouchbase.cluster import Cluster
from couchbase.auth import PasswordAuthenticator
from couchbase.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 couchbase.auth import PasswordAuthenticator
from couchbase.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))
on_connect() Awaitable

Returns an awaitable future that indicates connecting to the Couchbase cluster has completed.

Note

It is recommended to use the AsyncCluster’s static AsyncCluster.connect() method. See AsyncCluster.connect() for connect for examples.

Returns:

An empty future. If a result is provided, connecting to the Couchbase cluster is complete.

Otherwise an exception is raised.

Return type:

Awaitable

Raises:

UnAmbiguousTimeoutException – If an error occured while trying to connect.

property connected: bool

Indicator on if the cluster has been connected or not.

Type:

bool

bucket(bucket_name) AsyncBucket

Creates a Bucket instance to a specific bucket.

Parameters:

bucket_name (str) – Name of the bucket to reference

Returns:

A bucket instance

Return type:

AsyncBucket

Raises:

BucketNotFoundException – If provided bucket_name cannot be found.

cluster_info() Awaitable[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:

Awaitable[ClusterInfoResult]

Raises:
  • RuntimeError – If called prior to the cluster being connected.

  • ServiceUnavailableException – If called prior to connecting to a bucket if using server version < 6.6.

ping(*opts, **kwargs) Awaitable[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.

Returns:

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

Return type:

Awaitable[PingResult]

diagnostics(*opts, **kwargs) Awaitable[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.

Returns:

A report which describes current active connections with the cluster.

Return type:

Awaitable[DiagnosticsResult]

async wait_until_ready(timeout, *opts, **kwargs) Awaitable[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

  • ServiceType

  • ClusterState

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 acouchbase.cluster import Cluster
from couchbase.auth import PasswordAuthenticator
from couchbase.diagnostics import ServiceType
from couchbase.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]))
query(statement, *options, **kwargs) 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

  • QueryIndexManager: for how to manage query indexes

  • query(): For how to execute scope-level queries.

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

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided QueryOptions

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;')
async 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]))
async 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}))
async 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))
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()}')
search_query(index, query, *options, **kwargs) SearchResult

Executes an search query against the cluster.

Note

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

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 (Dict[str, Any]) – 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 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))

async 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}))

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 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))

async for row in q_res.rows():
    print(f'Found row: {row}')
    print(f'Fields: {row.fields}')
    print(f'Locations: {row.locations}')
analytics_query(statement, *options, **kwargs) 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

  • 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 (Dict[str, Any]) – keyword arguments that can be used in place or to override provided AnalyticsOptions

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)
async 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]))
async 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}))
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()}')
property transactions: Transactions

A Transactions instance which can be used to perform transactions on this cluster.

Type:

Transactions

buckets() BucketManager

Get a BucketManager which can be used to manage the buckets of this cluster.

Returns:

A BucketManager instance.

Return type:

BucketManager

users() UserManager

Get a UserManager which can be used to manage the users of this cluster.

Returns:

A UserManager instance.

Return type:

UserManager

query_indexes() QueryIndexManager

Get a QueryIndexManager which can be used to manage the query indexes of this cluster.

Returns:

A QueryIndexManager instance.

Return type:

QueryIndexManager

analytics_indexes() AnalyticsIndexManager

Get a AnalyticsIndexManager which can be used to manage the analytics dataverses, dataset, indexes and links of this cluster.

Returns:

An AnalyticsIndexManager instance.

Return type:

AnalyticsIndexManager

search_indexes() SearchIndexManager

Get a SearchIndexManager which can be used to manage the search indexes of this cluster.

Returns:

A SearchIndexManager instance.

Return type:

SearchIndexManager

eventing_functions() EventingFunctionManager

Get a EventingFunctionManager which can be used to manage 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

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.

Authentication

See Global API Authentication

Bucket

acouchbase.bucket.Bucket

alias of AsyncBucket

class acouchbase.bucket.AsyncBucket(cluster, bucket_name)

Create a Couchbase Bucket instance.

Exposes the operations which are available to be performed against a bucket. Namely the ability to access to Collections as well as performing management operations against the bucket.

Parameters:
  • cluster (Cluster) – A Cluster instance.

  • bucket_name (str) – Name of the bucket.

Raises:

BucketNotFoundException – If provided bucket_name cannot be found.

property name

The name of this Bucket instance.

Type:

str

property connected: bool

Indicator on if the bucket has been connected or not.

Type:

bool

scope(name) AsyncScope

Creates a Scope instance of the specified scope.

Parameters:

name (str) – Name of the scope to reference.

Returns:

A Scope instance of the specified scope.

Return type:

Scope

collection(collection_name)

Creates a Collection instance of the specified collection.

Parameters:

collection_name (str) – Name of the collection to reference.

Returns:

A Collection instance of the specified collection.

Return type:

Collection

default_collection()

Creates a Collection instance of the default collection.

Returns:

A Collection instance of the default collection.

Return type:

Collection

ping(*opts, **kwargs) Awaitable[PingResult]

Performs a ping operation against the bucket.

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.

Returns:

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

Return type:

Awaitable[PingResult]

view_query(design_doc, view_name, *view_options, **kwargs) ViewResult

Executes a View query against the bucket.

Note

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

See also

  • ViewIndexManager: for how to manage query indexes

Parameters:
  • design_doc (str) – The name of the design document containing the view to execute.

  • view_name (str) – The name of the view to execute.

  • view_options (ViewOptions) – Optional parameters for the view query operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided ViewOptions

Returns:

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

Return type:

ViewResult

Examples

Simple view query:

from couchbase.management.views import DesignDocumentNamespace

# ... other code ...

view_result = bucket.view_query('ddoc-name',
                                'view-name',
                                limit=10,
                                namespace=DesignDocumentNamespace.DEVELOPMENT)

async for row in view_result.rows():
    print(f'Found row: {row}')
collections() CollectionManager

Get a CollectionManager which can be used to manage the scopes and collections of this bucket.

Returns:

A CollectionManager instance.

Return type:

CollectionManager

view_indexes() ViewIndexManager

Get a ViewIndexManager which can be used to manage the view design documents and views of this bucket.

Returns:

A ViewIndexManager instance.

Return type:

ViewIndexManager

Scope

acouchbase.scope.Scope

alias of AsyncScope

class acouchbase.scope.AsyncScope(bucket, scope_name)

Create a Couchbase Scope instance.

Exposes the operations which are available to be performed against a scope. Namely the ability to access to Collections for performing operations.

Parameters:
  • bucket (Bucket) – A Bucket instance.

  • scope_name (str) – Name of the scope.

property name

The name of this Scope instance.

Type:

str

property bucket_name

The name of the bucket in which this Scope instance belongs.

Type:

str

query(statement, *options, **kwargs) QueryResult

Executes a N1QL query against the scope.

Note

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

Note

Scope-level queries are only supported on Couchbase Server versions that support scopes and collections.

See also

  • QueryIndexManager: For how to manage query indexes.

  • query(): For how to execute cluster-level queries.

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

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided QueryOptions

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 = scope.query('SELECT * FROM `inventory` WHERE country LIKE 'United%' LIMIT 2;')
async 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 `inventory` WHERE country LIKE $1 LIMIT $2;'
q_res = scope.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 couchbase.options import QueryOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = scope.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 couchbase.options import QueryOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = scope.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()}')
search_query(index, query, *options, **kwargs) SearchResult

Executes an search query against the scope.

Warning

This method is DEPRECATED and will be removed in a future release. Use search(): instead.

Note

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

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 (Dict[str, Any]) – 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 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 = scope.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 couchbase.options import SearchOptions

# ... other code ...

facet_name = 'activity'
facet = search.TermFacet('activity')
query = search.TermQuery('home')
q_res = scope.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 couchbase.options import SearchOptions

# ... other code ...

search_fields = ['name', 'activity']
query = search.TermQuery('home')
q_res = scope.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}')
analytics_query(statement, *options, **kwargs) AnalyticsResult

Executes an analaytics query against the scope.

Note

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

See also

  • AnalyticsIndexManager: for how to manage analytics dataverses, datasets, indexes and links.

  • analytics_query(): for how to execute cluster-level analytics queries

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

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided AnalyticsOptions

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 = scope.analytics_query(q_str)
async 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 = scope.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 couchbase.options import AnalyticsOptions

# ... other code ...

q_str = 'SELECT * FROM `travel-sample` WHERE country LIKE $country LIMIT $lim;'
q_res = scope.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 = scope.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()}')

Collection

acouchbase.collection.Collection

alias of AsyncCollection

class acouchbase.collection.AsyncCollection
property name: str

The name of this Collection instance.

Type:

str

exists(key, *opts, **kwargs) Awaitable[ExistsResult]

Checks whether a specific document exists or not.

Parameters:
  • key (str) – The key for the document to check existence.

  • opts (ExistsOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided ExistsOptions

Returns:

A future that contains an instance of ExistsResult if successful.

Return type:

Awaitable[ExistsResult]

Examples

Simple exists operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_10'
res = await collection.exists(key)
print(f'Document w/ key - {key} {"exists" if res.exists else "does not exist"}')

Simple exists operation with options:

from datetime import timedelta
from couchbase.options import ExistsOptions

# ... other code ...

key = 'airline_10'
res = await collection.exists(key, ExistsOptions(timeout=timedelta(seconds=2)))
print(f'Document w/ key - {key} {"exists" if res.exists else "does not exist"}')
get(key, *opts, **kwargs) Awaitable[GetResult]

Retrieves the value of a document from the collection.

Parameters:
  • key (str) – The key for the document to retrieve.

  • opts (GetOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided GetOptions

Returns:

A future that contains an instance of GetResult if successful.

Return type:

Awaitable[GetResult]

Raises:

DocumentNotFoundException – If the key provided does not exist on the server.

Examples

Simple get operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

res = await collection.get('airline_10')
print(f'Document value: {res.content_as[dict]}')

Simple get operation with options:

from datetime import timedelta
from couchbase.options import GetOptions

# ... other code ...

res = await collection.get('airline_10', GetOptions(timeout=timedelta(seconds=2)))
print(f'Document value: {res.content_as[dict]}')
get_and_lock(key, lock_time, *opts, **kwargs) Awaitable[GetResult]

Locks a document and retrieves the value of that document at the time it is locked.

Parameters:
  • key (str) – The key for the document to lock and retrieve.

  • lock_time (timedelta) – The amount of time to lock the document.

  • opts (GetAndLockOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided GetAndLockOptions

Returns:

A future that contains an instance of GetResult if successful.

Return type:

Awaitable[GetResult]

Raises:

DocumentNotFoundException – If the key provided does not exist on the server.

Examples

Simple get and lock operation:

from datetime import timedelta

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_10'
res = await collection.get_and_lock(key, timedelta(seconds=20))
print(f'Locked document: {res.content_as[dict]}')

Simple get and lock operation with options:

from datetime import timedelta
from couchbase.options import GetAndLockOptions

# ... other code ...

key = 'airline_10'
res = await collection.get_and_lock(key,
                            timedelta(seconds=20),
                            GetAndLockOptions(timeout=timedelta(seconds=2)))
print(f'Locked document: {res.content_as[dict]}')
get_and_touch(key, expiry, *opts, **kwargs) Awaitable[GetResult]

Retrieves the value of the document and simultanously updates the expiry time for the same document.

Parameters:
  • key (str) – The key for the document retrieve and set expiry time.

  • expiry (timedelta) – The new expiry to apply to the document.

  • opts (GetAndTouchOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided GetAndTouchOptions

Returns:

A future that contains an instance of GetResult if successful.

Return type:

Awaitable[GetResult]

Raises:

DocumentNotFoundException – If the key provided does not exist on the server.

Examples

Simple get and touch operation:

from datetime import timedelta

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_10'
res = await collection.get_and_touch(key, timedelta(seconds=20))
print(f'Document w/ updated expiry: {res.content_as[dict]}')

Simple get and touch operation with options:

from datetime import timedelta
from couchbase.options import GetAndTouchOptions

# ... other code ...

key = 'airline_10'
res = await collection.get_and_touch(key,
                            timedelta(seconds=20),
                            GetAndTouchOptions(timeout=timedelta(seconds=2)))
print(f'Document w/ updated expiry: {res.content_as[dict]}')
insert(key, value, *opts, **kwargs) Awaitable[MutationResult]

Inserts a new document to the collection, failing if the document already exists.

Parameters:
  • key (str) – Document key to insert.

  • value (JSONType) – The value of the document to insert.

  • opts (InsertOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided InsertOptions

Returns:

A future that contains an instance of MutationResult if successful.

Return type:

Awaitable[MutationResult]

Raises:

DocumentExistsException – If the document already exists on the server.

Examples

Simple insert operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_8091'
airline = {
    "type": "airline",
    "id": 8091,
    "callsign": "CBS",
    "iata": None,
    "icao": None,
    "name": "Couchbase Airways",
}
res = await collection.insert(key, doc)

Simple insert operation with options:

from couchbase.durability import DurabilityLevel, ServerDurability
from couchbase.options import InsertOptions

# ... other code ...

key = 'airline_8091'
airline = {
    "type": "airline",
    "id": 8091,
    "callsign": "CBS",
    "iata": None,
    "icao": None,
    "name": "Couchbase Airways",
}
durability = ServerDurability(level=DurabilityLevel.PERSIST_TO_MAJORITY)
res = await collection.insert(key, doc, InsertOptions(durability=durability))
lookup_in(key, spec, *opts, **kwargs) Awaitable[LookupInResult]

Performs a lookup-in operation against a document, fetching individual fields or information about specific fields inside the document value.

Parameters:
  • key (str) – The key for the document look in.

  • spec (Iterable[Spec]) – A list of specs describing the data to fetch from the document.

  • opts (LookupInOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided LookupInOptions

Returns:

A future that contains an instance of LookupInResult if successful.

Return type:

Awaitable[LookupInResult]

Raises:

DocumentNotFoundException – If the key provided does not exist on the server.

Examples

Simple look-up in operation:

import couchbase.subdocument as SD

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('hotel')

key = 'hotel_10025'
res = await collection.lookup_in(key, (SD.get("geo"),))
print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')

Simple look-up in operation with options:

from datetime import timedelta

import couchbase.subdocument as SD
from couchbase.options import LookupInOptions

# ... other code ...

key = 'hotel_10025'
res = await collection.lookup_in(key,
                            (SD.get("geo"),),
                            LookupInOptions(timeout=timedelta(seconds=2)))
print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')
mutate_in(key, spec, *opts, **kwargs) Awaitable[MutateInResult]

Performs a mutate-in operation against a document. Allowing atomic modification of specific fields within a document. Also enables access to document extended-attributes (i.e. xattrs).

Parameters:
  • key (str) – The key for the document look in.

  • spec (Iterable[Spec]) – A list of specs describing the operations to perform on the document.

  • opts (MutateInOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided MutateInOptions

Returns:

A future that contains an instance of MutateInResult if successful.

Return type:

Awaitable[MutateInResult]

Raises:

DocumentNotFoundException – If the key provided does not exist on the server.

Examples

Simple mutate-in operation:

import couchbase.subdocument as SD

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('hotel')

key = 'hotel_10025'
res = await collection.mutate_in(key, (SD.replace("city", "New City"),))

Simple mutate-in operation with options:

from datetime import timedelta

import couchbase.subdocument as SD
from couchbase.options import MutateInOptions

# ... other code ...

key = 'hotel_10025'
res = await collection.mutate_in(key,
                            (SD.replace("city", "New City"),),
                            MutateInOptions(timeout=timedelta(seconds=2)))
remove(key, *opts, **kwargs) Awaitable[MutationResult]

Removes an existing document. Failing if the document does not exist.

Parameters:
  • key (str) – Key for the document to remove.

  • opts (RemoveOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided RemoveOptions

Returns:

A future that contains an instance of MutationResult if successful.

Return type:

Awaitable[MutationResult]

Raises:

DocumentNotFoundException – If the document does not exist on the server.

Examples

Simple remove operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

res = collection.remove('airline_10')

Simple remove operation with options:

from couchbase.durability import DurabilityLevel, ServerDurability
from couchbase.options import RemoveOptions

# ... other code ...

durability = ServerDurability(level=DurabilityLevel.MAJORITY)
res = collection.remove('airline_10', RemoveOptions(durability=durability))
replace(key, value, *opts, **kwargs) Awaitable[MutationResult]

Replaces the value of an existing document. Failing if the document does not exist.

Parameters:
  • key (str) – Document key to replace.

  • value (JSONType) – The value of the document to replace.

  • opts (ReplaceOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided ReplaceOptions

Returns:

A future that contains an instance of MutationResult if successful.

Return type:

Awaitable[MutationResult]

Raises:

DocumentNotFoundException – If the document does not exist on the server.

Examples

Simple replace operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_8091'
res = await collection.get(key)
content = res.content_as[dict]
airline["name"] = "Couchbase Airways!!"
res = await collection.replace(key, doc)

Simple replace operation with options:

from couchbase.durability import DurabilityLevel, ServerDurability
from couchbase.options import ReplaceOptions

# ... other code ...

key = 'airline_8091'
res = await collection.get(key)
content = res.content_as[dict]
airline["name"] = "Couchbase Airways!!"
durability = ServerDurability(level=DurabilityLevel.MAJORITY)
res = await collection.replace(key, doc, InsertOptions(durability=durability))
touch(key, expiry, *opts, **kwargs) Awaitable[MutationResult]

Updates the expiry on an existing document.

Parameters:
  • key (str) – Key for the document to touch.

  • expiry (timedelta) – The new expiry for the document.

  • opts (TouchOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided TouchOptions

Returns:

A future that contains an instance of MutationResult if successful.

Return type:

Awaitable[MutationResult]

Raises:

DocumentNotFoundException – If the document does not exist on the server.

Examples

Simple touch operation:

from datetime import timedelta

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

res = await collection.touch('airline_10', timedelta(seconds=300))

Simple touch operation with options:

from datetime import timedelta

from couchbase.options import TouchOptions

# ... other code ...

res = await collection.touch('airline_10',
                        timedelta(seconds=300),
                        TouchOptions(timeout=timedelta(seconds=2)))
unlock(key, cas, *opts, **kwargs) Awaitable[None]

Unlocks a previously locked document.

Parameters:
  • key (str) – The key for the document to unlock.

  • cas (int) – The CAS of the document, used to validate lock ownership.

  • opts (couchbaseoptions.UnlockOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided UnlockOptions

Returns:

A future that contains an empty result if successful.

Return type:

Awaitable[None]

Raises:

Examples

Simple unlock operation:

from datetime import timedelta

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_10'
res = await collection.get_and_lock(key, timedelta(seconds=5))
await collection.unlock(key, res.cas)
# this should be okay once document is unlocked
await collection.upsert(key, res.content_as[dict])
upsert(key, value, *opts, **kwargs) Awaitable[MutationResult]

Upserts a document to the collection. This operation succeeds whether or not the document already exists.

Parameters:
  • key (str) – Document key to upsert.

  • value (JSONType) – The value of the document to upsert.

  • opts (UpsertOptions) – Optional parameters for this operation.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used in place or to override provided UpsertOptions

Returns:

A future that contains an instance of MutationResult if successful.

Return type:

Awaitable[MutationResult]

Examples

Simple upsert operation:

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

key = 'airline_8091'
airline = {
    "type": "airline",
    "id": 8091,
    "callsign": "CBS",
    "iata": None,
    "icao": None,
    "name": "Couchbase Airways",
}
res = await collection.upsert(key, doc)

Simple upsert operation with options:

from couchbase.durability import DurabilityLevel, ServerDurability
from couchbase.options import UpsertOptions

# ... other code ...

key = 'airline_8091'
airline = {
    "type": "airline",
    "id": 8091,
    "callsign": "CBS",
    "iata": None,
    "icao": None,
    "name": "Couchbase Airways",
}
durability = ServerDurability(level=DurabilityLevel.MAJORITY)
res = await collection.upsert(key, doc, InsertOptions(durability=durability))
scan(scan_type, *opts, **kwargs) ScanResultIterable

Execute a key-value range scan operation from the collection.

Note

Use this API for low concurrency batch queries where latency is not a critical as the system may have to scan a lot of documents to find the matching documents. For low latency range queries, it is recommended that you use SQL++ with the necessary indexes.

Parameters:
Raises:
Returns:

An instance of ScanResultIterable.

Return type:

ScanResultIterable

Examples

Simple range scan operation:

from couchbase.kv_range_scan import RangeScan
from couchbase.options import ScanOptions

# ... other code ...

bucket = cluster.bucket('travel-sample')
collection = bucket.scope('inventory').collection('airline')

scan_type = RangeScan(ScanTerm('airline-00'), ScanTerm('airline-99'))
scan_iter = collection.scan(scan_type, ScanOptions(ids_only=True))

async for res in scan_iter:
    print(res)
binary() BinaryCollection

Creates a BinaryCollection instance, allowing access to various binary operations possible against a collection.

See also

BinaryCollection

Returns:

A BinaryCollection instance.

Return type:

BinaryCollection

couchbase_list(key) CouchbaseList

Returns a CouchbaseList permitting simple list storage in a document.

See also

CouchbaseList

Returns:

A CouchbaseList instance.

Return type:

CouchbaseList

couchbase_map(key) CouchbaseMap

Returns a CouchbaseMap permitting simple map storage in a document.

See also

CouchbaseMap

Returns:

A CouchbaseMap instance.

Return type:

CouchbaseMap

couchbase_set(key) CouchbaseSet

Returns a CouchbaseSet permitting simple map storage in a document.

See also

CouchbaseSet

Returns:

A CouchbaseSet instance.

Return type:

CouchbaseSet

couchbase_queue(key) CouchbaseQueue

Returns a CouchbaseQueue permitting simple map storage in a document.

See also

CouchbaseQueue

Returns:

A CouchbaseQueue instance.

Return type:

CouchbaseQueue