Collection
- class couchbase.collection.Collection(scope: Scope, name: str)
A collection in a scope, and the key-value operations on its documents.
Warning
couchbase.collection.CBCollectionis deprecated, and will be removed in a future release. ImportCollectionfromcouchbase.collection.Get one from
collection().- Parameters:
- binary() BinaryCollection
Get the binary operations on this collection.
See also
- Returns:
A BinaryCollection instance.
- Return type:
- couchbase_list(key: str) CouchbaseList
Returns a CouchbaseList permitting simple list storage in a document.
See also
- Returns:
A CouchbaseList instance.
- Return type:
- couchbase_map(key: str) CouchbaseMap
Returns a CouchbaseMap permitting simple map storage in a document.
See also
- Returns:
A CouchbaseMap instance.
- Return type:
- couchbase_queue(key: str) CouchbaseQueue
Returns a CouchbaseQueue permitting simple map storage in a document.
See also
- Returns:
A CouchbaseQueue instance.
- Return type:
- couchbase_set(key: str) CouchbaseSet
Returns a CouchbaseSet permitting simple map storage in a document.
See also
- Returns:
A CouchbaseSet instance.
- Return type:
- exists(key: str, opts: ExistsOptions | None = None, **kwargs: Unpack[ExistsOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
ExistsOptions
- Returns:
An instance of
ExistsResult.- Return type:
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"}')
- exists_multi(keys: list[str], opts: ExistsMultiOptions | None = None, **kwargs: Unpack[ExistsMultiOptionsKwargs]) MultiExistsResult
For each key in the provided list, check if the document associated with the key exists.
- Parameters:
keys (list[str]) – The keys to use for the multiple exists operations.
opts (
ExistsMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
ExistsMultiOptions
- Returns:
An instance of
MultiExistsResult.- Return type:
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"}')
- get(key: str, opts: GetOptions | None = None, **kwargs: Unpack[GetOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
GetOptions
- Returns:
An instance of
GetResult.- Return type:
- 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: str, opts: GetAllReplicasOptions | None = None, **kwargs: Unpack[GetAllReplicasOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
GetAllReplicasOptions
- Returns:
A stream of
GetReplicaResultrepresenting both active and replicas of the document retrieved.- Return type:
Iterable[
GetReplicaResult]- Raises:
DocumentNotFoundException – If the key provided does not exist on the server.
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_all_replicas_multi(keys: list[str], opts: GetAllReplicasMultiOptions | None = None, **kwargs: Unpack[GetAllReplicasMultiOptionsKwargs]) MultiGetReplicaResult[list[GetReplicaResult]]
Retrieves each document from the active copy and every available replica.
- Parameters:
keys (list[str]) – The keys to use for the multiple get operations.
opts (
GetAllReplicasMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
GetAllReplicasMultiOptions
- Returns:
An instance of
MultiGetReplicaResult, mapping each key to a list ofGetReplicaResult.- Return type:
- 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_and_lock(key: str, lock_time: timedelta, opts: GetAndLockOptions | None = None, **kwargs: Unpack[GetAndLockOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
GetAndLockOptions
- Returns:
An instance of
GetResult.- Return type:
- 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_lock_multi(keys: list[str], lock_time: timedelta, opts: GetAndLockMultiOptions | None = None, **kwargs: Unpack[GetAndLockMultiOptionsKwargs]) MultiGetResult
For each key in the provided list, lock the document associated with the key.
- 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 – keyword arguments that can be used in place or to override provided
GetAndLockMultiOptions
- Returns:
An instance of
MultiGetResult.- Return type:
- 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_and_touch(key: str, expiry: timedelta, opts: GetAndTouchOptions | None = None, **kwargs: Unpack[GetAndTouchOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
GetAndTouchOptions
- Returns:
An instance of
GetResult.- Return type:
- 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: str, opts: GetAnyReplicaOptions | None = None, **kwargs: Unpack[GetAnyReplicaOptionsKwargs]) GetReplicaResult
Retrieves a document from whichever of the active copy and the replicas answers first.
- Parameters:
key (str) – The key for the document to retrieve.
opts (
GetAnyReplicaOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
GetAnyReplicaOptions
- Returns:
An instance of
GetReplicaResult.- Return type:
- 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]}')
- get_any_replica_multi(keys: list[str], opts: GetAnyReplicaMultiOptions | None = None, **kwargs: Unpack[GetAnyReplicaMultiOptionsKwargs]) MultiGetReplicaResult[GetReplicaResult]
Retrieves each document from whichever of the active copy and the replicas answers first.
- Parameters:
keys (list[str]) – The keys to use for the multiple get operations.
opts (
GetAnyReplicaMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
GetAnyReplicaMultiOptions
- Returns:
An instance of
MultiGetReplicaResult, mapping each key to a singleGetReplicaResult.- Return type:
- 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]}')
- get_multi(keys: list[str], opts: GetMultiOptions | None = None, **kwargs: Unpack[GetMultiOptionsKwargs]) MultiGetResult
For each key in the provided list, retrieve the document associated with the key.
- Parameters:
keys (list[str]) – The keys to use for the multiple get operations.
opts (
GetMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
GetMultiOptions
- Returns:
An instance of
MultiGetResult.- Return type:
- 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_replica(key: str, strategy: GetReplicaStrategy, opts: GetReplicaOptions | None = None, **kwargs: Unpack[GetReplicaOptionsKwargs]) GetReplicaResult
Retrieves a document from the replica the strategy selects.
- Parameters:
key (str) – The key for the document to retrieve.
strategy (
GetReplicaStrategy) – Selects the replica to read, created byfrom_index().opts (
GetReplicaOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
GetReplicaOptions
- Returns:
An instance of
GetReplicaResult.- Return type:
- Raises:
DocumentNotFoundOnReplicaException – If the replica does not hold the document.
ReplicaIndexOutOfBoundsException – If the bucket has no replica at the requested index, and the strategy does not wrap.
ReplicaIndexCurrentlyUnavailableException – If the requested replica cannot be read now, and the strategy does not wrap or no other replica can be read either.
InvalidArgumentException – If
strategywas not created byfrom_index().
Examples
Read the first replica:
from couchbase.replica_reads import GetReplicaStrategy, ReplicaIndex # ... other code ... res = collection.get_replica('airline_10', GetReplicaStrategy.from_index(ReplicaIndex.FIRST)) print(f'Document value: {res.content_as[dict]}')
Read the second replica, or the next one that can be read:
res = collection.get_replica('airline_10', GetReplicaStrategy.from_index(ReplicaIndex.SECOND, wrap=True))
- insert(key: str, value: Any, opts: InsertOptions | None = None, **kwargs: Unpack[InsertOptionsKwargs]) MutationResult
Inserts a new document to the collection, failing if the document already exists.
- Parameters:
key (str) – Document key to insert.
value (DocumentValue) – The value of the document to insert.
opts (
InsertOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
InsertOptions
- Returns:
An instance of
MutationResult.- Return type:
- 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))
- insert_multi(keys_and_docs: Mapping[str, Any], opts: InsertMultiOptions | None = None, **kwargs: Unpack[InsertMultiOptionsKwargs]) MultiMutationResult
Inserts a new document for each key-value pair, failing for a key whose document already exists.
- Parameters:
keys_and_docs (Mapping[str, DocumentValue]) – The keys and values/docs to use for the multiple insert operations.
opts (
InsertMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
InsertMultiOptions
- Returns:
An instance of
MultiMutationResult.- Return type:
- 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: list[str], lock_time: timedelta, opts: GetAndLockMultiOptions | None = None, **kwargs: Unpack[GetAndLockMultiOptionsKwargs]) MultiGetResult
For each key in the provided list, lock the document associated with the key.
Deprecated since version 4.2.0: Use
get_and_lock_multi()instead.
- lookup_in(key: str, spec: Iterable[Spec], opts: LookupInOptions | None = None, **kwargs: Unpack[LookupInOptionsKwargs]) LookupInResult
Fetches individual fields of a document, or information about them.
- 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 – keyword arguments that can be used in place or to override provided
LookupInOptions
- Returns:
An instance of
LookupInResult.- Return type:
- 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)}')
- lookup_in_all_replicas(key: str, spec: Iterable[Spec], opts: LookupInAllReplicasOptions | None = None, **kwargs: Unpack[LookupInAllReplicasOptionsKwargs]) Iterable[LookupInReplicaResult]
Fetches fields of a document from the active copy and every available replica.
- 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 (
LookupInAllReplicasOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
LookupInAllReplicasOptions
- Returns:
A stream of
LookupInReplicaResultrepresenting both active and replicas of the sub-document retrieved.- Return type:
Iterable[
LookupInReplicaResult]- Raises:
DocumentNotFoundException – If the key provided does not exist on the server.
Examples
Simple lookup_in_all_replicas operation:
import couchbase.subdocument as SD # ... other code ... bucket = cluster.bucket('travel-sample') collection = bucket.scope('inventory').collection('hotel') key = 'hotel_10025' results = collection.lookup_in_all_replicas(key, (SD.get("geo"),)) for res in results: print(f'Document is replica: {res.is_replica}') print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')
Simple lookup_in_all_replicas operation with options:
import couchbase.subdocument as SD from datetime import timedelta from couchbase.options import LookupInAllReplicasOptions # ... other code ... key = 'hotel_10025' opts = LookupInAllReplicasOptions(timeout=timedelta(seconds=2)) results = collection.lookup_in_all_replicas(key, (SD.get("geo"),), opts) for res in results: print(f'Document is replica: {res.is_replica}') print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')
Stream lookup_in_all_replicas results:
from datetime import timedelta from couchbase.options import GetAllReplicasOptions # ... other code ... key = 'hotel_10025' opts = LookupInAllReplicasOptions(timeout=timedelta(seconds=2)) results = collection.lookup_in_all_replicas(key, (SD.get("geo"),), opts) while True: try: res = next(results) print(f'Document is replica: {res.is_replica}') print(f'Hotel {key} coordinates: {res.content_as[dict](0)}') except StopIteration: print('Done streaming replicas.') break
- lookup_in_any_replica(key: str, spec: Iterable[Spec], opts: LookupInAnyReplicaOptions | None = None, **kwargs: Unpack[LookupInAnyReplicaOptionsKwargs]) LookupInReplicaResult
Fetches fields of a document from whichever of the active copy and the replicas answers first.
- 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 (
LookupInAnyReplicaOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
LookupInAnyReplicaOptions
- Returns:
An instance of
LookupInReplicaResult.- Return type:
- Raises:
DocumentUnretrievableException – If the key provided does not exist on the server.
Examples
Simple lookup_in_any_replica 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_any_replica(key, (SD.get("geo"),)) print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')
Simple lookup_in_any_replica operation with options:
from datetime import timedelta import couchbase.subdocument as SD from couchbase.options import LookupInAnyReplicaOptions # ... other code ... key = 'hotel_10025' res = collection.lookup_in_any_replica(key, (SD.get("geo"),), LookupInAnyReplicaOptions(timeout=timedelta(seconds=2))) print(f'Document is replica: {res.is_replica}') print(f'Hotel {key} coordinates: {res.content_as[dict](0)}')
- mutate_in(key: str, spec: Iterable[Spec], opts: MutateInOptions | None = None, **kwargs: Unpack[MutateInOptionsKwargs]) MutateInResult
Atomically modifies individual fields of a document.
The fields may include the document’s extended attributes (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 – keyword arguments that can be used in place or to override provided
MutateInOptions
- Returns:
An instance of
MutateInResult.- Return type:
- 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)))
- query_indexes() CollectionQueryIndexManager
Get a manager for the query indexes of this collection.
- Returns:
A
CollectionQueryIndexManagerinstance.- Return type:
- remove(key: str, opts: RemoveOptions | None = None, **kwargs: Unpack[RemoveOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
RemoveOptions
- Returns:
An instance of
MutationResult.- Return type:
- 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))
- remove_multi(keys: list[str], opts: RemoveMultiOptions | None = None, **kwargs: Unpack[RemoveMultiOptionsKwargs]) MultiMutationResult
Removes the document for each key, failing for a key whose document does not exist.
- Parameters:
keys (list[str]) – The keys to use for the multiple remove operations.
opts (
RemoveMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
RemoveMultiOptions
- Returns:
An instance of
MultiMutationResult.- Return type:
- 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(key: str, value: Any, opts: ReplaceOptions | None = None, **kwargs: Unpack[ReplaceOptionsKwargs]) MutationResult
Replaces the value of an existing document. Failing if the document does not exist.
- Parameters:
key (str) – Document key to replace.
value (DocumentValue) – The value of the document to replace.
opts (
ReplaceOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
ReplaceOptions
- Returns:
An instance of
MutationResult.- Return type:
- 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))
- replace_multi(keys_and_docs: Mapping[str, Any], opts: ReplaceMultiOptions | None = None, **kwargs: Unpack[ReplaceMultiOptionsKwargs]) MultiMutationResult
Replaces the document for each key-value pair, failing for a key whose document does not exist.
- Parameters:
keys_and_docs (Mapping[str, DocumentValue]) – The keys and values/docs to use for the multiple replace operations.
opts (
ReplaceMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
ReplaceMultiOptions
- Returns:
An instance of
MultiMutationResult.- Return type:
- 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}')
- scan(scan_type: ScanType, opts: ScanOptions | None = None, **kwargs: Unpack[ScanOptionsKwargs]) 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:
scan_type (
ScanType) – Either aRangeScan,PrefixScanorSamplingScaninstance.opts (
ScanOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
ScanOptions
- Raises:
InvalidArgumentException – If scan_type is not either a RangeScan or SamplingScan instance.
InvalidArgumentException – If sort option is provided and is incorrect type.
InvalidArgumentException – If consistent_with option is provided and is not a
- Returns:
An instance of
ScanResultIterable.- Return type:
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)
- touch(key: str, expiry: timedelta, opts: TouchOptions | None = None, **kwargs: Unpack[TouchOptionsKwargs]) 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 – keyword arguments that can be used in place or to override provided
TouchOptions
- Returns:
An instance of
MutationResult.- Return type:
- 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)))
- touch_multi(keys: list[str], expiry: timedelta, opts: TouchMultiOptions | None = None, **kwargs: Unpack[TouchMultiOptionsKwargs]) MultiMutationResult
Updates the expiry of the document for each key, failing for a key whose document does not exist.
- 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 – keyword arguments that can be used in place or to override provided
TouchMultiOptions
- Returns:
An instance of
MultiMutationResult.- Return type:
- 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(key: str, cas: int, opts: UnlockOptions | None = None, **kwargs: Unpack[UnlockOptionsKwargs]) 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 (
UnlockOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
UnlockOptions
- Raises:
DocumentNotFoundException – If the key provided does not exist on the server.
DocumentLockedException – If the provided cas is invalid.
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])
- unlock_multi(keys: MultiGetResult | MultiMutationResult | dict[str, int], opts: UnlockMultiOptions | None = None, **kwargs: Unpack[UnlockMultiOptionsKwargs]) dict[str, CouchbaseException | None]
Unlocks the document behind each result, failing for one whose document does not exist.
- Parameters:
keys (MultiResultType | dict[str, int]) – The result from a previous multi operation.
opts (
UnlockMultiOptions) – Optional parameters for this operation.**kwargs – 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, CouchbaseException | None]
- 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(key: str, value: Any, opts: UpsertOptions | None = None, **kwargs: Unpack[UpsertOptionsKwargs]) 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 (DocumentValue) – The value of the document to upsert.
opts (
UpsertOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
UpsertOptions
- Returns:
An instance of
MutationResult.- Return type:
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))
- upsert_multi(keys_and_docs: Mapping[str, Any], opts: UpsertMultiOptions | None = None, **kwargs: Unpack[UpsertMultiOptionsKwargs]) MultiMutationResult
Upserts a document for each key-value pair, whether or not the document already exists.
- Parameters:
keys_and_docs (Mapping[str, DocumentValue]) – The keys and values/docs to use for the multiple upsert operations.
opts (
UpsertMultiOptions) – Optional parameters for this operation.**kwargs – keyword arguments that can be used in place or to override provided
UpsertMultiOptions
- Returns:
An instance of
MultiMutationResult.- Return type:
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}')