Client Class — Client
¶
Client
¶
The client connects through a seed node (the address of a single node) to an Aerospike database cluster. From the seed node, the client learns of the other nodes and establishes connections to them. It also gets the partition map of the cluster, which is how it knows where every record actually lives.
The client handles the connections, including re-establishing them ahead of executing an operation. It keeps track of changes to the cluster through a cluster-tending thread.
See also
-
class
aerospike.
Client
¶ Example:
from __future__ import print_function # import the module import aerospike from aerospike import exception as ex import sys # Configure the client config = { 'hosts': [ ('127.0.0.1', 3000) ] } # Optionally set policies for various method types write_policies = {'total_timeout': 2000, 'max_retries': 0} read_policies = {'total_timeout': 1500, 'max_retries': 1} policies = {'write': write_policies, 'read': read_policies} config['policies'] = policies # Create a client and connect it to the cluster try: client = aerospike.client(config).connect() except ex.ClientError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) # Records are addressable via a tuple of (namespace, set, primary key) key = ('test', 'demo', 'foo') try: # Write a record client.put(key, { 'name': 'John Doe', 'age': 32 }) except ex.RecordError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) # Read a record (key, meta, record) = client.get(key) # Close the connection to the Aerospike cluster client.close()
-
connect
([username, password])¶ Connect to the cluster. The optional username and password only apply when connecting to the Enterprise Edition of Aerospike.
Parameters: - username (str) – a defined user with roles in the cluster. See
admin_create_user()
. - password (str) – the password will be hashed by the client using bcrypt.
Raises: ClientError
, for example when a connection cannot be established to a seed node (any single node in the cluster from which the client learns of the other nodes).See also
- username (str) – a defined user with roles in the cluster. See
-
is_connected
()¶ Tests the connections between the client and the nodes of the cluster. If the result is
False
, the client will require another call toconnect()
.Return type: bool
Changed in version 2.0.0.
-
close
()¶ Close all connections to the cluster. It is recommended to explicitly call this method when the program is done communicating with the cluster.
-
get
(key[, policy]) -> (key, meta, bins)¶ Read a record with a given key, and return the record as a
tuple()
consisting of key, meta and bins.Parameters: - key (tuple) – a Key Tuple associated with the record.
- policy (dict) – optional Read Policies.
Returns: a Record Tuple. See Unicode Handling.
Raises: from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = {'hosts': [('127.0.0.1', 3000)]} client = aerospike.client(config).connect() try: # assuming a record with such a key exists in the cluster key = ('test', 'demo', 1) (key, meta, bins) = client.get(key) print(key) print('--------------------------') print(meta) print('--------------------------') print(bins) except ex.RecordNotFound: print("Record not found:", key) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Warning
The client has been changed to raise a
RecordNotFound
exception whenget()
does not find the record. Code that used to check formeta != None
should be modified.Changed in version 2.0.0.
-
select
(key, bins[, policy]) -> (key, meta, bins)¶ Read a record with a given key, and return the record as a
tuple()
consisting of key, meta and bins, with the specified bins projected. Prior to Aerospike server 3.6.0, if a selected bin does not exist its value will beNone
. Starting with 3.6.0, if a bin does not exist it will not be present in the returned Record Tuple.Parameters: - key (tuple) – a Key Tuple associated with the record.
- bins (list) – a list of bin names to select from the record.
- policy (dict) – optional Read Policies.
Returns: a Record Tuple. See Unicode Handling.
Raises: from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: # assuming a record with such a key exists in the cluster key = ('test', 'demo', 1) (key, meta, bins) = client.select(key, ['name']) print("name: ", bins.get('name')) except ex.RecordNotFound: print("Record not found:", key) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Warning
The client has been changed to raise a
RecordNotFound
exception whenselect()
does not find the record. Code that used to check formeta != None
should be modified.Changed in version 2.0.0.
-
exists
(key[, policy]) -> (key, meta)¶ Check if a record with a given key exists in the cluster and return the record as a
tuple()
consisting of key and meta. If the record does not exist the meta data will beNone
.Parameters: - key (tuple) – a Key Tuple associated with the record.
- policy (dict) – optional Read Policies.
Return type: tuple()
(key, meta)Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: # assuming a record with such a key exists in the cluster key = ('test', 'demo', 1) (key, meta) = client.exists(key) print(key) print('--------------------------') print(meta) except ex.RecordNotFound: print("Record not found:", key) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Changed in version 2.0.3.
-
put
(key, bins[, meta[, policy[, serializer]]])¶ Write a record with a given key to the cluster.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bins (dict) – a
dict
of bin-name / bin-value pairs. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Write Policies.
- serializer – optionally override the serialization mode of the
client with one of the Serialization Constants. To
use a class-level user-defined serialization function registered with
aerospike.set_serializer()
useaerospike.SERIALIZER_USER
.
Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex config = { 'hosts': [ ('127.0.0.1', 3000) ], 'total_timeout': 1500 } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) bins = { 'l': [ "qwertyuiop", 1, bytearray("asd;as[d'as;d", "utf-8") ], 'm': { "key": "asd';q;'1';" }, 'i': 1234, 'f': 3.14159265359, 's': '!@#@#$QSDAsd;as' } client.put(key, bins, policy={'key': aerospike.POLICY_KEY_SEND}, meta={'ttl':180}) # adding a bin client.put(key, {'smiley': u"\ud83d\ude04"}) # removing a bin client.put(key, {'i': aerospike.null()}) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Note
Using Generation Policy
The generation policy allows a record to be written only when the generation is a specific value. In the following example, we only want to write the record if no change has occurred since
exists()
was called.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [ ('127.0.0.1',3000)]} client = aerospike.client(config).connect() try: (key, meta) = client.exists(('test','test','key1')) print(meta) print('============') client.put(('test','test','key1'), {'id':1,'a':2}, meta={'gen': 33}, policy={'gen':aerospike.POLICY_GEN_EQ}) print('Record written.') except ex.RecordGenerationError: print("put() failed due to generation policy mismatch") except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) client.close()
-
touch
(key[, val=0[, meta[, policy]]])¶ Touch the given record, setting its time-to-live and incrementing its generation.
Parameters: Raises: a subclass of
AerospikeError
.See also
import aerospike config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() key = ('test', 'demo', 1) client.touch(key, 120, policy={'total_timeout': 100}) client.close()
-
remove
(key[, policy])¶ Remove a record matching the key from the cluster.
Parameters: - key (tuple) – a Key Tuple associated with the record.
- policy (dict) – optional Remove Policies.
Raises: a subclass of
AerospikeError
.import aerospike config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() key = ('test', 'demo', 1) client.remove(key, {'retry': aerospike.POLICY_RETRY_ONCE client.close()
-
get_key_digest
(ns, set, key) → bytearray¶ Calculate the digest of a particular key. See: Key Tuple.
Parameters: Returns: a RIPEMD-160 digest of the input tuple.
Return type: import aerospike import pprint pp = pprint.PrettyPrinter(indent=2) config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() digest = client.get_key_digest("test", "demo", 1 ) pp.pprint(digest) key = ('test', 'demo', None, digest) (key, meta, bins) = client.get(key) pp.pprint(bins) client.close()
Deprecated since version 2.0.1: use the function
aerospike.calc_digest()
instead.
Bin Operations
-
remove_bin
(key, list[, meta[, policy]])¶ Remove a list of bins from a record with a given key. Equivalent to setting those bins to
aerospike.null()
with aput()
.Parameters: - key (tuple) – a Key Tuple associated with the record.
- list (list) – the bins names to be removed from the record.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Write Policies.
Raises: a subclass of
AerospikeError
.import aerospike config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() key = ('test', 'demo', 1) meta = { 'ttl': 3600 } client.remove_bin(key, ['name', 'age'], meta, {'retry': aerospike.POLICY_RETRY_ONCE}) client.close()
-
append
(key, bin, val[, meta[, policy]])¶ Append the string val to the string value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val (str) – the string to append to the value of bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) client.append(key, 'name', ' jr.', policy={'total_timeout': 1200}) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
-
prepend
(key, bin, val[, meta[, policy]])¶ Prepend the string value in bin with the string val.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val (str) – the string to prepend to the value of bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) client.prepend(key, 'name', 'Dr. ', policy={'total_timeout': 1200}) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
-
increment
(key, bin, offset[, meta[, policy]])¶ Increment the integer value in bin by the integer val.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- offset (
int
orfloat
) – the value by which to increment the value in bin. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: client.put(('test', 'cats', 'mr. peppy'), {'breed':'persian'}, policy={'exists': aerospike.POLICY_EXISTS_CREATE_OR_REPLACE}) (key, meta, bins) = client.get(('test', 'cats', 'mr. peppy')) print("Before:", bins, "\n") client.increment(key, 'lives', -1) (key, meta, bins) = client.get(key) print("After:", bins, "\n") client.increment(key, 'lives', -1) (key, meta, bins) = client.get(key) print("Poor Kitty:", bins, "\n") print(bins) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
-
list_append
(key, bin, val[, meta[, policy]])¶ Append a single element to a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val –
int
,str
,float
,bytearray
,list
,dict
. An unsupported type will be serialized. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_extend
(key, bin, items[, meta[, policy]])¶ Extend the list value in bin with the given items.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- items (list) – the items to append the list in bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_insert
(key, bin, index, val[, meta[, policy]])¶ Insert an element at the specified index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the position in the index where the value should be inserted.
- val –
int
,str
,float
,bytearray
,list
,dict
. An unsupported type will be serialized. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_insert_items
(key, bin, index, items[, meta[, policy]])¶ Insert the items at the specified index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the position in the index where the items should be inserted.
- items (list) – the items to insert into the list in bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_pop
(key, bin, index[, meta[, policy]]) → val¶ Remove and get back a list element at a given index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the index position in the list element which should be removed and returned.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Returns: a single list element.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_pop_range
(key, bin, index, count[, meta[, policy]]) → val¶ Remove and get back list elements at a given index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the index of first element in a range which should be removed and returned.
- count (int) – the number of elements in the range.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Returns: a
list
of elements.Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_remove
(key, bin, index[, meta[, policy]])¶ Remove a list element at a given index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the index position in the list element which should be removed.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_remove_range
(key, bin, index, count[, meta[, policy]])¶ Remove list elements at a given index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the index of first element in a range which should be removed.
- count (int) – the number of elements in the range.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_clear
(key, bin[, meta[, policy]])¶ Remove all the elements from a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_set
(key, bin, index, val[, meta[, policy]])¶ Set list element val at the specified index of a list value in bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the position in the index where the value should be set.
- val –
int
,str
,float
,bytearray
,list
,dict
. An unsupported type will be serialized. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_get
(key, bin, index[, meta[, policy]]) → val¶ Get the list element at the specified index of a list value in bin.
Parameters: Raises: a subclass of
AerospikeError
.Returns: the list elements at the given index.
Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_get_range
(key, bin, index, count[, meta[, policy]]) → val¶ Get the list of count elements starting at a specified index of a list value in bin.
Parameters: Raises: a subclass of
AerospikeError
.Returns: a
list
of elements.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_trim
(key, bin, index, count[, meta[, policy]]) → val¶ Remove elements from the list which are not within the range starting at the given index plus count.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index (int) – the position in the index marking the start of the range.
- index – the index position of the first element in a range which should not be removed.
- count (int) – the number of elements in the range.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: a
list
of elements.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
list_size
(key, bin[, meta[, policy]]) → count¶ Count the number of elements in the list value in bin.
Parameters: Raises: a subclass of
AerospikeError
.Returns: a
int
.Note
Requires server version >= 3.7.0
New in version 1.0.59.
-
map_set_policy
(key, bin, map_policy)¶ Set the map policy for the given bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_policy (dict) – Map Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_put
(key, bin, map_key, val[, map_policy[, meta[, policy]]])¶ Add the given map_key/value pair to the map record specified by key and bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - val –
int
,str
,float
,bytearray
,list
,dict
. An unsupported type will be serialized. - map_policy (dict) – optional Map Policies.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_put_items
(key, bin, items[, map_policy[, meta[, policy]]])¶ Add the given items dict of key/value pairs to the map record specified by key and bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- items (dict) – key/value pairs.
- map_policy (dict) – optional Map Policies.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_increment
(key, bin, map_key, incr[, map_policy[, meta[, policy]]])¶ Increment the value of the map entry by given incr. Map entry is specified by key, bin and map_key.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - incr –
int
orfloat
- map_policy (dict) – optional Map Policies.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_decrement
(key, bin, map_key, decr[, map_policy[, meta[, policy]]])¶ Decrement the value of the map entry by given decr. Map entry is specified by key, bin and map_key.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - decr –
int
orfloat
- map_policy (dict) – optional Map Policies.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_size
(key, bin[, meta[, policy]]) → count¶ Return the size of the map specified by key and bin.
Parameters: Raises: a subclass of
AerospikeError
.Returns: a
int
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_clear
(key, bin[, meta[, policy]])¶ Remove all entries from the map specified by key and bin.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_key
(key, bin, map_key, return_type[, meta[, policy]])¶ Remove and optionally return first map entry from the map specified by key and bin which matches given map_key.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_key_list
(key, bin, list, return_type[, meta[, policy]][, meta[, policy]])¶ Remove and optionally return map entries from the map specified by key and bin which have keys that match the given list of keys.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- list –
list
the list of keys to match - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_key_range
(key, bin, map_key, range, return_type[, meta[, policy]])¶ Remove and optionally return map entries from the map specified by key and bin identified by the key range (map_key inclusive, range exclusive).
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - range –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_value
(key, bin, val, return_type[, meta[, policy]])¶ Remove and optionally return map entries from the map specified by key and bin which have a value matching val parameter.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_value_list
(key, bin, list, return_type[, meta[, policy]])¶ Remove and optionally return map entries from the map specified by key and bin which have a value matching the list of values.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- list –
list
the list of values to match - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_value_range
(key, bin, val, range, return_type[, meta[, policy]])¶ Remove and optionally return map entries from the map specified by key and bin identified by the value range (val inclusive, range exclusive).
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - range –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_index
(key, bin, index, return_type[, meta[, policy]])¶ Remove and optionally return the map entry from the map specified by key and bin at the given index location.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index –
int
the index location of the map entry - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_index_range
(key, bin, index, range, return_type[, meta[, policy]])¶ Remove and optionally return the map entries from the map specified by key and bin starting at the given index location and removing range number of items.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index –
int
the index location of the first map entry to remove - range –
int
the number of items to remove from the map - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_rank
(key, bin, rank, return_type[, meta[, policy]])¶ Remove and optionally return the map entry from the map specified by key and bin with a value that has the given rank.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- rank –
int
the rank of the value of the entry in the map - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_remove_by_rank_range
(key, bin, rank, range, return_type[, meta[, policy]])¶ Remove and optionally return the map entries from the map specified by key and bin which have a value rank starting at rank and removing range number of items.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- rank –
int
the rank of the value of the first map entry to remove - range –
int
the number of items to remove from the map - return_type –
int
Map Return Types - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_key
(key, bin, map_key, return_type[, meta[, policy]])¶ Return map entry from the map specified by key and bin which has a key that matches the given map_key.
Parameters: Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_key_range
(key, bin, map_key, range, return_type[, meta[, policy]])¶ Return map entries from the map specified by key and bin identified by the key range (map_key inclusive, range exclusive).
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- map_key –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - range –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_value
(key, bin, val, return_type[, meta[, policy]])¶ Return map entries from the map specified by key and bin which have a value matching val parameter.
Parameters: Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_value_range
(key, bin, val, range, return_type[, meta[, policy]])¶ Return map entries from the map specified by key and bin identified by the value range (val inclusive, range exclusive).
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- val –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - range –
int
,str
,float
,bytearray
. An unsupported type will be serialized. - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_index
(key, bin, index, return_type[, meta[, policy]])¶ Return the map entry from the map specified by key and bin at the given index location.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index –
int
the index location of the map entry - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_index_range
(key, bin, index, range, return_type[, meta[, policy]])¶ Return the map entries from the map specified by key and bin starting at the given index location and removing range number of items.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- index –
int
the index location of the first map entry to remove - range –
int
the number of items to remove from the map - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_rank
(key, bin, rank, return_type[, meta[, policy]])¶ Return the map entry from the map specified by key and bin with a value that has the given rank.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- rank –
int
the rank of the value of the entry in the map - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
map_get_by_rank_range
(key, bin, rank, range, return_type[, meta[, policy]])¶ Return the map entries from the map specified by key and bin which have a value rank starting at rank and removing range number of items.
Parameters: - key (tuple) – a Key Tuple tuple associated with the record.
- bin (str) – the name of the bin.
- rank –
int
the rank of the value of the first map entry to remove - range –
int
the number of items to remove from the map - return_type –
int
Map Return Types - meta (dict) – unused for this operation
- policy (dict) – optional Operate Policies.
Raises: a subclass of
AerospikeError
.Returns: depends on return_type parameter
Note
Requires server version >= 3.8.4
New in version 2.0.4.
-
operate
(key, list[, meta[, policy]]) -> (key, meta, bins)¶ Perform multiple bin operations on a record with a given key, In Aerospike server versions prior to 3.6.0, non-existent bins being read will have a
None
value. Starting with 3.6.0 non-existent bins will not be present in the returned Record Tuple. The returned record tuple will only contain one entry per bin, even if multiple operations were performed on the bin.Parameters: - key (tuple) – a Key Tuple associated with the record.
- list (list) – a
list
of one or more bin operations, each structured as thedict
{'bin': bin name, 'op': aerospike.OPERATOR_* [, 'val': value]}
. See Operators. - meta (dict) – optional record metadata to be set, with field
'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
- policy (dict) – optional Operate Policies.
Returns: a Record Tuple. See Unicode Handling.
Raises: a subclass of
AerospikeError
.Note
In version 2.1.3 the return format of certain bin entries for this method, only in cases when a map operation specifying a `return_type` is used, has changed. Bin entries for map operations using “return_type” of aerospike.MAP_RETURN_KEY_VALUE will now return a bin value of a list of keys and corresponding values, rather than a list of key/value tuples. See the following code block for details.
# pre 2.1.3 formatting of key/value bin value [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')] # >= 2.1.3 formatting ['key1', 'val1', 'key2', 'val2', 'key3', 'val3']
Note
operate()
can now have multiple write operations on a single bin.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) client.put(key, {'age': 25, 'career': 'delivery boy'}) ops = [ { "op" : aerospike.OPERATOR_INCR, "bin": "age", "val": 1000 }, { "op" : aerospike.OPERATOR_WRITE, "bin": "name", "val": "J." }, { "op" : aerospike.OPERATOR_PREPEND, "bin": "name", "val": "Phillip " }, { "op" : aerospike.OPERATOR_APPEND, "bin": "name", "val": " Fry" }, { "op" : aerospike.OPERATOR_READ, "bin": "name" }, { "op" : aerospike.OPERATOR_READ, "bin": "career" } ] (key, meta, bins) = client.operate(key, ops, {'ttl':360}, {'total_timeout':500}) print(key) print('--------------------------') print(meta) print('--------------------------') print(bins) # will display all bins selected by OPERATOR_READ operations except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Note
OPERATOR_TOUCH
should only ever combine withOPERATOR_READ
, for example to implement LRU expiry on the records of a set.Warning
Having val associated with
OPERATOR_TOUCH
is deprecated. Use the meta ttl field instead.from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) ops = [ { "op" : aerospike.OPERATOR_TOUCH, }, { "op" : aerospike.OPERATOR_READ, "bin": "name" } ] (key, meta, bins) = client.operate(key, ops, {'ttl':1800}) print("Touched the record for {0}, extending its ttl by 30m".format(bins)) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Changed in version 2.1.3.
-
operate_ordered
(key, list[, meta[, policy]]) -> (key, meta, bins)¶ Perform multiple bin operations on a record with the results being returned as a list of (bin-name, result) tuples. The order of the elements in the list will correspond to the order of the operations from the input parameters.
param tuple key: a Key Tuple associated with the record. param list list: a list
of one or more bin operations, each structured as thedict
{'bin': bin name, 'op': aerospike.OPERATOR_* [, 'val': value]}
. See Operators.param dict meta: optional record metadata to be set, with field 'ttl'
set toint
number of seconds or one ofaerospike.TTL_NAMESPACE_DEFAULT
,aerospike.TTL_NEVER_EXPIRE
,aerospike.TTL_DONT_UPDATE
param dict policy: optional Operate Policies. return: a Record Tuple. See Unicode Handling. raises: a subclass of AerospikeError
.Note
In version 2.1.3 the return format of bin entries for this method, only in cases when a map operation specifying a `return_type` is used, has changed. Map operations using “return_type” of aerospike.MAP_RETURN_KEY_VALUE will now return a bin value of a list of keys and corresponding values, rather than a list of key/value tuples. See the following code block for details. In addition, some operations which did not return a value in versions <= 2.1.2 will now return a response.
# pre 2.1.3 formatting of key/value bin value [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')] # >= 2.1.3 formatting ['key1', 'val1', 'key2', 'val2', 'key3', 'val3']
from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: key = ('test', 'demo', 1) policy = { 'total_timeout': 1000, 'key': aerospike.POLICY_KEY_SEND, 'commit_level': aerospike.POLICY_COMMIT_LEVEL_MASTER } llist = [{"op": aerospike.OPERATOR_APPEND, "bin": "name", "val": "aa"}, {"op": aerospike.OPERATOR_READ, "bin": "name"}, {"op": aerospike.OPERATOR_INCR, "bin": "age", "val": 3}] client.operate_ordered(key, llist, {}, policy) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
New in version 2.0.2.
Changed in version 2.1.3.
Batch Operations
-
get_many
(keys[, policy]) → [ (key, meta, bins)]¶ Batch-read multiple records, and return them as a
list
. Any record that does not exist will have aNone
value for metadata and bins in the record tuple.Parameters: - keys (list) – a list of Key Tuple.
- policy (dict) – optional Batch Policies.
Returns: a
list
of Record Tuple.Raises: a
ClientError
if the batch is too big.See also
More information about the Batch Index interface new to Aerospike server >= 3.6.0.
from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: # assume the fourth key has no matching record keys = [ ('test', 'demo', '1'), ('test', 'demo', '2'), ('test', 'demo', '3'), ('test', 'demo', '4') ] records = client.get_many(keys) print records except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Note
We expect to see something like:
[ (('test', 'demo', '1', bytearray(b'ev\xb4\x88\x8c\xcf\x92\x9c \x0bo\xbd\x90\xd0\x9d\xf3\xf6\xd1\x0c\xf3')), {'gen': 1, 'ttl': 2592000}, {'age': 1, 'name': u'Name1'}), (('test', 'demo', '2', bytearray(b'n\xcd7p\x88\xdcF\xe1\xd6\x0e\x05\xfb\xcbs\xa68I\xf0T\xfd')), {'gen': 1, 'ttl': 2592000}, {'age': 2, 'name': u'Name2'}), (('test', 'demo', '3', bytearray(b'\x9f\xf2\xe3\xf3\xc0\xc1\xc3q\xb5$n\xf8\xccV\xa9\xed\xd91a\x86')), {'gen': 1, 'ttl': 2592000}, {'age': 3, 'name': u'Name3'}), (('test', 'demo', '4', bytearray(b'\x8eu\x19\xbe\xe0(\xda ^\xfa\x8ca\x93s\xe8\xb3%\xa8]\x8b')), None, None) ]
Warning
The return type changed to
list
starting with version 1.0.50.Changed in version 1.0.50.
-
exists_many
(keys[, policy]) → [ (key, meta)]¶ Batch-read metadata for multiple keys, and return it as a
list
. Any record that does not exist will have aNone
value for metadata in the result tuple.Parameters: - keys (list) – a list of Key Tuple.
- policy (dict) – optional Batch Policies.
Returns: a
list
of (key, metadata)tuple()
.See also
More information about the Batch Index interface new to Aerospike server >= 3.6.0.
from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: # assume the fourth key has no matching record keys = [ ('test', 'demo', '1'), ('test', 'demo', '2'), ('test', 'demo', '3'), ('test', 'demo', '4') ] records = client.exists_many(keys) print records except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Note
We expect to see something like:
[ (('test', 'demo', '1', bytearray(b'ev\xb4\x88\x8c\xcf\x92\x9c \x0bo\xbd\x90\xd0\x9d\xf3\xf6\xd1\x0c\xf3')), {'gen': 2, 'ttl': 2592000}), (('test', 'demo', '2', bytearray(b'n\xcd7p\x88\xdcF\xe1\xd6\x0e\x05\xfb\xcbs\xa68I\xf0T\xfd')), {'gen': 7, 'ttl': 1337}), (('test', 'demo', '3', bytearray(b'\x9f\xf2\xe3\xf3\xc0\xc1\xc3q\xb5$n\xf8\xccV\xa9\xed\xd91a\x86')), {'gen': 9, 'ttl': 543}), (('test', 'demo', '4', bytearray(b'\x8eu\x19\xbe\xe0(\xda ^\xfa\x8ca\x93s\xe8\xb3%\xa8]\x8b')), None) ]
Warning
The return type changed to
list
starting with version 1.0.50.Changed in version 1.0.50.
-
select_many
(keys, bins[, policy]) → [(key, meta, bins), ...]}¶ Batch-read multiple records, and return them as a
list
. Any record that does not exist will have aNone
value for metadata and bins in the record tuple. The bins will be filtered as specified.Parameters: - keys (list) – a list of Key Tuple.
- bins (list) – the bin names to select from the matching records.
- policy (dict) – optional Batch Policies.
Returns: a
list
of Record Tuple.See also
More information about the Batch Index interface new to Aerospike server >= 3.6.0.
from __future__ import print_function import aerospike from aerospike import exception as ex import sys config = { 'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() try: # assume the fourth key has no matching record keys = [ ('test', 'demo', None, bytearray(b'ev\xb4\x88\x8c\xcf\x92\x9c \x0bo\xbd\x90\xd0\x9d\xf3\xf6\xd1\x0c\xf3'), ('test', 'demo', None, bytearray(b'n\xcd7p\x88\xdcF\xe1\xd6\x0e\x05\xfb\xcbs\xa68I\xf0T\xfd'), ('test', 'demo', None, bytearray(b'\x9f\xf2\xe3\xf3\xc0\xc1\xc3q\xb5$n\xf8\xccV\xa9\xed\xd91a\x86'), ('test', 'demo', None, bytearray(b'\x8eu\x19\xbe\xe0(\xda ^\xfa\x8ca\x93s\xe8\xb3%\xa8]\x8b') ] records = client.select_many(keys, [u'name']) print records except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) sys.exit(1) finally: client.close()
Note
We expect to see something like:
[ (('test', 'demo', None, bytearray(b'ev\xb4\x88\x8c\xcf\x92\x9c \x0bo\xbd\x90\xd0\x9d\xf3\xf6\xd1\x0c\xf3'), {'gen': 1, 'ttl': 2592000}, {'name': u'Name1'}), (('test', 'demo', None, bytearray(b'n\xcd7p\x88\xdcF\xe1\xd6\x0e\x05\xfb\xcbs\xa68I\xf0T\xfd'), {'gen': 1, 'ttl': 2592000}, {'name': u'Name2'}), (('test', 'demo', None, bytearray(b'\x9f\xf2\xe3\xf3\xc0\xc1\xc3q\xb5$n\xf8\xccV\xa9\xed\xd91a\x86'), {'gen': 1, 'ttl': 2592000}, {'name': u'Name3'}), (('test', 'demo', None, bytearray(b'\x8eu\x19\xbe\xe0(\xda ^\xfa\x8ca\x93s\xe8\xb3%\xa8]\x8b'), None, None) ]
Warning
The return type changed to
list
starting with version 1.0.50.Changed in version 1.0.50.
Scans
-
scan
(namespace[, set]) → Scan¶ Return a
aerospike.Scan
object to be used for executing scans over a specified set (which can be omitted orNone
) in a namespace. A scan with aNone
set returns all the records in the namespace.Parameters: Returns: an
aerospike.Scan
class.
Queries
-
query
(namespace[, set]) → Query¶ Return a
aerospike.Query
object to be used for executing queries over a specified set (which can be omitted orNone
) in a namespace. A query with aNone
set returns records which are not in any named set. This is different than the meaning of aNone
set in a scan.Parameters: Returns: an
aerospike.Query
class.
UDFs
-
udf_put
(filename[, udf_type=aerospike.UDF_TYPE_LUA[, policy]])¶ Register a UDF module with the cluster.
Parameters: Raises: a subclass of
AerospikeError
.Note
Register the UDF module and copy it to the Lua ‘user_path’, a directory that should contain a copy of the modules registered with the cluster.
config = { 'hosts': [ ('127.0.0.1', 3000)], 'lua': { 'user_path': '/path/to/lua/user_path'}} client = aerospike.client(config).connect() client.udf_put('/path/to/my_module.lua') client.close()
Changed in version 1.0.45.
-
udf_remove
(module[, policy])¶ Remove a previously registered UDF module from the cluster.
Parameters: Raises: a subclass of
AerospikeError
.client.udf_remove('my_module.lua')
Changed in version 1.0.39.
-
udf_list
([policy]) → []¶ Return the list of UDF modules registered with the cluster.
Parameters: policy (dict) – currently timeout in milliseconds is the available policy. Return type: list
Raises: a subclass of AerospikeError
.from __future__ import print_function import aerospike config = {'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() print(client.udf_list()) client.close()
Note
We expect to see something like:
[{'content': bytearray(b''), 'hash': bytearray(b'195e39ceb51c110950bd'), 'name': 'my_udf1.lua', 'type': 0}, {'content': bytearray(b''), 'hash': bytearray(b'8a2528e8475271877b3b'), 'name': 'stream_udf.lua', 'type': 0}, {'content': bytearray(b''), 'hash': bytearray(b'362ea79c8b64857701c2'), 'name': 'aggregate_udf.lua', 'type': 0}, {'content': bytearray(b''), 'hash': bytearray(b'635f47081431379baa4b'), 'name': 'module.lua', 'type': 0}]
Changed in version 1.0.39.
-
udf_get
(module[, language=aerospike.UDF_TYPE_LUA[, policy]]) → str¶ Return the content of a UDF module which is registered with the cluster.
Parameters: Return type: Raises: a subclass of
AerospikeError
.Changed in version 1.0.39.
-
apply
(key, module, function, args[, policy])¶ Apply a registered (see
udf_put()
) record UDF to a particular record.Parameters: Returns: the value optionally returned by the UDF, one of
str
,int
,float
,bytearray
,list
,dict
.Raises: a subclass of
AerospikeError
.See also
-
scan_apply
(ns, set, module, function[, args[, policy[, options]]]) → int¶ Initiate a background scan and apply a record UDF to each record matched by the scan.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- set (str) – the set name. Should be
None
if the entire namespace is to be scanned. - module (str) – the name of the UDF module.
- function (str) – the name of the UDF to apply to the records matched by the scan.
- args (list) – the arguments to the UDF.
- policy (dict) – optional Scan Policies.
- options (dict) – the Scan Options that will apply to the scan.
Return type: Returns: a job ID that can be used with
job_info()
to track the status of theaerospike.JOB_SCAN
, as it runs in the background.Raises: a subclass of
AerospikeError
.See also
-
query_apply
(ns, set, predicate, module, function[, args[, policy]]) → int¶ Initiate a background query and apply a record UDF to each record matched by the query.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- set (str) – the set name. Should be
None
if you want to query records in the ns which are in no set. - predicate (tuple) – the
tuple()
produced by one of theaerospike.predicates
methods. - module (str) – the name of the UDF module.
- function (str) – the name of the UDF to apply to the records matched by the query.
- args (list) – the arguments to the UDF.
- policy (dict) – optional Write Policies.
Return type: Returns: a job ID that can be used with
job_info()
to track the status of theaerospike.JOB_QUERY
, as it runs in the background.Raises: a subclass of
AerospikeError
.See also
Warning
This functionality will become available with a future release of the Aerospike server.
New in version 1.0.50.
-
job_info
(job_id, module[, policy]) → dict¶ Return the status of a job running in the background.
Parameters: - job_id (int) – the job ID returned by
scan_apply()
andquery_apply()
. - module – one of
aerospike.JOB_SCAN
oraerospike.JOB_QUERY
.
Returns: a
dict
with keys status, records_read, and progress_pct. The value of status is one ofaerospike.JOB_STATUS_*
. See: Job Constants.Raises: a subclass of
AerospikeError
.from __future__ import print_function import aerospike from aerospike import exception as ex import time config = {'hosts': [ ('127.0.0.1', 3000)]} client = aerospike.client(config).connect() try: # run the UDF 'add_val' in Lua module 'simple' on the records of test.demo job_id = client.scan_apply('test', 'demo', 'simple', 'add_val', ['age', 1]) while True: time.sleep(0.25) response = client.job_info(job_id, aerospike.JOB_SCAN) if response['status'] == aerospike.JOB_STATUS_COMPLETED: break print("Job ", str(job_id), " completed") print("Progress percentage : ", response['progress_pct']) print("Number of scanned records : ", response['records_read']) except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) client.close()
New in version 1.0.50.
- job_id (int) – the job ID returned by
-
scan_info
(scan_id) → dict¶ Return the status of a scan running in the background.
Parameters: scan_id (int) – the scan ID returned by scan_apply()
.Returns: a dict
with keys status, records_scanned, and progress_pct. The value of status is one ofaerospike.SCAN_STATUS_*
. See: Scan Constants.Raises: a subclass of AerospikeError
.Deprecated since version 1.0.50: Use
job_info()
instead.from __future__ import print_function import aerospike from aerospike import exception as ex config = {'hosts': [ ('127.0.0.1', 3000)]} client = aerospike.client(config).connect() try: scan_id = client.scan_apply('test', 'demo', 'simple', 'add_val', ['age', 1]) while True: response = client.scan_info(scan_id) if response['status'] == aerospike.SCAN_STATUS_COMPLETED or \ response['status'] == aerospike.SCAN_STATUS_ABORTED: break if response['status'] == aerospike.SCAN_STATUS_COMPLETED: print("Background scan successful") print("Progress percentage : ", response['progress_pct']) print("Number of scanned records : ", response['records_scanned']) print("Background scan status : ", "SCAN_STATUS_COMPLETED") else: print("Scan_apply failed") except ex.AerospikeError as e: print("Error: {0} [{1}]".format(e.msg, e.code)) client.close()
Info
-
index_string_create
(ns, set, bin, index_name[, policy])¶ Create a string index with index_name on the bin in the specified ns, set.
Parameters: Raises: a subclass of
AerospikeError
.Changed in version 1.0.39.
-
index_integer_create
(ns, set, bin, index_name[, policy])¶ Create an integer index with index_name on the bin in the specified ns, set.
Parameters: Raises: a subclass of
AerospikeError
.Changed in version 1.0.39.
-
index_list_create
(ns, set, bin, index_datatype, index_name[, policy])¶ Create an index named index_name for numeric, string or GeoJSON values (as defined by index_datatype) on records of the specified ns, set whose bin is a list.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- set (str) – the set name.
- bin (str) – the name of bin the secondary index is built on.
- index_datatype – Possible values are
aerospike.INDEX_STRING
,aerospike.INDEX_NUMERIC
andaerospike.INDEX_GEO2DSPHERE
. - index_name (str) – the name of the index.
- policy (dict) – optional Info Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.0
New in version 1.0.42.
-
index_map_keys_create
(ns, set, bin, index_datatype, index_name[, policy])¶ Create an index named index_name for numeric, string or GeoJSON values (as defined by index_datatype) on records of the specified ns, set whose bin is a map. The index will include the keys of the map.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- set (str) – the set name.
- bin (str) – the name of bin the secondary index is built on.
- index_datatype – Possible values are
aerospike.INDEX_STRING
,aerospike.INDEX_NUMERIC
andaerospike.INDEX_GEO2DSPHERE
. - index_name (str) – the name of the index.
- policy (dict) – optional Info Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.0
New in version 1.0.42.
-
index_map_values_create
(ns, set, bin, index_datatype, index_name[, policy])¶ Create an index named index_name for numeric, string or GeoJSON values (as defined by index_datatype) on records of the specified ns, set whose bin is a map. The index will include the values of the map.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- set (str) – the set name.
- bin (str) – the name of bin the secondary index is built on.
- index_datatype – Possible values are
aerospike.INDEX_STRING
,aerospike.INDEX_NUMERIC
andaerospike.INDEX_GEO2DSPHERE
. - index_name (str) – the name of the index.
- policy (dict) – optional Info Policies.
Raises: a subclass of
AerospikeError
.Note
Requires server version >= 3.8.0
import aerospike client = aerospike.client({ 'hosts': [ ('127.0.0.1', 3000)]}).connect() # assume the bin fav_movies in the set test.demo bin should contain # a dict { (str) _title_ : (int) _times_viewed_ } # create a secondary index for string values of test.demo records whose 'fav_movies' bin is a map client.index_map_keys_create('test', 'demo', 'fav_movies', aerospike.INDEX_STRING, 'demo_fav_movies_titles_idx') # create a secondary index for integer values of test.demo records whose 'fav_movies' bin is a map client.index_map_values_create('test', 'demo', 'fav_movies', aerospike.INDEX_NUMERIC, 'demo_fav_movies_views_idx') client.close()
New in version 1.0.42.
-
index_geo2dsphere_create
(ns, set, bin, index_name[, policy])¶ Create a geospatial 2D spherical index with index_name on the bin in the specified ns, set.
Parameters: Raises: a subclass of
AerospikeError
.See also
Note
Requires server version >= 3.7.0
import aerospike client = aerospike.client({ 'hosts': [ ('127.0.0.1', 3000)]}).connect() client.index_geo2dsphere_create('test', 'pads', 'loc', 'pads_loc_geo') client.close()
New in version 1.0.53.
-
index_remove
(ns, index_name[, policy])¶ Remove the index with index_name from the namespace.
Parameters: - ns (str) – the namespace in the aerospike cluster.
- index_name (str) – the name of the index.
- policy (dict) – optional Info Policies.
Raises: a subclass of
AerospikeError
.Changed in version 1.0.39.
-
get_nodes
() → []¶ Return the list of hosts present in a connected cluster.
return: a list
of node address tuples.raises: a subclass of AerospikeError
.import aerospike config = {'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() nodes = client.get_nodes() print(nodes) client.close()
Note
We expect to see something like:
[('127.0.0.1', 3000), ('127.0.0.1', 3010)]
Changed in version 3.0.0.
Warning
In versions < 3.0.0
get_nodes
will not work when using TLS-
info
(command[, hosts[, policy]]) → {}¶ Deprecated since version 3.0.0: Use
info_node()
to send a request to a single node, orinfo_all()
to send a request to the entire cluster. Sending requests to specific nodes can be better handled with a simple Python function such as:def info_to_host_list(client, request, hosts, policy=None): output = {} for host in hosts: try: response = client.info_node(request, host, policy) output[host] = response except Exception as e: # Handle the error gracefully here output[host] = e return output
Send an info command to all nodes in the cluster and filter responses to only include nodes specified in a hosts list.
Parameters: - command (str) – the info command.
- hosts (list) – a
list
containing an address, porttuple()
. Example:[('127.0.0.1', 3000)]
- policy (dict) – optional Info Policies.
Return type: Raises: a subclass of
AerospikeError
.See also
import aerospike config = {'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() response = client.info(command) client.close()
Note
We expect to see something like:
{'BB9581F41290C00': (None, '127.0.0.1:3000\n'), 'BC3581F41290C00': (None, '127.0.0.1:3010\n')}
Changed in version 3.0.0.
-
info_all
(command[, policy]]) → {}¶ Send an info command to all nodes in the cluster to which the client is connected. If any of the individual requests fail, this will raise an exception.
Parameters: - command (str) – the info command.
- policy (dict) – optional Info Policies.
Return type: Raises: a subclass of
AerospikeError
.See also
import aerospike config = {'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect() response = client.info_all(command) client.close()
Note
We expect to see something like:
{'BB9581F41290C00': (None, '127.0.0.1:3000\n'), 'BC3581F41290C00': (None, '127.0.0.1:3010\n')}
New in version 3.0.0.
-
info_node
(command, host[, policy]) → str¶ Send an info command to a single node specified by host.
Parameters: - command (str) – the info command.
- host (tuple) – a
tuple()
containing an address, port , optional tls-name . Example:('127.0.0.1', 3000)
or when using TLS('127.0.0.1', 4333, 'server-tls-name')
. In order to send an info request when TLS is enabled, the tls-name must be present. - policy (dict) – optional Info Policies.
Return type: Raises: a subclass of
AerospikeError
.See also
Changed in version 3.0.0.
Warning
for client versions < 3.0.0
info_node
will not work when using TLS
-
-
has_geo
() → bool¶ Check whether the connected cluster supports geospatial data and indexes.
Return type: bool
Raises: a subclass of AerospikeError
.New in version 1.0.53.
-
shm_key
() → int¶ Expose the value of the shm_key for this client if shared-memory cluster tending is enabled,
Return type: int
orNone
New in version 1.0.56.
-
truncate
(namespace, set, nanos[, policy])¶ Remove records in specified namespace/set efficiently. This method is many orders of magnitude faster than deleting records one at a time. Works with Aerospike Server versions >= 3.12. See Truncate command reference.
This asynchronous server call may return before the truncation is complete. The user can still write new records after the server returns because new records will have last update times greater than the truncate cutoff (set at the time of truncate call)
Parameters: - namespace (str) – The namespace on which the truncation operation should be performed.
- set (str) – The set to truncate. Pass in
None
to indicate that all records in the namespace should be truncated. - nanos (long) – A cutoff threshold indicating that records last updated before the threshold will be removed.Units are in nanoseconds since unix epoch (1970-01-01). A value of
0
indicates that all records in the set should be truncated regardless of update time. The value must not be in the future. - policy (dict) – Optional Info Policies
Return type: Status indicating the success of the operation.
Raises: a subclass of
AerospikeError
.New in version 2.0.11.
import aerospike import time client = aerospike.client({'hosts': [('localhost', 3000)]}).connect() # Store 10 items in the database for i in range(10): key = ('test', 'truncate', i) record = {'item': i} client.put(key, record) time.sleep(2) current_time = time.time() # Convert the current time to nanoseconds since epoch threshold_ns = int(current_time * 10 ** 9) time.sleep(2) # Make sure some time passes before next round of additions # Store another 10 items into the database for i in range(10, 20): key = ('test', 'truncate', i) record = {'item': i} client.put(key, record) # Store a record in the 'test' namespace without a set key = ('test', None, 'no set') record = ({'item': 'no set'}) client.put(key, record) # Remove all items created before the threshold time # The first 10 records we added will be removed by this call. # The second 10 will remain. client.truncate('test', 'truncate', threshold_ns) # Remove all records from test/truncate. # After this the record with key ('test', None, 'no set') still exists client.truncate('test', 'truncate', 0) # Remove all records from the test namespace client.truncate('test', None, 0) client.close()
Admin
Note
The admin methods implement the security features of the Enterprise Edition of Aerospike. These methods will raise a
SecurityNotSupported
when the client is connected to a Community Edition cluster (seeaerospike.exception
).A user is validated by the client against the server whenever a connection is established through the use of a username and password (passwords hashed using bcrypt). When security is enabled, each operation is validated against the user’s roles. Users are assigned roles, which are collections of Privilege Objects.
import aerospike from aerospike import exception as ex import time config = {'hosts': [('127.0.0.1', 3000)] } client = aerospike.client(config).connect('ipji', 'life is good') try: dev_privileges = [{'code': aerospike.PRIV_READ}, {'code': aerospike.PRIV_READ_WRITE}] client.admin_create_role('dev_role', dev_privileges) client.admin_grant_privileges('dev_role', [{'code': aerospike.PRIV_READ_WRITE_UDF}]) client.admin_create_user('dev', 'you young whatchacallit... idiot', ['dev_role']) time.sleep(1) print(client.admin_query_user('dev')) print(admin_query_users()) except ex.AdminError as e: print("Error [{0}]: {1}".format(e.code, e.msg)) client.close()
See also
-
admin_create_role
(role, privileges[, policy])¶ Create a custom, named role containing a
list
of privileges.Parameters: - role (str) – the name of the role.
- privileges (list) – a list of Privilege Objects.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_drop_role
(role[, policy])¶ Drop a custom role.
Parameters: - role (str) – the name of the role.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_grant_privileges
(role, privileges[, policy])¶ Add privileges to a role.
Parameters: - role (str) – the name of the role.
- privileges (list) – a list of Privilege Objects.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_revoke_privileges
(role, privileges[, policy])¶ Remove privileges from a role.
Parameters: - role (str) – the name of the role.
- privileges (list) – a list of Privilege Objects.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_query_role
(role[, policy]) → []¶ Get the
list
of privileges associated with a role.Parameters: - role (str) – the name of the role.
- policy (dict) – optional Admin Policies.
Returns: a
list
of Privilege Objects.Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_query_roles
([policy]) → {}¶ Get all named roles and their privileges.
Parameters: policy (dict) – optional Admin Policies. Returns: a dict
of Privilege Objects keyed by role name.Raises: one of the AdminError
subclasses.Changed in version 1.0.44.
-
admin_create_user
(username, password, roles[, policy])¶ Create a user with a specified username and grant it roles.
Parameters: - username (str) – the username to be added to the aerospike cluster.
- password (str) – the password associated with the given username.
- roles (list) – the list of role names assigned to the user.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_drop_user
(username[, policy])¶ Drop the user with a specified username from the cluster.
Parameters: - username (str) – the username to be dropped from the aerospike cluster.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_change_password
(username, password[, policy])¶ Change the password of the user username. This operation can only be performed by that same user.
Parameters: - username (str) – the username.
- password (str) – the password associated with the given username.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_set_password
(username, password[, policy])¶ Set the password of the user username by a user administrator.
Parameters: - username (str) – the username to be added to the aerospike cluster.
- password (str) – the password associated with the given username.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_grant_roles
(username, roles[, policy])¶ Add roles to the user username.
Parameters: - username (str) – the username to be granted the roles.
- roles (list) – a list of role names.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_revoke_roles
(username, roles[, policy])¶ Remove roles from the user username.
Parameters: - username (str) – the username to have the roles revoked.
- roles (list) – a list of role names.
- policy (dict) – optional Admin Policies.
Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_query_user
(username[, policy]) → []¶ Return the list of roles granted to the specified user username.
Parameters: - username (str) – the username to query for.
- policy (dict) – optional Admin Policies.
Returns: a
list
of role names.Raises: one of the
AdminError
subclasses.Changed in version 1.0.44.
-
admin_query_users
([policy]) → {}¶ Return the
dict
of users, with their roles keyed by username.Parameters: policy (dict) – optional Admin Policies. Returns: a dict
of roles keyed by username.Raises: one of the AdminError
subclasses.Changed in version 1.0.44.
-
Key Tuple¶
-
key
The key tuple which is sent and returned by various operations contains
(namespace, set, primary key[, the record's RIPEMD-160 digest])
- namespace the
str
name of the namespace, which must be preconfigured on the cluster. - set the
str
name of the set. Will be created automatically if it does not exist. - primary key the value by which the client-side application identifies the record, which can be of type
str
,int
orbytearray
. - digest the first three parts of the tuple get hashed through RIPEMD-160, and the digest used by the clients and cluster nodes to locate the record. A key tuple is also valid if it has the digest part filled and the primary key part set to
None
.
>>> client = aerospike.client(config).connect() >>> client.put(('test','demo','oof'), {'id':0, 'a':1}) >>> (key, meta, bins) = client.get(('test','demo','oof')) >>> key ('test', 'demo', None, bytearray(b'\ti\xcb\xb9\xb6V#V\xecI#\xealu\x05\x00H\x98\xe4=')) >>> (key2, meta2, bins2) = client.get(key) >>> bins2 {'a': 1, 'id': 0} >>> client.close()
See also
Changed in version 1.0.47.
- namespace the
Record Tuple¶
-
record
The record tuple
(key, meta, bins)
which is returned by various read operations.See also
Unicode Handling¶
Both str
and unicode()
values are converted by the
client into UTF-8 encoded strings for storage on the aerospike server.
Read methods such as get()
,
query()
, scan()
and
operate()
will return that data as UTF-8 encoded
str
values. To get a unicode()
you will need to manually decode.
Warning
Prior to release 1.0.43 read operations always returned strings as unicode()
.
>>> client.put(key, { 'name': 'Dr. Zeta Alphabeta', 'age': 47})
>>> (key, meta, record) = client.get(key)
>>> type(record['name'])
<type 'str'>
>>> record['name']
'Dr. Zeta Alphabeta'
>>> client.put(key, { 'name': unichr(0x2603), 'age': 21})
>>> (key, meta, record) = client.get(key)
>>> type(record['name'])
<type 'str'>
>>> record['name']
'\xe2\x98\x83'
>>> print(record['name'])
☃
>>> name = record['name'].decode('utf-8')
>>> type(name)
<type 'unicode'>
>>> name
u'\u2603'
>>> print(name)
☃
Changed in version 1.0.43.
Write Policies¶
-
policy
A
dict
of optional write policies which are applicable toput()
,query_apply()
.remove_bin()
.- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:0
- sleep_between_retries
- An
int
. Milliseconds to sleep between retries. Enter zero to skip sleep. Default:0
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- key one of the
aerospike.POLICY_KEY_*
values such asaerospike.POLICY_KEY_DIGEST
- Default:
aerospike.POLICY_KEY_DIGEST
- key one of the
- exists one of the
aerospike.POLICY_EXISTS_*
values such asaerospike.POLICY_EXISTS_CREATE
- Default:
`aerospike.POLICY_GEN_IGNORE
- exists one of the
- gen one of the
aerospike.POLICY_GEN_*
values such asaerospike.POLICY_GEN_IGNORE
- Default:
aerospike.POLICY_GEN_IGNORE
- gen one of the
- commit_level one of the
aerospike.POLICY_COMMIT_LEVEL_*
values such asaerospike.POLICY_COMMIT_LEVEL_ALL
- Default:
aerospike.POLICY_COMMIT_LEVEL_ALL
- commit_level one of the
- durable_delete boolean value: True to perform durable delete (requires Enterprise server version >= 3.10)
- Default:
False
Read Policies¶
-
policy
A
dict
of optional read policies which are applicable toget()
,exists()
,select()
.- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:2
- sleep_between_retries
- An
int
. Milliseconds to sleep between retries. Enter zero to skip sleep. Default:0
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- deserialize
bool
Should raw bytes representing a list or map be deserialized to a list or dictionary.Set to False for backup programs that just need access to raw bytes.Default:True
- linearize_read
- Force reads to be linearized for server namespaces that support CP mode. Setting this policy to
True
requires an Enterprise server with version 4.0.0 or greater.Default:False
- key one of the
aerospike.POLICY_KEY_*
values such asaerospike.POLICY_KEY_DIGEST
- Default:
aerospike.POLICY_KEY_DIGEST
- key one of the
- consistency_level one of the
aerospike.POLICY_CONSISTENCY_*
values such asaerospike.POLICY_CONSISTENCY_ONE
- Default:
aerospike.POLICY_CONSISTENCY_ONE
- consistency_level one of the
- replica one of the
aerospike.POLICY_REPLICA_*
values such asaerospike.POLICY_REPLICA_MASTER
- Default:
aerospike.POLICY_REPLICA_SEQUENCE
- replica one of the
Operate Policies¶
-
policy
A
dict
of optional operate policies which are applicable toappend()
,prepend()
,increment()
,operate()
, and atomic list and map operations.- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:0
- sleep_between_retries
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- linearize_read
- Force reads to be linearized for server namespaces that support CP mode. Setting this policy to
True
requires an Enterprise server with version 4.0.0 or greater.Default:False
- key one of the
aerospike.POLICY_KEY_*
values such asaerospike.POLICY_KEY_DIGEST
- Default:
aerospike.POLICY_KEY_DIGEST
- key one of the
- gen one of the
aerospike.POLICY_GEN_*
values such asaerospike.POLICY_GEN_IGNORE
- Default:
aerospike.POLICY_GEN_IGNORE
- gen one of the
- replica one of the
aerospike.POLICY_REPLICA_*
values such asaerospike.POLICY_REPLICA_MASTER
- Default:
aerospike.POLICY_REPLICA_SEQUENCE
- replica one of the
- commit_level one of the
aerospike.POLICY_COMMIT_LEVEL_*
values such asaerospike.POLICY_COMMIT_LEVEL_ALL
- Default:
aerospike.POLICY_COMMIT_LEVEL_ALL
- commit_level one of the
- consistency_level one of the
aerospike.POLICY_CONSISTENCY_*
values such asaerospike.POLICY_CONSISTENCY_ONE
- Default:
aerospike.POLICY_CONSISTENCY_ONE
- consistency_level one of the
- exists one of the
aerospike.POLICY_EXISTS_*
values such asaerospike.POLICY_EXISTS_CREATE
- Default:
`aerospike.POLICY_GEN_IGNORE
- exists one of the
durable_delete boolean value: True to perform durable delete (requires Enterprise server version >= 3.10) Default:
False
Apply Policies¶
-
policy
A
dict
of optional apply policies which are applicable toapply()
.- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:0
- sleep_between_retries
- An
int
. Milliseconds to sleep between retries. Enter zero to skip sleep. Default:0
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- linearize_read
- Force reads to be linearized for server namespaces that support CP mode. Setting this policy to
True
requires an Enterprise server with version 4.0.0 or greater.Default:False
- key one of the
aerospike.POLICY_KEY_*
values such asaerospike.POLICY_KEY_DIGEST
- Default:
aerospike.POLICY_KEY_DIGEST
- key one of the
- replica one of the
aerospike.POLICY_REPLICA_*
values such asaerospike.POLICY_REPLICA_MASTER
- Default:
aerospike.POLICY_REPLICA_SEQUENCE
- replica one of the
- gen one of the
aerospike.POLICY_GEN_*
values such asaerospike.POLICY_GEN_IGNORE
- Default:
aerospike.POLICY_GEN_IGNORE
- gen one of the
- commit_level one of the
aerospike.POLICY_COMMIT_LEVEL_*
values such asaerospike.POLICY_COMMIT_LEVEL_ALL
- Default:
aerospike.POLICY_COMMIT_LEVEL_ALL
- commit_level one of the
- durable_delete boolean value: True to perform durable delete (requires Enterprise server version >= 3.10)
- Default:
False
Remove Policies¶
-
policy
A
dict
of optional remove policies which are applicable toremove()
.- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:0
- sleep_between_retries
- An
int
. Milliseconds to sleep between retries. Enter zero to skip sleep. Default:0
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- key one of the
aerospike.POLICY_KEY_*
values such asaerospike.POLICY_KEY_DIGEST
- Default:
aerospike.POLICY_KEY_DIGEST
- key one of the
- commit_level one of the
aerospike.POLICY_COMMIT_LEVEL_*
values such asaerospike.POLICY_COMMIT_LEVEL_ALL
- Default:
aerospike.POLICY_COMMIT_LEVEL_ALL
- commit_level one of the
- gen one of the
aerospike.POLICY_GEN_*
values such asaerospike.POLICY_GEN_IGNORE
- Default:
aerospike.POLICY_GEN_IGNORE
- gen one of the
durable_delete boolean value: True to perform durable delete (requires Enterprise server version >= 3.10) Default:
False
- replica one of the
aerospike.POLICY_REPLICA_*
values such asaerospike.POLICY_REPLICA_MASTER
- Default:
aerospike.POLICY_REPLICA_SEQUENCE
- replica one of the
Batch Policies¶
-
policy
- A
dict
of optional batch policies which are applicable to get_many()
,exists_many()
andselect_many()
.
- max_retries
- An
int
. Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry.If max_retries is exceeded, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
.WARNING: Database writes that are not idempotent (such as “add”) should not be retried because the write operation may be performed multiple timesif the client timed out previous transaction attempts. It’s important to use a distinct write policy for non-idempotent writes which sets max_retries = 0;Default:2
- sleep_between_retries
- socket_timeout
- An
int
. Socket idle timeout in milliseconds when processing a database command.If socket_timeout is not zero and the socket has been idle for at least socket_timeout, both max_retries and total_timeout are checked. If max_retries and total_timeout are not exceeded, the transaction is retried.If bothsocket_timeout
andtotal_timeout
are non-zero andsocket_timeout
>total_timeout
, thensocket_timeout
will be set tototal_timeout
. Ifsocket_timeout
is zero, there will be no socket idle limit.Default:0
.
- total_timeout
- An
int
. Total transaction timeout in milliseconds.The total_timeout is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction.Iftotal_timeout
is not zero andtotal_timeout
is reached before the transaction completes, the transaction will return errorAEROSPIKE_ERR_TIMEOUT
. Iftotal_timeout
is zero, there will be no total time limit.Default:1000
- linearize_read
- Force reads to be linearized for server namespaces that support CP mode. Setting this policy to
True
requires an Enterprise server with version 4.0.0 or greater.Default:False
- consistency_level one of the
aerospike.POLICY_CONSISTENCY_*
values such asaerospike.POLICY_CONSISTENCY_ONE
- Default:
aerospike.POLICY_CONSISTENCY_ONE
- consistency_level one of the
concurrent
bool
Determine if batch commands to each server are run in parallel threads. Default Falseallow_inline
bool
. Allow batch to be processed immediately in the server’s receiving thread when the server deems it to be appropriate. If False, the batch will always be processed in separate transaction threads. This field is only relevant for the new batch index protocol. Default True.send_set_name
bool
Send set name field to server for every key in the batch for batch index protocol. This is only necessary when authentication is enabled and security roles are defined on a per set basis. Default: Falsedeserialize
bool
Should raw bytes be deserialized to as_list or as_map. Set to False for backup programs that just need access to raw bytes. Default: True
- A
Info Policies¶
-
policy
- A
dict
of optional info policies which are applicable to info()
,info_node()
and index operations.
- timeout read timeout in milliseconds
- A
Admin Policies¶
-
policy
A
dict
of optional admin policies which are applicable to admin (security) operations.- timeout admin operation timeout in milliseconds
Map Policies¶
-
policy
A
dict
of optional map policies which are applicable to map operations.- map_write_mode write mode for the map. Valid values: aerospike.MAP_UPDATE, aerospike.MAP_UPDATE_ONLY, aerospike.MAP_CREATE_ONLY
- map_order ordering to maintain for the map entries. Valid values: aerospike.MAP_UNORDERED, aerospike.MAP_KEY_ORDERED, aerospike.MAP_KEY_VALUE_ORDERED
Privilege Objects¶
-
privilege
A
dict
describing a privilege associated with a specific role.- code one of the
aerospike.PRIV_*
values such asaerospike.PRIV_READ
- ns optional namespace to which the privilege applies, otherwise the privilege applies globally.
- set optional set within the ns to which the privilege applies, otherwise to the entire namespace.
Example:
{'code': aerospike.PRIV_READ, 'ns': 'test', 'set': 'demo'}
- code one of the