Cluster object¶
- class couchbase.cluster.Cluster[source]¶
- classmethod connect(connection_string, options=None, **kwargs)[source]¶
Create a Cluster object. An Authenticator must be provided, either as the authenticator named parameter, or within the options argument.
- Parameters
connection_string (
str
) – the connection string for the cluster.options (
Optional
[ClusterOptions
]) – options for the cluster.kwargs (Any) – Override corresponding value in options.
- Return type
- class couchbase.cluster.ClusterOptions[source]¶
- __init__(authenticator, **kwargs)[source]¶
Options to set when creating a cluster. Note the authenticator is mandatory, all the others are optional.
- Parameters
authenticator (Authenticator) –
Authenticator
to use - seePasswordAuthenticator
andCertAuthenticator
.timeout_options (ClusterTimeoutOptions) – A
ClusterTimeoutOptions
object, with various optional timeouts.tracing_options (ClusterTracingOptions) – A
ClusterTracingOptions
object, with various options for tracing.log_redaction (bool) – Turn log redaction on/off.
compression (Compression) – A
Compression
value for this cluster.compression_min_size (int) – Min size of the data before compression kicks in.
compression_min_ratio (float) – A float representing the minimum compression ratio to use when compressing.
enable_mutation_tokens (bool) – Turn mutation tokens on/off. On by default.
tracer (CouchbaseTracer) – Tracer to use. None by default, which uses internal tracing only.
transcoder (Transcoder) – Global transcoder to use. None by default, which uses default transcoder.
- class couchbase.cluster.CertAuthenticator[source]¶
- __init__(cert_path=None, key_path=None, trust_store_path=None, cluster_username=None, cluster_password=None)[source]¶
Certificate authentication mechanism.
- Parameters
cluster_username (str) – Global cluster username. Only required for management operations
cluster_password (str) – Global cluster password. Only required for management operations
cert_path (str) – Path to the CA key
key_path (str) – Path to the key
trust_store_path (str) – Path of the certificate trust store.
- class couchbase.cluster.PasswordAuthenticator[source]¶
- __init__(username, password, cert_path=None)[source]¶
This class uses a single credential pair of username and password, and is designed to be used either with cluster management operations or with Couchbase 5.0 style usernames with role based access control.
- Parameters
username (str) – username to use for auth.
password (str) – password for the user.
cert_path (str) – Path to the CA key.
Bucket object¶
- class couchbase.bucket.Bucket[source]¶
- scope(scope_name)[source]¶
Open the named scope.
- Parameters
scope_name (
str
) – Name of scope to open on this bucket.- Return type
- Returns
the named scope
- default_collection()[source]¶
Open the default collection.
- Return type
CBCollection
- Returns
the default
Collection
object.
- collection(collection_name)[source]¶
Open a collection in the default scope.
- Parameters
collection_name (
str
) – collection name- Return type
CBCollection
- Returns
the default
Collection
object.
To open a bucket, you want to use the Cluster.
- class couchbase.cluster.Cluster[source]¶
- bucket(name)[source]¶
Open a bucket on this cluster. This doesn’t create a bucket, merely opens an existing bucket.
- Parameters
name (
str
) – Name of bucket to open.- Return type
- Returns
The :class:~.bucket.Bucket` you requested.
- Raise
BucketDoesNotExistException
if the bucket has not been created on this cluster.
Scope object¶
- class couchbase.collection.Scope[source]¶
- __init__(parent, name=None)[source]¶
Collection scope representation. Constructor should only be invoked internally.
- Parameters
parent (
Bucket
) – parent bucket.name (
Optional
[str
]) – name of scope to open
- default_collection()[source]¶
Returns the default collection for this bucket. :rtype:
CBCollection
:return: ACollection
for a collection with the given name.
- collection(collection_name)[source]¶
Gets the named collection for this bucket.
- Parameters
collection_name (
str
) – string identifier for a given collection.- Return type
CBCollection
- Returns
A
Collection
for a collection with the given name.- Raise
CollectionNotFoundException
Collection object¶
- class couchbase.collection.Collection¶
- __init__(*options, name=None, parent_scope=None, **kwargs)¶
Couchbase collection.
- param parent_scope
parent scope
- param name
name of collection
- param options
miscellaneous options
- Warning
This is an internal API call.
Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.
Used internally by the SDK. This constructor is not intended for external use.
Passing Arguments¶
All keyword arguments passed to methods should be specified as keyword arguments, and the user should not rely on their position within the keyword specification - as this is subject to change.
Thus, if a function is prototyped as:
def foo(self, key, foo=None, bar=1, baz=False)
then arguments passed to foo()
should always be in the form of
obj.foo(key, foo=fooval, bar=barval, baz=bazval)
and never like
obj.foo(key, fooval, barval, bazval)
Option Blocks¶
- class couchbase.options.OptionBlock[source]¶
- __init__(*args, **kwargs)[source]¶
This is a wrapper for a set of options for a Couchbase command. It can be passed into the command in the ‘options’ parameter and overriden by parameters of the same name via the following **kwargs.
- Parameters
args (
Any
) –kwargs (
Any
) – parameters to pass in to the OptionBlock
- class couchbase.collection.AppendOptions[source]¶
- __init__(durability=None, cas=None, timeout=None)¶
Options for appending an item
- Parameters
cas – CAS value
timeout – Timeout for operation
durability – Durability settings
- class couchbase.collection.DecrementOptions[source]¶
- __init__(durability=None, cas=None, timeout=None, span=None, expiry=None, initial=<class 'couchbase.options.SignedInt64'> with value 0, delta=<class 'couchbase.collection.DeltaValue'> with value 1)¶
Settings for decrement operations
- Parameters
durability (
Optional
[DurabilityType
]) – Durability settingscas (
Optional
[int
]) – the CAS valuetimeout (
Optional
[timedelta
]) – Timeout for the operationspan (
Optional
[CouchbaseSpan
]) – Parent span for the operationexpiry (
Optional
[timedelta
]) – Expiration timeinitial (
SignedInt64
) – Initial valuedelta (
DeltaValue
) – Variation
- class couchbase.collection.ExistsOptions[source]¶
- __init__(timeout=None, span=None, **kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout (
Optional
[timedelta
]) – Timeout for an operation
- class couchbase.collection.GetAllReplicasOptions[source]¶
- __init__(**kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout – Timeout for an operation
- class couchbase.collection.GetAndLockOptions[source]¶
- __init__(**kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout – Timeout for an operation
- class couchbase.collection.GetAndTouchOptions[source]¶
- __init__(**kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout – Timeout for an operation
- class couchbase.collection.GetAnyReplicaOptions[source]¶
- __init__(**kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout – Timeout for an operation
- class couchbase.collection.IncrementOptions[source]¶
- __init__(durability=None, cas=None, timeout=None, span=None, expiry=None, initial=<class 'couchbase.options.SignedInt64'> with value 0, delta=<class 'couchbase.collection.DeltaValue'> with value 1)¶
Settings for increment operations
- Parameters
durability (
Optional
[DurabilityType
]) – Durability settingscas (
Optional
[int
]) – the CAS valuetimeout (
Optional
[timedelta
]) – Timeout for the operationspan (
Optional
[CouchbaseSpan
]) – Parent span for the operationexpiry (
Optional
[timedelta
]) – Expiration timeinitial (
SignedInt64
) – Initial valuedelta (
DeltaValue
) – Variation
- class couchbase.collection.LookupInOptions[source]¶
- __init__(timeout=None, span=None, **kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout (
Optional
[timedelta
]) – Timeout for an operation
- class couchbase.collection.PrependOptions[source]¶
- __init__(durability=None, cas=None, timeout=None)¶
Options for prepending an item
- Parameters
cas – CAS value
timeout – Timeout for operation
durability – Durability settings
- class couchbase.collection.TouchOptions[source]¶
- __init__(timeout=None, span=None, **kwargs)¶
An OptionBlock with a timeout
- Parameters
timeout (
Optional
[timedelta
]) – Timeout for an operation
Integer Types¶
- class couchbase.options.ConstrainedInt(value)[source]¶
Bases:
object
A signed integer between cls.min() and cls.max() inclusive
- Parameters
value (couchbase.options.AcceptableInts) – the value to initialise this with.
- Raise
InvalidArgumentException
if not in range
- class couchbase.options.SignedInt64(value)[source]¶
Bases:
couchbase.options.ConstrainedInt
A signed integer between -0x8000000000000000 and +0x7FFFFFFFFFFFFFFF inclusive.
- Parameters
value (couchbase.options.AcceptableInts) – the value to initialise this with.
- Raise
InvalidArgumentException
if not in range
- class couchbase.options.UnsignedInt32(value)[source]¶
Bases:
couchbase.options.ConstrainedInt
An unsigned integer between 0x00000000 and +0x80000000 inclusive.
- Parameters
value (couchbase.options.AcceptableInts) – the value to initialise this with.
- Raise
ArgumentError
if not in range
- class couchbase.options.UnsignedInt64(value)[source]¶
Bases:
couchbase.options.ConstrainedInt
An unsigned integer between 0x0000000000000000 and +0x8000000000000000 inclusive.
- Parameters
value (couchbase.options.AcceptableInts) – the value to initialise this with.
- Raise
ArgumentError
if not in range
Key and Value Format¶
By default, keys are encoded as UTF-8, while values are encoded as JSON; which was selected to be the default for compatibility and ease-of-use with views.
Format Options¶
The following constants may be used as values to the format option
in methods where this is supported. This is also the value returned in the
flags
attribute of the
ValueResult
object from a
get()
operation.
Each format specifier has specific rules about what data types it accepts.
- couchbase.FMT_JSON¶
Indicates the value is to be converted to JSON. This accepts any plain Python object and internally calls
json.dumps(value)()
. See the Python json documentation for more information. It is recommended you use this format if you intend to examine the value in a MapReduce view function
- couchbase.FMT_PICKLE¶
Convert the value to Pickle. This is the most flexible format as it accepts just about any Python object. This should not be used if operating in environments where other Couchbase clients in other languages might be operating (as Pickle is a Python-specific format)
- couchbase.FMT_BYTES¶
Pass the value as a byte string. No conversion is performed, but the value must already be of a bytes type. In Python 2.x bytes is a synonym for str. In Python 3.x, bytes and str are distinct types. Use this option to store “binary” data. An exception will be thrown if a unicode object is passed, as unicode objects do not have any specific encoding. You must first encode the object to your preferred encoding and pass it along as the value.
Note that values with FMT_BYTES are retrieved as byte objects.
FMT_BYTES is the quickest conversion method.
- couchbase.FMT_UTF8¶
Pass the value as a UTF-8 encoded string. This accepts unicode objects. It may also accept str objects if their content is encodable as UTF-8 (otherwise a
ValueFormatException
is thrown).Values with FMT_UTF8 are retrieved as unicode objects (for Python 3 unicode objects are plain str objects).
- couchbase.FMT_AUTO¶
Automatically determine the format of the input type. The value of this constant is an opaque object.
The rules are as follows:
If the value is a
str
,FMT_UTF8
is used. If it is abytes
object thenFMT_BYTES
is used. If it is alist
,tuple
ordict
,bool
, orNone
thenFMT_JSON
is used. For anything elseFMT_PICKLE
is used.
Key Format¶
The above format options are only valid for values being passed to one
of the storage methods (see couchbase.collection.Collection.upsert()
).
For keys, the acceptable inputs are those for FMT_UTF8
Single-Key Data Methods¶
These methods all return a Result
object containing
information about the operation (such as status and value).
Storing Data¶
- class couchbase.collection.Collection¶
These methods set the contents of a key in Couchbase. If successful, they replace the existing contents (if any) of the key.
- upsert(key, value, *options, **kwargs)¶
Unconditionally store the object in Couchbase.
- Parameters
key (
str
) – The key to set the value with. By default, the key must be either abytes
orstr
object encodable as UTF-8. If a custom transcoder class is used (see__init__()
), then the key object is passed directly to the transcoder, which may serialize it how it wishes.value (
Any
) –The value to set for the key. This should be a native Python value which will be transparently serialized to JSON by the library. Do not pass already-serialized JSON as the value or it will be serialized again.
If you are using a different format setting (see format parameter), and/or a custom transcoder then value for this argument may need to conform to different criteria.
options (
UpsertOptions
) – Options for the upsert operation.kwargs (
Any
) – Override corresponding value in options.
- Raise
InvalidArgumentException
if an argument is supplied that is not applicable in this context. For example setting the CAS as a string.- Raise
:exc`.CouchbaseNetworkException`
- Raise
DocumentExistsException
if the key already exists on the server with a different CAS value.- Raise
ValueFormatException
if the value cannot be serialized with chosen encoder, e.g. if you try to store a dictionary in plain mode.
Simple set:
cb.upsert('key', 'value')
Force JSON document format for value:
cb.upsert('foo', {'bar': 'baz'})
Insert JSON from a string:
JSONstr = '{"key1": "value1", "key2": 123}' JSONobj = json.loads(JSONstr) cb.upsert("documentID", JSONobj)
Force UTF8 document format for value:
cb.upsert('foo', "<xml></xml>", format=couchbase_core.FMT_UTF8)
Simple set with durability:
cb.upsert('key', 'value', durability_level=Durability.MAJORITY_AND_PERSIST_TO_ACTIVE)
- Return type
- insert(key, value, *options, **kwargs)¶
Store an object in Couchbase unless it already exists.
Follows the same conventions as
upsert()
but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists.Notably missing from this method is the cas parameter, this is because insert will only succeed if a key does not already exist on the server (and thus can have no CAS)
- Parameters
key (
str
) – Key of document to insertvalue (
Any
) – The document itself.options – Options for the insert request.
kwargs – Override corresponding value in the options.
- Raise
DocumentExistsException
if the key already exists
See also
- Return type
- replace(key, value, *options, **kwargs)¶
Store an object in Couchbase only if it already exists.
Follows the same conventions as
upsert()
, but the value is stored only if a previous value already exists.- Parameters
key (
str
) – Key of document to replacevalue (
Any
) – The document itself.options (
ReplaceOptions
) – Options for the replace request.kwargs (
Any
) – Override corresponding value in the options.
- Raise
DocumentNotFoundException
if the key does not exist
See also
- Return type
Retrieving Data¶
- class couchbase.collection.Collection¶
- get(key, *options, **kwargs)¶
Obtain an object stored in Couchbase by given key.
- Parameters
key (
str
) – The key to fetch. The type of key is the same as mentioned inupsert()
- Param
GetOptions options: The options to use for this get request.
- Param
Any kwargs: Override corresponding value in options.
- Raise
DocumentNotFoundException
if the key does not exist
Simple get:
value = cb.get('key').content_as[str]
Inspect CAS value:
rv = cb.get("key") value, cas = rv.content_as[str], rv.cas
- Request the expiry::
rv = cb.get(“key”, GetOptions(with_expiry=True)) value, expiry = rv.content_as[str], rv.expiry
- Return type
Modifying Data¶
These methods modify existing values in Couchbase
- class couchbase.collection.BinaryCollection[source]¶
- append(key, value, *options, **kwargs)[source]¶
Append a string to an existing value in Couchbase.
Other parameters follow the same conventions as
upsert()
.The format argument must be one of
FMT_UTF8
orFMT_BYTES
. If not specified, it will beFMT_UTF8
(overriding thedefault_format
attribute). This is because JSON or Pickle formats will be nonsensical when random data is appended to them. If you wish to modify a JSON or Pickle encoded object, you will need to retrieve it (viaget()
), modify it, and then store it again (usingupsert()
).Additionally, you must ensure the value (and flags) for the current value is compatible with the data to be appended. For an example, you may append a
FMT_BYTES
value to an existingFMT_JSON
value, but an error will be thrown when retrieving the value usingget()
(you may still use thedata_passthrough
to overcome this).- Parameters
key (str) – Key for the value to append
value (Union[str|bytes]) – The data to append to the existing value.
options (AppendOptions) – Options for the append operation.
- Raise
NotStoredException
if the key does not exist
- Return type
- prepend(key, value, *options, **kwargs)[source]¶
Prepend a string to an existing value in Couchbase.
- Parameters
key (
str
) – Key for the value to appendvalue (
str
) – The data to append to the existing value.options (
PrependOptions
) – Options for the prepend operation.
- Raise
NotStoredException
if the key does not exist
See also
- Return type
Entry Operations¶
These methods affect an entry in Couchbase. They do not directly modify the value, but may affect the entry’s accessibility or duration.
- class couchbase.collection.Collection¶
- remove(key, *options, **kwargs)¶
Remove the key-value entry for a given key in Couchbase.
- Parameters
key (
str
) – A string which is the key to remove. The format and type of the key follows the same conventions as inupsert()
options (
RemoveOptions
) – Options for removing key.kwargs – Override corresponding value in options
- Raise
DocumentNotFoundException
if the key does not exist.- Raise
DocumentExistsException
if a CAS was specified, but the CAS on the server had changed
Simple remove:
ok = cb.remove("key").success
Don’t complain if key does not exist:
ok = cb.remove("key", quiet=True)
Only remove if CAS matches our version:
rv = cb.get("key") cb.remove("key", RemoveOptions(cas=rv.cas))
- Return type
- get_and_lock(key, expiry, *options, **kwargs)¶
Get a document with the specified key, locking it from mutation.
- Parameters
key (
str
) – Key of document to lockexpiry (
timedelta
) – Time at which the lock expires. Note you can always unlock it, and the server unlocks it after 15 seconds.options (
GetAndLockOptions
) – Options for the get and lock operation.kwargs – Override corresponding value in options.
- Return type
- unlock(key, cas, *options, **kwargs)¶
Unlock a Locked Key in Couchbase.
This unlocks an item previously locked by
lock()
- Parameters
key (
str
) – The key to unlockcas (
int
) – The cas, which you got when you used get_and_lock.options (
UnlockOptions
) – Options for the unlock operation.kwargs (
Any
) – Override corresponding value in options.
See
get_and_lock()
for an example.- Raise
TemporaryFailException
if the CAS supplied does not match the CAS on the server (possibly because it was unlocked by previous call).
See also
- Return type
- get_and_touch(key, expiry, *options, **kwargs)¶
Get the document with the specified key, and update the expiry.
- Parameters
key (
str
) – Key of document to get and touch.expiry (
timedelta
) – New expiry for document. Set to timedelta(seconds=0) to never expire.options (
GetAndTouchOptions
) – Options for request.kwargs – Override corresponding value in options.
- Return type
- Returns
A
couchbase.result.GetResult
object representing the document for this key.
- touch(key, expiry, *options, **kwargs)¶
Update a key’s expiry time
- Parameters
key (
str
) – The key whose expiry time should be modifiedexpiry (
timedelta
) – The new expiry time. If the expiry time is timedelta(seconds=0), then the key never expires (and any existing expiry is removed)options (
TouchOptions
) – Options for touch command.kwargs – Override corresponding value in options.
- Raise
The same things that
get()
does
See also
get_and_touch()
- which can be used to get and update the expiry- Return type
Sub-Document Operations¶
These methods provide entry points to modify parts of a document in Couchbase.
Note
Sub-Document API methods are available in Couchbase Server 4.5 (currently in Developer Preview).
The server and SDK implementations and APIs are subject to change
- class couchbase.collection.Collection¶
- lookup_in(key, spec, *options, **kwargs)¶
Atomically retrieve one or more paths from a document.
- Parameters
key (
str
) – The key of the document to lookupspec (
Iterable
[Spec
]) – An iterable sequence of Specs (seecouchbase_core.subdocument
)options (
LookupInOptions
) – Options for the lookup_in operation.kwargs (
Any
) – Override corresponding value in options.
- Return type
- Returns
A
couchbase.LookupInResult
object. This object contains the results and any errors of the operation.
Example:
import couchbase_core.subdocument as SD rv = cb.lookup_in('user', SD.get('email'), SD.get('name'), SD.exists('friends.therock')) email = rv[0] name = rv[1] friend_exists = rv.exists(2)
- mutate_in(key, spec, *options, **kwargs)¶
Perform multiple atomic modifications within a document.
- Parameters
key (
str
) – The key of the document to modifyspec (
Iterable
[Spec
]) – An iterable of specs (Seecouchbase.mutate_in.MutateInSpecItemBase
)options (
MutateInOptions
) – Options for the mutate_in operation.kwargs (
Any
) – Override corresponding value in options.
Here’s an example of adding a new tag to a “user” document and incrementing a modification counter:
import couchbase_core.subdocument as SD # .... cb.mutate_in('user', SD.array_addunique('tags', 'dog'), SD.counter('updates', 1))
Note
The insert_doc and upsert_doc options are mutually exclusive. Use insert_doc when you wish to create a new document with extended attributes (xattrs).
See also
couchbase_core.subdocument
- Return type
Counter Operations¶
These are atomic counter operations for Couchbase. They increment
or decrement a counter. A counter is a key whose value can be parsed
as an integer. Counter values may be retrieved (without modification)
using the couchbase.collection.Collection.get()
method
- class couchbase.options.SignedInt64[source]¶
- __init__(value)[source]¶
A signed integer between -0x8000000000000000 and +0x7FFFFFFFFFFFFFFF inclusive.
- Parameters
value (couchbase.options.AcceptableInts) – the value to initialise this with.
- Raise
InvalidArgumentException
if not in range
- class couchbase.collection.DeltaValue[source]¶
- __init__(value)[source]¶
A non-negative integer between 0 and +0x7FFFFFFFFFFFFFFF inclusive. Used as an argument for
Collection.increment()
andCollection.decrement()
- Parameters
value (
Union
[ForwardRef
,c_long
,c_ulong
,int
]) – the value to initialise this with.- Raise
InvalidArgumentException
if not in range
- class couchbase.collection.BinaryCollection[source]¶
- increment(key, *options, **kwargs)[source]¶
Increment the numeric value of an item.
This method instructs the server to treat the item stored under the given key as a numeric counter.
Counter operations require that the stored value exists as a string representation of a number (e.g.
123
). If storing items using theupsert()
family of methods, and using the defaultcouchbase_core.FMT_JSON
then the value will conform to this constraint.- Parameters
key (
str
) – A key whose counter value is to be modifieddelta – an amount by which the key should be incremented.
options (
IncrementOptions
) – Options for the increment operation.kwargs – Overrides corresponding value in the options
- Raise
DocumentNotFoundException
if the key does not exist on the bucket (and initial was None)- Raise
DeltaBadvalException
if the key exists, but the existing value is not numeric- Return type
- Returns
A
couchbase.result.MutationResult
object.
Simple increment:
rv = cb.increment("key") cb.get("key").content_as[int] # 42
Increment by 10:
rv = cb.increment("key", DeltaValue(10))
Increment by 20, set initial value to 5 if it does not exist:
rv = cb.increment("key", DeltaValue(20), initial=SignedInt64(5))
- decrement(key, *options, **kwargs)[source]¶
Decrement the numeric value of an item.
This method instructs the server to treat the item stored under the given key as a numeric counter.
Counter operations require that the stored value exists as a string representation of a number (e.g.
123
). If storing items using theupsert()
family of methods, and using the defaultcouchbase_core.FMT_JSON
then the value will conform to this constraint.- Parameters
key (
str
) – A key whose counter value is to be modifieddelta – an amount by which the key should be decremented.
options (
IncrementOptions
) – Options for the decrement operation.kwargs – Overrides corresponding value in the options
- Raise
DocumentNotFoundException
if the key does not exist on the bucket (and initial was None)- Raise
DeltaBadvalException
if the key exists, but the existing value is not numeric- Return type
- Returns
A
couchbase.result.MutationResult
object.
Simple decrement:
rv = cb.decrement("key") cb.get("key").content_as[int] # 42
Decrement by 10:
rv = cb.decrement("key", DeltaValue(10))
Decrement by 20, set initial value to 5 if it does not exist:
rv = cb.decrement("key", DeltaValue(20), initial=SignedInt64(5))
Multi-Key Data Methods¶
These methods tend to be more efficient than their single-key
equivalents. They return a couchbase.result.MultiResultBase
object (which is
a dict subclass) which contains class:couchbase.result.Result objects as the
values for its keys
- class couchbase.collection.Collection¶
- upsert_multi(keys, *options, **kwargs)¶
Write multiple items to the cluster. Multi version of
upsert()
- param keys
A dictionary of keys to set. The keys are the keys as they should be on the server, and the values are the values for the keys to be stored.
keys may also be a
ItemCollection
. If using a dictionary variant for item collections, an additional ignore_cas parameter may be supplied with a boolean value. If not specified, the operation will fail if the CAS value on the server does not match the one specified in the Item’s cas field.- param ttl
If specified, sets the expiry value for all keys
- param format
If specified, this is the conversion format which will be used for _all_ the keys.
- param persist_to
Durability constraint for persistence. Note that it is more efficient to use
endure_multi()
on the returnedMultiResult
than using these parameters for a high volume of keys. Using these parameters however does save on latency as the constraint checking for each item is performed as soon as it is successfully stored.- param replicate_to
Durability constraints for replication. See notes on the persist_to parameter for usage.
- param durability_level
Sync replication durability level. You should either use this or the old-style durability params above, but not both.
- returns
a dictionary of
MutationResult
objects by key
The multi methods are more than just a convenience, they also save on network performance by batch-scheduling operations, reducing latencies. This is especially noticeable on smaller value sizes.
See also
- Warning
This is a volatile API call that is still in flux and may likely be changed.
It may also be an inherently private API call that may be exposed, but “YMMV” (your mileage may vary) principles apply.
- Return type
Dict
[str
,MutationResult
]
- get_multi(keys, *options, **kwargs)¶
Get multiple keys from the collection
- param keys
list of keys to get
- type keys
list of keys to get
- return
a dictionary of
GetResult
objects by key
- Warning
This is a volatile API call that is still in flux and may likely be changed.
It may also be an inherently private API call that may be exposed, but “YMMV” (your mileage may vary) principles apply.
- Return type
Dict
[str
,GetResult
]
- insert_multi(keys, *options, **kwargs)¶
Insert multiple items into the collection.
- param keys
dictionary of items to insert, by key
- return
a dictionary of
MutationResult
objects by key
See also
upsert_multi()
- for other optional arguments- Warning
This is a volatile API call that is still in flux and may likely be changed.
It may also be an inherently private API call that may be exposed, but “YMMV” (your mileage may vary) principles apply.
- Return type
Dict
[str
,MutationResult
]
- replace_multi()¶
- lock_multi()¶
- unlock_multi()¶
Multi-key variant of unlock
- touch_multi()¶
- remove_multi(keys, *options, **kwargs)¶
Remove multiple items from the collection.
- param keys
list of items to remove, by key
- return
a dictionary of
MutationResult
objects by key
See also
upsert_multi()
- for other optional arguments- Warning
This is a volatile API call that is still in flux and may likely be changed.
It may also be an inherently private API call that may be exposed, but “YMMV” (your mileage may vary) principles apply.
- Return type
Dict
[str
,MutationResult
]
- class couchbase.collection.BinaryCollection[source]¶
Batch Operation Pipeline¶
Warning
The APIs below are from SDK2 and currently only available from the couchbase_v2 legacy support package. We plan to update these to support SDK3 shortly.
In addition to the multi methods, you may also use the Pipeline context manager to schedule multiple operations of different types
- class couchbase_v2.bucket.Bucket¶
- class couchbase_v2.bucket.Pipeline¶
MapReduce/View Methods¶
- class couchbase.bucket.Bucket[source]¶
- view_query(design_doc, view_name, *view_options, **kwargs)[source]¶
Run a View Query
- Parameters
design_doc (str) – design document
view_name (str) – view name
view_options (ViewOptions) – Options to use when querying a view index.
kwargs – Override corresponding option in options.
- Return type
- Returns
A
ViewResult
containing the view results
N1QL Query Methods¶
- class couchbase.cluster.Cluster[source]¶
- query(statement, *options, **kwargs)[source]¶
Perform a N1QL query.
- Parameters
statement (
str
) – the N1QL query statement to executeoptions (
Union
[QueryOptions
,Any
]) – A QueryOptions object or the positional parameters in the query.kwargs (
Any
) – Override the corresponding value in the Options. If they don’t match any value in the options, assumed to be named parameters for the query.
- Return type
- Returns
The results of the query or error message if the query failed on the server.
- Raise
QueryException
- for errors involving the query itself. Also any exceptions raised by underlying system -TimeoutException
for instance.
Full-Text Search Methods¶
- class couchbase.cluster.Cluster[source]¶
- search_query(index, query, *options, **kwargs)[source]¶
Executes a Search or FTS query against the remote cluster and returns a SearchResult implementation with the results of the query.
from couchbase.search import MatchQuery, SearchOptions it = cb.search('name', MatchQuery('nosql'), SearchOptions(limit=10)) for hit in it: print(hit)
- Parameters
index (str) – Name of the index to use for this query.
query (
SearchQuery
) – the fluent search API to construct a query for FTS.options (
SearchOptions
) – the options to pass to the cluster with the query.kwargs – Overrides corresponding value in options.
- Return type
SearchResult
- Returns
A
SearchResult
object with the results of the query or error message if the query failed on the server.- Raise
SearchException
Errors related to the query itself. Also, any exceptions raised by the underlying platform -TimeoutException
for example.
Analytics Query Methods¶
- class couchbase.cluster.Cluster[source]¶
- analytics_query(statement, *options, **kwargs)[source]¶
Executes an Analytics query against the remote cluster and returns a AnalyticsResult with the results of the query.
- Parameters
statement (
str
) – the analytics statement to executeoptions (
AnalyticsOptions
) – the optional parameters that the Analytics service takes based on the Analytics RFC.
- Return type
- Returns
An AnalyticsResult object with the results of the query or error message if the query failed on the server.
- Raise
AnalyticsException
errors associated with the analytics query itself. Also, any exceptions raised by the underlying platform -TimeoutException
for example.
Design Document Management¶
To perform design document management operations, you must first get
an instance of the ViewIndexManager
. You can do this by invoking
the views()
method on the
Bucket
object.
Note
Design document management functions are async. This means that any
successful return value simply means that the operation was scheduled
successfuly on the server. It is possible that the view or design will
still not yet exist after creating, deleting, or publishing a design
document. Therefore it may be recommended to verify that the view exists
by “polling” until the view does not fail. This may be accomplished by
specifying the syncwait
parameter to the various design methods which
accept them.
Note
The normal process for dealing with views and design docs is to first
create a development design document. Such design documents are
prefixed with the string dev_
. They operate on a small subset of
cluster data and as such are ideal for testing as they do not impact
load very much.
Once you are satisfied with the behavior of the development design doc, you can publish it into a production mode design doc. Such design documents always operate on the full cluster dataset.
The view and design functions accept a use_devmode
parameter which
prefixes the design name with dev_
if not already prefixed.
N1QL Index Management¶
Before issuing any N1QL query using query()
, the bucket being
queried must have an index defined for the query. The simplest index is the
primary index.
To create a primary index, use:
mgr.create_primary_index('bucket_name', CreatePrimaryQueryIndexOptions(ignore_if_exists=True))
You can create additional indexes using:
mgr.create_index('bucket_name', 'idx_foo', fields=['foo'])
- class couchbase.management.queries.QueryIndexManager[source]¶
- get_all_indexes(bucket_name, *options, **kwargs)[source]¶
Fetches all indexes from the server.
- Parameters
bucket_name (str) – the name of the bucket.
options (GetAllQueryIndexOptions) – Options to use for getting all indexes.
kwargs (Any) – Override corresponding value in options.
- Return type
List
[QueryIndex
]- Returns
A list of QueryIndex objects.
- Raises
InvalidArgumentsException
- create_primary_index(bucket_name, *options, **kwargs)[source]¶
Creates a new primary index.
- Parameters
bucket_name (str) – name of the bucket.
index_name (str) – name of the index.
options (CreatePrimaryQueryIndexOptions) – Options to use when creating primary index
kwargs (Any) – Override corresponding values in options.
- Raises
QueryIndexAlreadyExistsException
- Raises
InvalidArgumentsException
- create_index(bucket_name, index_name, fields, *options, **kwargs)[source]¶
Creates a new index.
- Parameters
bucket_name (str) – name of the bucket.
index_name (str) – the name of the index.
fields (Iterable[str]) – Fields over which to create the index.
options (CreateQueryIndexOptions) – Options to use when creating index.
kwargs (Any) – Override corresponding value in options.
- Raises
QueryIndexAlreadyExistsException
- Raises
InvalidArgumentsException
- Return type
None
- drop_primary_index(bucket_name, *options, **kwargs)[source]¶
Drops a primary index.
- Parameters
bucket_name – name of the bucket.
index_name – name of the index.
ignore_if_not_exists – Don’t error/throw if the index does not exist.
timeout – the time allowed for the operation to be terminated. This is controlled by the client.
- Raises
QueryIndexNotFoundException
- Raises
InvalidArgumentsException
- drop_index(bucket_name, index_name, *options, **kwargs)[source]¶
Drops an index.
- Parameters
bucket_name (str) – name of the bucket.
index_name (str) – name of the index.
options (DropQueryIndexOptions) – Options for dropping index.
kwargs (Any) – Override corresponding value in options.
- Raises
QueryIndexNotFoundException
- Raises
InvalidArgumentsException
- watch_indexes(bucket_name, index_names, *options, **kwargs)[source]¶
Watch polls indexes until they are online.
- Parameters
bucket_name (str) – name of the bucket.
index_names (Iterable[str]) – name(s) of the index(es).
options (WatchQueryIndexOptions) – Options for request to watch indexes.
kwargs (Any) – Override corresponding valud in options.
- Raises
QueryIndexNotFoundException
- Raises
WatchQueryIndexTimeoutException
- build_deferred_indexes(bucket_name, *options, **kwargs)[source]¶
Build Deferred builds all indexes which are currently in deferred state.
- Parameters
bucket_name (str) – name of the bucket.
options (BuildDeferredQueryIndexOptions) – Options for building deferred indexes.
kwargs (Any) – Override corresponding value in options.
- Raise
InvalidArgumentsException
- class couchbase.bucket..Bucket¶
Flushing (clearing) the Bucket¶
For some stages of development and/or deployment, it might be useful to be able to clear the bucket of its contents.
- class couchbase.management.buckets.BucketManager[source]¶
- flush_bucket(bucket_name, *options, **kwargs)[source]¶
Flushes a bucket (uses the ns_server REST interface).
- Parameters
bucket_name (str) – the name of the bucket.
options (FlushBucketOptions) – options for flushing the bucket.
kwargs (Any) – override corresponding value in options.
- Raises
BucketNotFoundException
- Raises
InvalidArgumentsException
- Raises
FlushDisabledException
Informational Methods¶
Warning
The APIs below are from SDK2 and currently only available from the couchbase_v2 legacy support package. We plan to update these to support SDK3 shortly.
These methods do not operate on keys directly, but offer various information about things
Item API Methods¶
Warning
The APIs below are from SDK2 and currently only available from the couchbase_v2 legacy support package. We plan to update these to support SDK3 shortly.
These methods are specifically for the Item
API. Most of the multi methods will accept Item objects as well,
however there are some special methods for this interface
- class couchbase_v2.bucket.Bucket¶
Durability Constraints¶
Durability constraints ensure safer protection against data loss.
- class couchbase.durability.DurabilityOptionBlock[source]¶
- __init__(timeout=None, durability=None, expiry=None, **kwargs)[source]¶
Options for operations with any type of durability
- Parameters
durability (
Optional
[DurabilityType
]) – Durability settingsexpiry (
Optional
[timedelta
]) – When any mutation should expiretimeout (
Optional
[timedelta
]) – Timeout for operation
- class couchbase.durability.ClientDurability[source]¶
- class couchbase.durability.ClientDurableOptionBlock[source]¶
- __init__(timeout=None, durability=None)[source]¶
Options for operations with client-type durability
- Parameters
durability (
Optional
[ClientDurability
]) – Client durability settingstimeout (
Optional
[timedelta
]) – Timeout for operation
- class couchbase.durability.ServerDurableOptionBlock[source]¶
- __init__(timeout=None, durability=None)[source]¶
Options for operations with server-type durability
- Parameters
durability (
Optional
[ServerDurability
]) – Server durability settingstimeout (
Optional
[timedelta
]) – Timeout for operation
Attributes¶
- class couchbase.bucket.Bucket[source]¶
- kv_timeout¶
The default timeout for all kv operations on this bucket.
# Set the default kv timeout to 10 seconds: bucket.kv_timeout = timedelta(seconds=10) # Get the current default: timeout = bucket.kv_timeout
- Return type
timedelta
- views_timeout¶
The default timeout for all view operations on this bucket.
# Set the default view timeout to 10 seconds: cb.view_timeout = timedelta(seconds=10) # Get the default view timeout: timeout = cb.view_timeout
- Return type
timedelta
- quiet¶
Whether to suppress errors when keys are not found (in
get()
anddelete()
operations).An error is still returned within the
Result
object
- transcoder¶
The
Transcoder
object being used.This is normally
None
unless a customcouchbase_core.transcoder.Transcoder
is being used
- data_passthrough¶
When this flag is set, values are always returned as raw bytes
- unlock_gil¶
Whether GIL manipulation is enabeld for this connection object.
This attribute can only be set from the constructor.
- name¶
Get the name of this bucket.
- Returns
Name of this bucket.
- Return type
str
- default_format¶
Specify the default format (default:
FMT_JSON
) to encode your data before storing in Couchbase. It uses the flags field to store the format.See format_info for the possible values
On a
get()
the original value will be returned. This means the JSON will be decoded, respectively the object will be unpickled.See also
format_info and
data_passthrough
- quiet¶
It controlls whether to raise an exception when the client executes operations on non-existent keys (default: False). If it is False it will raise
couchbase.exceptions.NotFoundException
exceptions. When set to True the operations will not raise an exception, but still set an error inside theResult
object.
- lockmode¶
- class couchbase.cluster.Cluster[source]¶
- query_timeout¶
The timeout for N1QL query operations, as a timedelta. This affects the
query()
method. This can be set inconnect()
by passing in aClusterOptions
with the query_timeout set to the desired time.Timeouts may also be adjusted on a per-query basis by setting the
timeout
property in the options to the n1ql_query method. The effective timeout is either the per-query timeout or the global timeout, whichever is lower.- Return type
timedelta
- server_nodes¶
Get a list of the current nodes in the cluster
- is_ssl¶
Read-only boolean property indicating whether SSL is used for this connection.
If this property is true, then all communication between this object and the Couchbase cluster is encrypted using SSL.
See
__init__()
for more information on connection options.- Return type
bool
- compression¶
Returns the compression mode to be used when talking to the server. See
Compression
for details. This can be set in theconnect()
by passing in aClusterOptions
with the desired compression set in it.- Return type
Compression
- compression_min_size¶
Minimum size (in bytes) of the document payload to be compressed when compression enabled. This can be set in the
connect()
by passing in aClusterOptions
with the desired compression set in it.- Return type
int
- compression_min_ratio¶
Minimum compression ratio (compressed / original) of the compressed payload to allow sending it to cluster. This can be set in the
connect()
by passing in aClusterOptions
with the desired ratio set in it.- Return type
float
Private APIs¶
- class couchbase_core.client.Client[source]¶
The following APIs are not supported because using them is inherently dangerous. They are provided as workarounds for specific problems which may be encountered by users, and for potential testing of certain states and/or modifications which are not attainable with the public API.
- _close()¶
Close the instance’s underlying socket resources
Note that operations pending on the connection may fail.
- _cntl(*args, **kwargs)[source]¶
Low-level interface to the underlying C library’s settings. via
lcb_cntl()
.This method accepts an opcode and an optional value. Constants are intentionally not defined for the various opcodes to allow saner error handling when an unknown opcode is not used.
Warning
If you pass the wrong parameters to this API call, your application may crash. For this reason, this is not a public API call. Nevertheless it may be used sparingly as a workaround for settings which may have not yet been exposed directly via a supported API
- Parameters
op (int) – Type of cntl to access. These are defined in libcouchbase’s
cntl.h
header filevalue – An optional value to supply for the operation. If a value is not passed then the operation will return the current value of the cntl without doing anything else. otherwise, it will interpret the cntl in a manner that makes sense. If the value is a float, it will be treated as a timeout value and will be multiplied by 1000000 to yield the microsecond equivalent for the library. If the value is a boolean, it is treated as a C
int
value_type –
String indicating the type of C-level value to be passed to
lcb_cntl()
. The possible values are:"string"
- NUL-terminated const char.Pass a Python string
"int"
- Cint
type. Pass a Python int"uint32_t"
- Clcb_uint32_t
type.Pass a Python int
"unsigned"
- Cunsigned int
type.Pass a Python int
"float"
- Cfloat
type. Pass a Python float"timeout"
- The number of seconds as a float. This isconverted into microseconds within the extension library.
- Returns
If no value argument is provided, retrieves the current setting (per the
value_type
specification). Otherwise this function returnsNone
.
- _cntlstr(key, value)[source]¶
Low-level interface to the underlying C library’s settings. via
lcb_cntl_string()
.This method accepts a key and a value. It can modify the same sort of settings as the
_cntl()
method, but may be a bit more convenient to follow in code.Warning
See
_cntl()
for warnings.- Parameters
key (string) – The setting key
value (string) – The setting value
See the API documentation for libcouchbase for a list of acceptable setting keys.
- _vbmap()¶
Returns a tuple of (vbucket, server index) for a key
Additional Connection Options¶
This section is intended to document some of the less common connection
options and formats of the connection string
(see couchbase.cluster.Cluster.__init__()
).
Using Custom Ports¶
If you require to connect to an alternate port for bootstrapping the client
(either because your administrator has configured the cluster to listen on
alternate ports, or because you are using the built-in cluster_run
script provided with the server source code), you may do so in the host list
itself.
Simply provide the host in the format of host:port
.
Note that the port is dependent on the scheme used. In this case, the scheme dictates what specific service the port points to.
Scheme |
Protocol |
---|---|
|
memcached port (default is |
|
SSL-encrypted memcached port (default is |
|
REST API/Administrative port (default is |
Options in Connection String¶
Additional client options may be specified within the connection string itself. These options are derived from the underlying libcouchbase library and thus will accept any input accepted by the library itself. The following are some influential options:
config_total_timeout
. Number of seconds to wait for the client bootstrap to complete.config_node_timeout
. Maximum number of time to wait (in seconds) to attempt to bootstrap from the current node. If the bootstrap times out (and theconfig_total_timeout
setting is not reached), the bootstrap is then attempted from the next node (or an exception is raised if no more nodes remain).config_cache
. If set, this will refer to a file on the filesystem where cached “bootstrap” information may be stored. This path may be shared among multiple instance of the Couchbase client. Using this option may reduce overhead when using many short-lived instances of the client.If the file does not exist, it will be created.