Skip to main content
Version: 0.4.0

Client

aerospike-py provides both synchronous (Client) and asynchronous (AsyncClient) APIs with identical functionality.

Factory Functions

client(config)

Create a new Aerospike client instance.

ParameterDescription
configClientConfig dictionary. Must contain a "hosts" key with a list of (host, port) tuples.

Returns: A new Client instance (not yet connected).

import aerospike_py

client = aerospike_py.client({
"hosts": [("127.0.0.1", 3000)],
}).connect()

set_log_level(level)

Set the aerospike_py log level.

Accepts LOG_LEVEL_* constants. Controls both Rust-internal and Python-side logging.

ParameterDescription
levelOne of LOG_LEVEL_OFF (-1), LOG_LEVEL_ERROR (0), LOG_LEVEL_WARN (1), LOG_LEVEL_INFO (2), LOG_LEVEL_DEBUG (3), LOG_LEVEL_TRACE (4).
import aerospike_py

aerospike_py.set_log_level(aerospike_py.LOG_LEVEL_DEBUG)

get_metrics()

Return collected metrics in Prometheus text format.

Returns: A string in Prometheus exposition format.

print(aerospike_py.get_metrics())

start_metrics_server(port=9464)

Start a background HTTP server serving /metrics for Prometheus.

ParameterDescription
portTCP port to listen on (default 9464).
aerospike_py.start_metrics_server(port=9464)

stop_metrics_server()

Stop the background metrics HTTP server.

aerospike_py.stop_metrics_server()

Connection

connect(username=None, password=None)

Connect to the Aerospike cluster.

Returns self for method chaining.

ParameterDescription
usernameOptional username for authentication.
passwordOptional password for authentication.

Returns: The connected client instance.

note

Raises ClusterError Failed to connect to any cluster node.

client = aerospike_py.client(config).connect()

# With authentication
client = aerospike_py.client(config).connect("admin", "admin")

is_connected()

Check whether the client is connected to the cluster.

Returns: True if the client has an active cluster connection.

if client.is_connected():
print("Connected")

close()

Close the connection to the cluster.

After calling this method the client can no longer be used for database operations.

client.close()

get_node_names()

Return the names of all nodes in the cluster.

Returns: A list of node name strings.

nodes = client.get_node_names()
# ['BB9020011AC4202', 'BB9030011AC4202']

Info

info_all(command, policy=None)

Send an info command to all cluster nodes.

ParameterDescription
commandThe info command string (e.g. "namespaces").
policyOptional AdminPolicy dict.

Returns: A list of InfoNodeResult(node_name, error_code, response) tuples.

results = client.info_all("namespaces")
for node, err, response in results:
print(f"{node}: {response}")

info_random_node(command, policy=None)

Send an info command to a random cluster node.

ParameterDescription
commandThe info command string.
policyOptional AdminPolicy dict.

Returns: The info response string.

response = client.info_random_node("build")

CRUD Operations

put(key, bins, meta=None, policy=None)

Write a record to the Aerospike cluster.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
binsDictionary of bin name-value pairs to write.
metaOptional WriteMeta dict (e.g. {"ttl": 300}).
policyOptional WritePolicy dict.
note

Raises RecordExistsError Record already exists (with CREATE_ONLY policy).

note

Raises RecordTooBig Record size exceeds the configured write-block-size.

key = ("test", "demo", "user1")
client.put(key, {"name": "Alice", "age": 30})

# With TTL (seconds)
client.put(key, {"score": 100}, meta={"ttl": 300})

# Create only (fail if exists)
import aerospike_py
client.put(
key,
{"x": 1},
policy={"exists": aerospike_py.POLICY_EXISTS_CREATE_ONLY},
)

get(key, policy=None)

Read a record from the cluster.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
policyOptional ReadPolicy dict.

Returns: A Record NamedTuple with key, meta, bins fields.

note

Raises RecordNotFound The record does not exist.

record = client.get(("test", "demo", "user1"))
print(record.bins) # {"name": "Alice", "age": 30}

select(key, bins, policy=None)

Read specific bins from a record.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
binsList of bin names to retrieve.
policyOptional ReadPolicy dict.

Returns: A Record NamedTuple with key, meta, bins fields.

note

Raises RecordNotFound The record does not exist.

record = client.select(("test", "demo", "user1"), ["name"])
# record.bins = {"name": "Alice"}

exists(key, policy=None)

Check whether a record exists.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
policyOptional ReadPolicy dict.

Returns: An ExistsResult NamedTuple with key, meta fields. meta is None if the record does not exist.

result = client.exists(("test", "demo", "user1"))
if result.meta is not None:
print(f"Found, gen={result.meta.gen}")

remove(key, meta=None, policy=None)

Delete a record from the cluster.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
metaOptional WriteMeta dict for generation check.
policyOptional WritePolicy dict.
note

Raises RecordNotFound The record does not exist.

client.remove(("test", "demo", "user1"))

# With generation check
import aerospike_py
client.remove(
key,
meta={"gen": 3},
policy={"gen": aerospike_py.POLICY_GEN_EQ},
)

touch(key, val=0, meta=None, policy=None)

Reset the TTL of a record.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
valNew TTL value in seconds.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.
note

Raises RecordNotFound The record does not exist.

client.touch(("test", "demo", "user1"), val=300)

String / Numeric Operations

append(key, bin, val, meta=None, policy=None)

Append a string to a bin value.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
binTarget bin name.
valString value to append.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.
client.append(("test", "demo", "user1"), "name", "_suffix")

prepend(key, bin, val, meta=None, policy=None)

Prepend a string to a bin value.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
binTarget bin name.
valString value to prepend.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.
client.prepend(("test", "demo", "user1"), "name", "prefix_")

increment(key, bin, offset, meta=None, policy=None)

Increment a numeric bin value.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
binTarget bin name.
offsetInteger or float amount to add (use negative to decrement).
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.
client.increment(("test", "demo", "user1"), "age", 1)
client.increment(("test", "demo", "user1"), "score", 0.5)

remove_bin(key, bin_names, meta=None, policy=None)

Remove specific bins from a record by setting them to nil.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
bin_namesList of bin names to remove.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.
client.remove_bin(("test", "demo", "user1"), ["temp_bin", "debug_bin"])

Multi-Operation

operate(key, ops, meta=None, policy=None)

Execute multiple operations atomically on a single record.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
opsList of operation dicts with "op", "bin", "val" keys.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.

Returns: A Record NamedTuple with key, meta, bins fields.

import aerospike_py

ops = [
{"op": aerospike_py.OPERATOR_INCR, "bin": "counter", "val": 1},
{"op": aerospike_py.OPERATOR_READ, "bin": "counter", "val": None},
]
record = client.operate(("test", "demo", "key1"), ops)
print(record.bins)

operate_ordered(key, ops, meta=None, policy=None)

Execute multiple operations with ordered results.

Like operate() but returns results as an ordered list preserving the operation order.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
opsList of operation dicts with "op", "bin", "val" keys.
metaOptional WriteMeta dict.
policyOptional WritePolicy dict.

Returns: An OperateOrderedResult NamedTuple with key, meta, ordered_bins fields.

import aerospike_py

ops = [
{"op": aerospike_py.OPERATOR_INCR, "bin": "counter", "val": 1},
{"op": aerospike_py.OPERATOR_READ, "bin": "counter", "val": None},
]
result = client.operate_ordered(("test", "demo", "key1"), ops)
# result.ordered_bins = [BinTuple("counter", 2)]

Batch Operations

batch_read(keys, bins=None, policy=None, _dtype=None)

Read multiple records in a single batch call.

ParameterDescription
keysList of (namespace, set, primary_key) tuples.
binsOptional list of bin names to read. None reads all bins; an empty list performs an existence check only.
policyOptional BatchPolicy dict.
_dtypeOptional NumPy dtype. When provided, returns NumpyBatchRecords instead of the default type.

Returns: Sync: BatchRecords. Async: BatchReadHandle (or NumpyBatchRecords when _dtype is set).

keys = [("test", "demo", f"user_{i}") for i in range(10)]

batch = client.batch_read(keys)
for br in batch.batch_records:
if br.result == 0 and br.record is not None:
print(br.record.bins)

# Read specific bins
batch = client.batch_read(keys, bins=["name", "age"])

batch_operate(keys, ops, policy=None)

Execute operations on multiple records in a single batch call.

ParameterDescription
keysList of (namespace, set, primary_key) tuples.
opsList of operation dicts to apply to each record.
policyOptional BatchPolicy dict.

Returns: A list of BatchRecord NamedTuples with per-record result codes.

import aerospike_py

keys = [("test", "demo", f"user_{i}") for i in range(10)]
ops = [{"op": aerospike_py.OPERATOR_INCR, "bin": "views", "val": 1}]
results = client.batch_operate(keys, ops)
for br in results.batch_records:
if br.result == 0 and br.record is not None:
print(br.record.bins)

batch_write(records, policy=None, retry=0)

Write multiple records with per-record bins in a single batch call. Each record is a (key, bins) or (key, bins, meta) tuple. Unlike batch_operate() which applies the same operations to all keys, each record can have different bins and TTL.

ParameterDescription
recordsList of (key, bins) or (key, bins, meta) tuples. Key is (namespace, set, primary_key), bins is a dict, meta is an optional WriteMeta dict (e.g. {"ttl": 300}).
policyOptional BatchPolicy dict. Supports "ttl" key for batch-level TTL (seconds).
retryMax retries for transient failures (default 0). Failed records are retried with exponential backoff.

TTL precedence: Per-record meta["ttl"] overrides batch-level policy["ttl"]. Records without meta use the batch-level TTL (or namespace default if unset).

Returns: BatchRecords with per-record result codes. Each BatchRecord includes an in_doubt flag indicating whether the write may have completed despite the error.

records = [
(("test", "demo", "user1"), {"name": "Alice", "age": 30}),
(("test", "demo", "user2"), {"name": "Bob", "age": 25}),
]
results = client.batch_write(records, retry=3)

# With batch-level TTL (30 days)
results = client.batch_write(records, policy={"ttl": 2592000})

# With per-record TTL
records_with_ttl = [
(("test", "demo", "user1"), {"name": "Alice"}, {"ttl": 3600}),
(("test", "demo", "user2"), {"name": "Bob"}, {"ttl": 86400}),
]
results = client.batch_write(records_with_ttl)

batch_remove(keys, policy=None)

Delete multiple records in a single batch call.

ParameterDescription
keysList of (namespace, set, primary_key) tuples.
policyOptional BatchPolicy dict.

Returns: A list of BatchRecord NamedTuples with per-record result codes.

keys = [("test", "demo", f"user_{i}") for i in range(10)]
results = client.batch_remove(keys)
failed = [br for br in results.batch_records if br.result != 0]

Query & Scan

query(namespace, set_name)

Create a Query object for secondary index queries.

ParameterDescription
namespaceThe namespace to query.
set_nameThe set to query.

Returns: A Query object. Use where() to set a predicate filter and results() or foreach() to execute.

query = client.query("test", "demo")
query.select("name", "age")
query.where(predicates.between("age", 20, 30))
records = query.results()

Index Management

index_integer_create(namespace, set_name, bin_name, index_name, policy=None)

Create a numeric secondary index.

ParameterDescription
namespaceTarget namespace.
set_nameTarget set.
bin_nameBin to index.
index_nameName for the new index.
policyOptional AdminPolicy dict.
note

Raises IndexFoundError An index with that name already exists.

client.index_integer_create("test", "demo", "age", "age_idx")

index_string_create(namespace, set_name, bin_name, index_name, policy=None)

Create a string secondary index.

ParameterDescription
namespaceTarget namespace.
set_nameTarget set.
bin_nameBin to index.
index_nameName for the new index.
policyOptional AdminPolicy dict.
note

Raises IndexFoundError An index with that name already exists.

client.index_string_create("test", "demo", "name", "name_idx")

index_geo2dsphere_create(namespace, set_name, bin_name, index_name, policy=None)

Create a geospatial secondary index.

ParameterDescription
namespaceTarget namespace.
set_nameTarget set.
bin_nameBin to index (must contain GeoJSON values).
index_nameName for the new index.
policyOptional AdminPolicy dict.
note

Raises IndexFoundError An index with that name already exists.

client.index_geo2dsphere_create("test", "demo", "location", "geo_idx")

index_remove(namespace, index_name, policy=None)

Remove a secondary index.

ParameterDescription
namespaceTarget namespace.
index_nameName of the index to remove.
policyOptional AdminPolicy dict.
note

Raises IndexNotFound The index does not exist.

client.index_remove("test", "age_idx")

Truncate

truncate(namespace, set_name, nanos=0, policy=None)

Remove all records in a namespace/set.

ParameterDescription
namespaceTarget namespace.
set_nameTarget set.
nanosOptional last-update cutoff in nanoseconds.
policyOptional AdminPolicy dict.
client.truncate("test", "demo")

UDF

udf_put(filename, udf_type=0, policy=None)

Register a Lua UDF module on the cluster.

ParameterDescription
filenamePath to the Lua source file.
udf_typeUDF language type (only Lua 0 is supported).
policyOptional AdminPolicy dict.
client.udf_put("my_udf.lua")

udf_remove(module, policy=None)

Remove a registered UDF module.

ParameterDescription
moduleModule name to remove (without .lua extension).
policyOptional AdminPolicy dict.
client.udf_remove("my_udf")

apply(key, module, function, args=None, policy=None)

Execute a UDF on a single record.

ParameterDescription
keyRecord key as (namespace, set, primary_key) tuple.
moduleName of the registered UDF module.
functionName of the function within the module.
argsOptional list of arguments to pass to the function.
policyOptional WritePolicy dict.

Returns: The return value of the UDF function.

result = client.apply(
("test", "demo", "key1"),
"my_udf",
"my_function",
[1, "hello"],
)

Query Object

Secondary index query object.

Created via Client.query(namespace, set_name). Use where() to set a predicate filter, select() to choose bins, then results() or foreach() to execute.

from aerospike_py import predicates

query = client.query("test", "demo")
query.select("name", "age")
query.where(predicates.between("age", 20, 30))
records = query.results()

select()

Select specific bins to return in query results.

query = client.query("test", "demo")
query.select("name", "age")

where(predicate)

Set a predicate filter for the query.

Requires a matching secondary index on the filtered bin.

ParameterDescription
predicateA predicate tuple created by aerospike_py.predicates helper functions.
from aerospike_py import predicates

query = client.query("test", "demo")
query.where(predicates.equals("name", "Alice"))

results(policy=None)

Execute the query and return all matching records.

ParameterDescription
policyOptional QueryPolicy dict.

Returns: A list of Record NamedTuples.

records = query.results()
for record in records:
print(record.bins)

foreach(callback, policy=None)

Execute the query and invoke a callback for each record.

The callback receives a Record NamedTuple. Return False from the callback to stop iteration early.

ParameterDescription
callbackFunction called with each record. Return False to stop.
policyOptional QueryPolicy dict.
def process(record):
print(record.bins)

query.foreach(process)