Core couchbase API

Cluster

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

Raises:
static connect(connstr, *options, **kwargs) Cluster

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:

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))
property connected: bool

Indicator on if the cluster has been connected or not.

Type:

bool

bucket(bucket_name) Bucket

Creates a Bucket instance to a specific bucket.

See also

bucket.Bucket

Parameters:

bucket_name (str) – Name of the bucket to reference

Returns:

A bucket instance

Return type:

Bucket

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

  • BucketNotFoundException – If provided bucket_name cannot be found.

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

PingResult

diagnostics(*opts, **kwargs) 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:

DiagnosticsResult

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

  • couchbase.Scope.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;')
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()}')
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.

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

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}')
search(index, request, *options, **kwargs) 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

  • 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) – Type of search request 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 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]
request = search.SearchRequest.create(VectorSearch.from_vector_query(VectorQuery('vector_field', vector)))
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}')
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.

  • Scope.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)
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()}')
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

close()

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

class couchbase.bucket.Bucket(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) Scope

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

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

Creates a Collection instance of the default collection.

Returns:

A Collection instance of the default collection.

Return type:

Collection

ping(*opts, **kwargs) 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:

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)

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

class couchbase.scope.Scope(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: str

The name of this Scope instance.

Type:

str

property bucket_name: str

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

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;')
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]))
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}))
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))
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))

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

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

for row in q_res.rows():
    print(f'Found row: {row}')
    print(f'Fields: {row.fields}')
    print(f'Locations: {row.locations}')
search(index, request, *options, **kwargs) SearchResult

Executes an search against the scope.

Note

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

See also

  • ScopeSearchIndexManager: for how to manage search indexes.

  • search(): for how to execute cluster-level search

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

  • request (SearchRequest) – Type of search request 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 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 = scope.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]
request = search.SearchRequest.create(VectorSearch.from_vector_query(VectorQuery('vector_field', vector)))
q_res = scope.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 = scope.search('travel-sample-vector-index', request, SearchOptions(limit=10))

for row in q_res.rows():
    print(f'Found row: {row}')
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)
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]))
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}))
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)
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()}')
search_indexes() ScopeSearchIndexManager

Get a ScopeSearchIndexManager which can be used to manage the search indexes of this scope.

Returns:

A ScopeSearchIndexManager instance.

Return type:

ScopeSearchIndexManager

Collection

class couchbase.collection.Collection
property name: str

The name of this Collection instance.

Type:

str

exists(key, *opts, **kwargs) 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:

An instance of ExistsResult.

Return type:

ExistsResult

Examples

Simple exists operation:

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

key = 'airline_10'
res = 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 = 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) 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:

An instance of GetResult.

Return type:

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 = 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 = collection.get('airline_10', GetOptions(timeout=timedelta(seconds=2)))
print(f'Document value: {res.content_as[dict]}')
get_all_replicas(key, *opts, **kwargs) Iterable[GetReplicaResult]

Retrieves the value of a document from the collection returning both active and all available replicas.

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

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

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

Returns:

A stream of GetReplicaResult representing both active and replicas of the document retrieved.

Return type:

Iterable[GetReplicaResult]

Raises:

Examples

Simple get_all_replicas operation:

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

result = collection.get_all_replicas('airline_10')
for res in results:
    print(f'Document is replica: {res.is_replica}')
    print(f'Document value: {res.content_as[dict]}')

Simple get_all_replicas operation with options:

from datetime import timedelta
from couchbase.options import GetAllReplicasOptions

# ... other code ...

result = collection.get_all_replicas('airline_10', GetAllReplicasOptions(timeout=timedelta(seconds=10)))
for res in result:
    print(f'Document is replica: {res.is_replica}')
    print(f'Document value: {res.content_as[dict]}')

Stream get_all_replicas results:

from datetime import timedelta
from couchbase.options import GetAllReplicasOptions

# ... other code ...

result = collection.get_all_replicas('airline_10', GetAllReplicasOptions(timeout=timedelta(seconds=10)))
while True:
    try:
        res = next(result)
        print(f'Document is replica: {res.is_replica}')
        print(f'Document value: {res.content_as[dict]}')
    except StopIteration:
        print('Done streaming replicas.')
        break
get_and_lock(key, lock_time, *opts, **kwargs) 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:

An instance of GetResult.

Return type:

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

An instance of GetResult.

Return type:

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 = 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 = collection.get_and_touch(key,
                            timedelta(seconds=20),
                            GetAndTouchOptions(timeout=timedelta(seconds=2)))
print(f'Document w/ updated expiry: {res.content_as[dict]}')
get_any_replica(key, *opts, **kwargs) GetReplicaResult

Retrieves the value of a document from the collection leveraging both active and all available replicas returning the first available.

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

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

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

Returns:

An instance of GetReplicaResult.

Return type:

GetReplicaResult

Raises:

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

Examples

Simple get_any_replica operation:

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

res = collection.get_any_replica('airline_10')
print(f'Document is replica: {res.is_replica}')
print(f'Document value: {res.content_as[dict]}')

Simple get_any_replica operation with options:

from datetime import timedelta
from couchbase.options import GetAnyReplicaOptions

# ... other code ...

res = collection.get_any_replica('airline_10', GetAnyReplicaOptions(timeout=timedelta(seconds=5)))
print(f'Document is replica: {res.is_replica}')
print(f'Document value: {res.content_as[dict]}')
insert(key, value, *opts, **kwargs) 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:

An instance of MutationResult.

Return type:

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 = 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 = collection.insert(key, doc, InsertOptions(durability=durability))
lookup_in(key, spec, *opts, **kwargs) 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:

An instance of LookupInResult.

Return type:

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

An instance of MutateInResult.

Return type:

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 = 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 = collection.mutate_in(key,
                            (SD.replace("city", "New City"),),
                            MutateInOptions(timeout=timedelta(seconds=2)))
remove(key, *opts, **kwargs) 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:

An instance of MutationResult.

Return type:

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

An instance of MutationResult.

Return type:

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 = collection.get(key)
content = res.content_as[dict]
airline["name"] = "Couchbase Airways!!"
res = 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 = collection.get(key)
content = res.content_as[dict]
airline["name"] = "Couchbase Airways!!"
durability = ServerDurability(level=DurabilityLevel.MAJORITY)
res = collection.replace(key, doc, InsertOptions(durability=durability))
touch(key, expiry, *opts, **kwargs) 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:

An instance of MutationResult.

Return type:

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 = collection.touch('airline_10', timedelta(seconds=300))

Simple touch operation with options:

from datetime import timedelta

from couchbase.options import TouchOptions

# ... other code ...

res = collection.touch('airline_10',
                        timedelta(seconds=300),
                        TouchOptions(timeout=timedelta(seconds=2)))
unlock(key, cas, *opts, **kwargs) 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

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 = collection.get_and_lock(key, timedelta(seconds=5))
collection.unlock(key, res.cas)
# this should be okay once document is unlocked
collection.upsert(key, res.content_as[dict])
upsert(key, value, *opts, **kwargs) 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:

An instance of MutationResult.

Return type:

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

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

list_append(key, value, create=False, **kwargs) OperationResult

Add an item to the end of a list.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.append() instead.

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

  • value (JSONType) – The value to append to the list.

  • create (bool, optional) – Whether the list should be created if it does not exist.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

couchbase~.result.OperationResult

Raises:

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

list_prepend(key, value, create=False, **kwargs) OperationResult

Add an item to the beginning of a list.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.prepend() instead.

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

  • value (JSONType) – The value to prepend to the list.

  • create (bool, optional) – Whether the list should be created if it does not exist.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

list_set(key, index, value, **kwargs) OperationResult

Sets an item within a list at a given position.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.set_at() instead.

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

  • index (int) – The position to replace.

  • value (JSONType) – The value to prepend to the list.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

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

  • IndexError – If the index is out of bounds.

list_get(key, index, **kwargs) Any

Get a specific element within a list.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.get_at() instead.

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

  • index (int) – The position to retrieve.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

The value of the element at the specified index.

Return type:

Any

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

  • IndexError – If the index is out of bounds.

list_remove(key, index, **kwargs) OperationResult

Remove the element at a specific index from a list.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.remove_at() instead.

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

  • index (int) – The position to remove.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

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

  • IndexError – If the index is out of bounds.

list_size(key, **kwargs) int

Returns the number of items in the list.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseList.size() instead.

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

The number of items in the list.

Return type:

int

Raises:

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

couchbase_map(key) CouchbaseMap

Returns a CouchbaseMap permitting simple map storage in a document.

See also

CouchbaseMap

Returns:

A CouchbaseMap instance.

Return type:

CouchbaseMap

map_add(key, mapkey, value, create=False, **kwargs) OperationResult

Set a value for a key in a map.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseMap.add() instead.

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

  • mapkey (str) – The key in the map to set.

  • value (Any) – The value to use.

  • create (bool, optional) – Whether the map should be created if it does not exist.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

map_get(key, mapkey, **kwargs) Any

Retrieve a value from a map.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseMap.get() instead.

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

  • mapkey (str) – The key in the map to set.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

The value of the specified key.

Return type:

Any

Raises:

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

map_remove(key, mapkey, **kwargs) OperationResult

Remove an item from a map.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseMap.remove() instead.

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

  • mapkey (str) – The key in the map to set.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

map_size(key, **kwargs) int

Get the number of items in the map.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseMap.remove() instead.

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

The number of items in the map.

Return type:

int

Raises:

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

couchbase_set(key) CouchbaseSet

Returns a CouchbaseSet permitting simple map storage in a document.

See also

CouchbaseSet

Returns:

A CouchbaseSet instance.

Return type:

CouchbaseSet

set_add(key, value, create=False, **kwargs) OperationResult | None

Add an item to a set if the item does not yet exist.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseSet.add() instead.

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

  • value (Any) – The value to add to the set.

  • create (bool, optional) – Whether the set should be created if it does not exist.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

set_remove(key, value, **kwargs) OperationResult | None

Remove an item from a set.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseSet.remove() instead.

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

  • value (Any) – The value to remove from the set.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

set_size(key, **kwargs) int

Get the length of a set.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseSet.size() instead.

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

The length of a set.

Return type:

int

Raises:

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

set_contains(key, value, **kwargs) bool

Determine if an item exists in a set

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseSet.contains() instead.

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

  • value (Any) – The value to check for.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

True if the set contains the specified value. False othwerwise.

Return type:

bool

Raises:

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

couchbase_queue(key) CouchbaseQueue

Returns a CouchbaseQueue permitting simple map storage in a document.

See also

CouchbaseQueue

Returns:

A CouchbaseQueue instance.

Return type:

CouchbaseQueue

queue_push(key, value, create=False, **kwargs) OperationResult

Add an item to the end of a queue.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseQueue.push() instead.

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

  • value (Any) – The value to add.

  • create (bool, optional) – Whether the queue should be created if it does not exist.

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

queue_pop(key, **kwargs) OperationResult

Remove and return the first item queue.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseQueue.pop() instead.

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

  • **kwargs (Dict[str, Any]) – keyword arguments that can be used as optional parameters for this operation.

Returns:

An instance of OperationResult.

Return type:

OperationResult

Raises:

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

queue_size(key) int

Get the length of a queue.

Warning

This method is deprecated and will be removed in a future version. Use CouchbaseQueue.size() instead.

Parameters:

key (str) – The key for the queue document.

Returns:

The length of the queue.

Return type:

int

Raises:

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

get_multi(keys, *opts, **kwargs) MultiGetResult

For each key in the provided list, retrieve the document associated with the key.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple get operations.

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

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

Returns:

An instance of MultiGetResult.

Return type:

MultiGetResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple get-multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_multi(keys)
for k, v in res.results.items():
    print(f'Doc {k} has value: {v.content_as[dict]}')

Simple get-multi operation, raise an Exception if an Exception occurs:

from couchbase.options import GetMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_multi(keys,
                            GetMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Doc {k} has value: {v.content_as[dict]}')

Simple get-multi operation, individual key options:

from datetime import timedelta

from couchbase.options import GetMultiOptions, GetOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': GetOptions(timeout=timedelta(seconds=10))}
res = collection.get_multi(keys,
                            GetMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Doc {k} has value: {v.content_as[dict]}')
get_and_lock_multi(keys, lock_time, *opts, **kwargs) MultiGetResult

For each key in the provided list, lock the document associated with the key.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple lock operations.

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

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

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

Returns:

An instance of MultiGetResult.

Return type:

MultiGetResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple get_and_lock_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_and_lock_multi(keys, timedelta(seconds=20))
for k, v in res.results.items():
    print(f'Locked document: key={k}, content={v.content_as[str]}')

Simple get_and_lock_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import GetAndLockMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_and_lock_multi(keys,
                                     timedelta(seconds=20),
                                     GetAndLockMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Locked document: key={k}, content={v.content_as[str]}')

Simple get_and_lock_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import GetAndLockMultiOptions, GetAndLockOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': GetAndLockOptions(timeout=timedelta(seconds=10))}
res = collection.get_and_lock_multi(keys,
                                     timedelta(seconds=20),
                                     GetAndLockMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Locked document: key={k}, content={v.content_as[str]}')
get_all_replicas_multi(keys, *opts, **kwargs) MultiGetReplicaResult

For each key in the provided list, retrieve the document from the collection returning both active and all available replicas.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple get operations.

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

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

Returns:

An instance of MultiGetReplicaResult.

Return type:

MultiGetReplicaResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple get_all_replicas_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_all_replicas_multi(keys)
for k, docs in res.results.items():
    for doc in docs:
        if doc.is_replica:
            print(f'Replica doc {k} has value: {doc.content_as[dict]}')
        else:
            print(f'Active doc {k} has value: {doc.content_as[dict]}')

Simple get_all_replicas_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import GetAllReplicasMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_all_replicas_multi(keys,
                            GetAllReplicasMultiOptions(return_exceptions=False))
for k, docs in res.results.items():
    for doc in docs:
        if doc.is_replica:
            print(f'Replica doc {k} has value: {doc.content_as[dict]}')
        else:
            print(f'Active doc {k} has value: {doc.content_as[dict]}')

Simple get_all_replicas_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import GetAllReplicasMultiOptions, GetAllReplicasOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': GetAllReplicasOptions(timeout=timedelta(seconds=10))}
res = collection.get_all_replicas_multi(keys,
                            GetAllReplicasMultiOptions(per_key_options=per_key_opts))
for k, docs in res.results.items():
    for doc in docs:
        if doc.is_replica:
            print(f'Replica doc {k} has value: {doc.content_as[dict]}')
        else:
            print(f'Active doc {k} has value: {doc.content_as[dict]}')
get_any_replica_multi(keys, *opts, **kwargs) MultiGetReplicaResult

For each key in the provided list, retrieve the document associated with the key from the collection leveraging both active and all available replicas returning the first available.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple get operations.

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

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

Returns:

An instance of MultiGetReplicaResult.

Return type:

MultiGetReplicaResult

Raises:

DocumentUnretrievableException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple get_any_replica_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_any_replica_multi(keys)
for k, v in res.results.items():
    if v.is_replica:
        print(f'Replica doc {k} has value: {v.content_as[dict]}')
    else:
        print(f'Active doc {k} has value: {v.content_as[dict]}')

Simple get_any_replica_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import GetAnyReplicaMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_any_replica_multi(keys,
                            GetAnyReplicaMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    if v.is_replica:
        print(f'Replica doc {k} has value: {v.content_as[dict]}')
    else:
        print(f'Active doc {k} has value: {v.content_as[dict]}')

Simple get_any_replica_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import GetAnyReplicaMultiOptions, GetAnyReplicaOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': GetAnyReplicaOptions(timeout=timedelta(seconds=10))}
res = collection.get_any_replica_multi(keys,
                            GetAnyReplicaMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    if v.is_replica:
        print(f'Replica doc {k} has value: {v.content_as[dict]}')
    else:
        print(f'Active doc {k} has value: {v.content_as[dict]}')
exists_multi(keys, *opts, **kwargs) MultiExistsResult

For each key in the provided list, check if the document associated with the key exists.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple exists operations.

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

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

Returns:

An instance of MultiExistsResult.

Return type:

MultiExistsResult

Examples

Simple exists_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.exists_multi(keys)
for k, v in res.results.items():
    print(f'Doc with key={k} {"exists" if v.exists else "does not exist"}')

Simple exists_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import ExistsMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.exists_multi(keys,
                              ExistsMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Doc with key={k} {"exists" if v.exists else "does not exist"}')

Simple exists_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import ExistsMultiOptions, ExistsOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': ExistsOptions(timeout=timedelta(seconds=10))}
res = collection.exists_multi(keys,
                              ExistsMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Doc with key={k} {"exists" if v.exists else "does not exist"}')
insert_multi(keys_and_docs, *opts, **kwargs) MultiMutationResult

For each key, value pair in the provided dict, inserts a new document to the collection, failing if the document already exists.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys_and_docs (Dict[str, JSONType]) – The keys and values/docs to use for the multiple insert operations.

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

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

Returns:

An instance of MultiMutationResult.

Return type:

MultiMutationResult

Raises:

DocumentExistsException – If the key provided already exists on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple insert_multi operation:

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
res = collection.insert_multi(keys_and_docs)
for k, v in res.results.items():
    print(f'Doc inserted: key={k}, cas={v.cas}')

Simple insert_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import InsertMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
res = collection.insert_multi(keys_and_docs,
                              InsertMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Doc inserted: key={k}, cas={v.cas}')

Simple insert_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import InsertMultiOptions, InsertOptions

# ... other code ...

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
per_key_opts = {'doc1': InsertOptions(timeout=timedelta(seconds=10))}
res = collection.insert_multi(keys_and_docs,
                              InsertMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Doc inserted: key={k}, cas={v.cas}')
lock_multi(keys, lock_time, *opts, **kwargs) MultiGetResult

Warning

This method is deprecated and will be deprecated in a future release. Use get_and_lock_multi() instead.

remove_multi(keys, *opts, **kwargs) MultiMutationResult

For each key in the provided list, remove the existing document. This operation fails if the document does not exist.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple remove operations.

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

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

Returns:

An instance of MultiMutationResult.

Return type:

MultiMutationResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple remove_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.remove_multi(keys)

Simple remove_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import RemoveMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.remove_multi(keys,
                              RemoveMultiOptions(return_exceptions=False))

Simple remove_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import RemoveMultiOptions, RemoveOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
per_key_opts = {'doc1': RemoveOptions(timeout=timedelta(seconds=10))}
res = collection.remove_multi(keys,
                              RemoveMultiOptions(per_key_options=per_key_opts))
replace_multi(keys_and_docs, *opts, **kwargs) MultiMutationResult

For each key, value pair in the provided dict, replaces the value of a document in the collection. This operation fails if the document does not exist.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys_and_docs (Dict[str, JSONType]) – The keys and values/docs to use for the multiple replace operations.

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

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

Returns:

An instance of MultiMutationResult.

Return type:

MultiMutationResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

Examples

Simple replace_multi operation:

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_multi(keys)
keys_and_docs = {}
for k, v in res.results.items():
    # assuming document is JSON
    content = v.content_as[dict]
    content['foo'] = 'bar'
    keys_and_docs[k] = content
res = collection.replace_multi(keys_and_docs)
for k, v in res.results.items():
    print(f'Doc replaced: key={k}, cas={v.cas}')

Simple replace_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import ReplaceMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_multi(keys)
keys_and_docs = {}
for k, v in res.results.items():
    # assuming document is JSON
    content = v.content_as[dict]
    content['foo'] = 'bar'
    keys_and_docs[k] = content
res = collection.replace_multi(keys_and_docs,
                               ReplaceMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Doc replaced: key={k}, cas={v.cas}')

Simple replace_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import ReplaceMultiOptions, ReplaceOptions

# ... other code ...

collection = bucket.default_collection()
keys = ['doc1', 'doc2', 'doc3']
res = collection.get_multi(keys)
keys_and_docs = {}
for k, v in res.results.items():
    # assuming document is JSON
    content = v.content_as[dict]
    content['foo'] = 'bar'
    keys_and_docs[k] = content
per_key_opts = {'doc1': ReplaceOptions(timeout=timedelta(seconds=10))}
res = collection.replace_multi(keys_and_docs,
                               ReplaceMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Doc replaced: key={k}, cas={v.cas}')
touch_multi(keys, expiry, *opts, **kwargs) MultiMutationResult

For each key in the provided list, update the expiry on an existing document. This operation fails if the document does not exist.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (List[str]) – The keys to use for the multiple touch operations.

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

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

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

Returns:

An instance of MultiMutationResult.

Return type:

MultiMutationResult

Raises:

DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

unlock_multi(keys, *opts, **kwargs) Dict[str, None | exception]

For each result in the provided MultiResultType in the provided list, unlocks a previously locked document. This operation fails if the document does not exist.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys (Union[MultiResultType, Dict[str, int]]) – The result from a previous multi operation.

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

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

Returns:

Either None if operation successful or an Exception if the operation was unsuccessful

Return type:

Dict[str, Union[None, CouchbaseBaseException]]

Raises:
  • DocumentNotFoundException – If the key provided does not exist on the server and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

  • DocumentLockedException – If the provided cas is invalid and the return_exceptions options is False. Otherwise the exception is returned as a match to the key, but is not raised.

upsert_multi(keys_and_docs, *opts, **kwargs) MultiMutationResult

For each key, value pair in the provided dict, upserts a document to the collection. This operation succeeds whether or not the document already exists.

Note

This method is part of an uncommitted API that is unlikely to change, but may still change as final consensus on its behavior has not yet been reached.

Parameters:
  • keys_and_docs (Dict[str, JSONType]) – The keys and values/docs to use for the multiple upsert operations.

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

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

Returns:

An instance of MultiMutationResult.

Return type:

MultiMutationResult

Examples

Simple upsert_multi operation:

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
res = collection.upsert_multi(keys_and_docs)
for k, v in res.results.items():
    print(f'Doc upserted: key={k}, cas={v.cas}')

Simple upsert_multi operation, raise an Exception if an Exception occurs:

from couchbase.options import UpsertMultiOptions

# ... other code ...

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
res = collection.upsert_multi(keys_and_docs,
                              UpsertMultiOptions(return_exceptions=False))
for k, v in res.results.items():
    print(f'Doc upserted: key={k}, cas={v.cas}')

Simple upsert_multi operation, individual key options:

from datetime import timedelta

from couchbase.options import UpsertMultiOptions, UpsertOptions

# ... other code ...

collection = bucket.default_collection()
keys_and_docs = {
    'doc1': {'foo': 'bar', 'id': 'doc1'},
    'doc2': {'bar': 'baz', 'id': 'doc2'},
    'doc3': {'baz': 'qux', 'id': 'doc3'},
    'doc4': {'qux': 'quux', 'id': 'doc4'}
}
per_key_opts = {'doc1': UpsertOptions(timeout=timedelta(seconds=10))}
res = collection.upsert_multi(keys_and_docs,
                              UpsertMultiOptions(per_key_options=per_key_opts))
for k, v in res.results.items():
    print(f'Doc upserted: key={k}, cas={v.cas}')