Client
aerospike-py provides both synchronous (Client) and asynchronous (AsyncClient) APIs with identical functionality.
Factory Functions
client(config)
Create a new Aerospike client instance.
| Parameter | Description |
|---|---|
config | ClientConfig 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.
| Parameter | Description |
|---|---|
level | One 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.
| Parameter | Description |
|---|---|
port | TCP 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.
| Parameter | Description |
|---|---|
username | Optional username for authentication. |
password | Optional password for authentication. |
Returns: The connected client instance.
Raises ClusterError Failed to connect to any cluster node.
- Sync Client
- Async Client
client = aerospike_py.client(config).connect()
# With authentication
client = aerospike_py.client(config).connect("admin", "admin")
# Without authentication
client = await aerospike_py.AsyncClient(config).connect()
# With authentication
client = await aerospike_py.AsyncClient(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.
- Sync Client
- Async Client
if client.is_connected():
print("Connected")
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.
- Sync Client
- Async Client
client.close()
await client.close()
get_node_names()
Return the names of all nodes in the cluster.
Returns: A list of node name strings.
- Sync Client
- Async Client
nodes = client.get_node_names()
# ['BB9020011AC4202', 'BB9030011AC4202']
nodes = await client.get_node_names()
Info
info_all(command, policy=None)
Send an info command to all cluster nodes.
| Parameter | Description |
|---|---|
command | The info command string (e.g. "namespaces"). |
policy | Optional AdminPolicy dict. |
Returns: A list of InfoNodeResult(node_name, error_code, response) tuples.
- Sync Client
- Async Client
results = client.info_all("namespaces")
for node, err, response in results:
print(f"{node}: {response}")
results = await 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.
| Parameter | Description |
|---|---|
command | The info command string. |
policy | Optional AdminPolicy dict. |
Returns: The info response string.
- Sync Client
- Async Client
response = client.info_random_node("build")
response = await client.info_random_node("build")
CRUD Operations
put(key, bins, meta=None, policy=None)
Write a record to the Aerospike cluster.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bins | Dictionary of bin name-value pairs to write. |
meta | Optional WriteMeta dict (e.g. {"ttl": 300}). |
policy | Optional WritePolicy dict. |
Raises RecordExistsError Record already exists (with CREATE_ONLY policy).
Raises RecordTooBig Record size exceeds the configured write-block-size.
- Sync Client
- Async Client
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},
)
key = ("test", "demo", "user1")
await client.put(key, {"name": "Alice", "age": 30})
# With TTL (seconds)
await client.put(key, {"score": 100}, meta={"ttl": 300})
get(key, policy=None)
Read a record from the cluster.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
policy | Optional ReadPolicy dict. |
Returns: A Record NamedTuple with key, meta, bins fields.
Raises RecordNotFound The record does not exist.
- Sync Client
- Async Client
record = client.get(("test", "demo", "user1"))
print(record.bins) # {"name": "Alice", "age": 30}
record = await client.get(("test", "demo", "user1"))
print(record.bins) # {"name": "Alice", "age": 30}
select(key, bins, policy=None)
Read specific bins from a record.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bins | List of bin names to retrieve. |
policy | Optional ReadPolicy dict. |
Returns: A Record NamedTuple with key, meta, bins fields.
Raises RecordNotFound The record does not exist.
- Sync Client
- Async Client
record = client.select(("test", "demo", "user1"), ["name"])
# record.bins = {"name": "Alice"}
record = await client.select(("test", "demo", "user1"), ["name"])
# record.bins = {"name": "Alice"}
exists(key, policy=None)
Check whether a record exists.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
policy | Optional ReadPolicy dict. |
Returns: An ExistsResult NamedTuple with key, meta fields.
meta is None if the record does not exist.
- Sync Client
- Async Client
result = client.exists(("test", "demo", "user1"))
if result.meta is not None:
print(f"Found, gen={result.meta.gen}")
result = await 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.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
meta | Optional WriteMeta dict for generation check. |
policy | Optional WritePolicy dict. |
Raises RecordNotFound The record does not exist.
- Sync Client
- Async Client
client.remove(("test", "demo", "user1"))
# With generation check
import aerospike_py
client.remove(
key,
meta={"gen": 3},
policy={"gen": aerospike_py.POLICY_GEN_EQ},
)
await client.remove(("test", "demo", "user1"))
touch(key, val=0, meta=None, policy=None)
Reset the TTL of a record.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
val | New TTL value in seconds. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
Raises RecordNotFound The record does not exist.
- Sync Client
- Async Client
client.touch(("test", "demo", "user1"), val=300)
await 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.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bin | Target bin name. |
val | String value to append. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
- Sync Client
- Async Client
client.append(("test", "demo", "user1"), "name", "_suffix")
await client.append(("test", "demo", "user1"), "name", "_suffix")
prepend(key, bin, val, meta=None, policy=None)
Prepend a string to a bin value.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bin | Target bin name. |
val | String value to prepend. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
- Sync Client
- Async Client
client.prepend(("test", "demo", "user1"), "name", "prefix_")
await client.prepend(("test", "demo", "user1"), "name", "prefix_")
increment(key, bin, offset, meta=None, policy=None)
Increment a numeric bin value.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bin | Target bin name. |
offset | Integer or float amount to add (use negative to decrement). |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
- Sync Client
- Async Client
client.increment(("test", "demo", "user1"), "age", 1)
client.increment(("test", "demo", "user1"), "score", 0.5)
await client.increment(("test", "demo", "user1"), "age", 1)
await 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.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
bin_names | List of bin names to remove. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
- Sync Client
- Async Client
client.remove_bin(("test", "demo", "user1"), ["temp_bin", "debug_bin"])
await client.remove_bin(("test", "demo", "user1"), ["temp_bin"])
Multi-Operation
operate(key, ops, meta=None, policy=None)
Execute multiple operations atomically on a single record.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
ops | List of operation dicts with "op", "bin", "val" keys. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
Returns: A Record NamedTuple with key, meta, bins fields.
- Sync Client
- Async Client
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)
import aerospike_py
ops = [
{"op": aerospike_py.OPERATOR_INCR, "bin": "counter", "val": 1},
{"op": aerospike_py.OPERATOR_READ, "bin": "counter", "val": None},
]
record = await 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.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
ops | List of operation dicts with "op", "bin", "val" keys. |
meta | Optional WriteMeta dict. |
policy | Optional WritePolicy dict. |
Returns: An OperateOrderedResult NamedTuple with key, meta,
ordered_bins fields.
- Sync Client
- Async Client
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)]
import aerospike_py
ops = [
{"op": aerospike_py.OPERATOR_INCR, "bin": "counter", "val": 1},
{"op": aerospike_py.OPERATOR_READ, "bin": "counter", "val": None},
]
result = await 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.
| Parameter | Description |
|---|---|
keys | List of (namespace, set, primary_key) tuples. |
bins | Optional list of bin names to read. None reads all bins; an empty list performs an existence check only. |
policy | Optional BatchPolicy dict. |
_dtype | Optional NumPy dtype. When provided, returns NumpyBatchRecords instead of BatchRecords. |
Returns: BatchRecords (or NumpyBatchRecords when _dtype is set).
- Sync Client
- Async Client
keys = [("test", "demo", f"user_{i}") for i in range(10)]
batch = client.batch_read(keys)
for br in batch.batch_records:
if br.record:
print(br.record.bins)
# Read specific bins
batch = client.batch_read(keys, bins=["name", "age"])
keys = [("test", "demo", f"user_{i}") for i in range(10)]
batch = await client.batch_read(keys, bins=["name", "age"])
for br in batch.batch_records:
if br.record:
print(br.record.bins)
batch_operate(keys, ops, policy=None)
Execute operations on multiple records in a single batch call.
| Parameter | Description |
|---|---|
keys | List of (namespace, set, primary_key) tuples. |
ops | List of operation dicts to apply to each record. |
policy | Optional BatchPolicy dict. |
Returns: A list of Record NamedTuples.
- Sync Client
- Async Client
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)
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 = await client.batch_operate(keys, ops)
batch_remove(keys, policy=None)
Delete multiple records in a single batch call.
| Parameter | Description |
|---|---|
keys | List of (namespace, set, primary_key) tuples. |
policy | Optional BatchPolicy dict. |
Returns: A list of Record NamedTuples.
- Sync Client
- Async Client
keys = [("test", "demo", f"user_{i}") for i in range(10)]
results = client.batch_remove(keys)
keys = [("test", "demo", f"user_{i}") for i in range(10)]
results = await client.batch_remove(keys)
Query & Scan
query(namespace, set_name)
Create a Query object for secondary index queries.
| Parameter | Description |
|---|---|
namespace | The namespace to query. |
set_name | The set to query. |
Returns: A Query object. Use where() to set a predicate filter
and results() or foreach() to execute.
- Sync Client
- Async Client
query = client.query("test", "demo")
query.select("name", "age")
query.where(predicates.between("age", 20, 30))
records = query.results()
query = client.query("test", "demo")
query.where(predicates.between("age", 20, 30))
records = await query.results()
Index Management
index_integer_create(namespace, set_name, bin_name, index_name, policy=None)
Create a numeric secondary index.
| Parameter | Description |
|---|---|
namespace | Target namespace. |
set_name | Target set. |
bin_name | Bin to index. |
index_name | Name for the new index. |
policy | Optional AdminPolicy dict. |
Raises IndexFoundError An index with that name already exists.
- Sync Client
- Async Client
client.index_integer_create("test", "demo", "age", "age_idx")
await 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.
| Parameter | Description |
|---|---|
namespace | Target namespace. |
set_name | Target set. |
bin_name | Bin to index. |
index_name | Name for the new index. |
policy | Optional AdminPolicy dict. |
Raises IndexFoundError An index with that name already exists.
- Sync Client
- Async Client
client.index_string_create("test", "demo", "name", "name_idx")
await 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.
| Parameter | Description |
|---|---|
namespace | Target namespace. |
set_name | Target set. |
bin_name | Bin to index (must contain GeoJSON values). |
index_name | Name for the new index. |
policy | Optional AdminPolicy dict. |
Raises IndexFoundError An index with that name already exists.
- Sync Client
- Async Client
client.index_geo2dsphere_create("test", "demo", "location", "geo_idx")
await client.index_geo2dsphere_create(
"test", "demo", "location", "geo_idx"
)
index_remove(namespace, index_name, policy=None)
Remove a secondary index.
| Parameter | Description |
|---|---|
namespace | Target namespace. |
index_name | Name of the index to remove. |
policy | Optional AdminPolicy dict. |
Raises IndexNotFound The index does not exist.
- Sync Client
- Async Client
client.index_remove("test", "age_idx")
await client.index_remove("test", "age_idx")
Truncate
truncate(namespace, set_name, nanos=0, policy=None)
Remove all records in a namespace/set.
| Parameter | Description |
|---|---|
namespace | Target namespace. |
set_name | Target set. |
nanos | Optional last-update cutoff in nanoseconds. |
policy | Optional AdminPolicy dict. |
- Sync Client
- Async Client
client.truncate("test", "demo")
await client.truncate("test", "demo")
UDF
udf_put(filename, udf_type=0, policy=None)
Register a Lua UDF module on the cluster.
| Parameter | Description |
|---|---|
filename | Path to the Lua source file. |
udf_type | UDF language type (only Lua 0 is supported). |
policy | Optional AdminPolicy dict. |
- Sync Client
- Async Client
client.udf_put("my_udf.lua")
await client.udf_put("my_udf.lua")
udf_remove(module, policy=None)
Remove a registered UDF module.
| Parameter | Description |
|---|---|
module | Module name to remove (without .lua extension). |
policy | Optional AdminPolicy dict. |
- Sync Client
- Async Client
client.udf_remove("my_udf")
await client.udf_remove("my_udf")
apply(key, module, function, args=None, policy=None)
Execute a UDF on a single record.
| Parameter | Description |
|---|---|
key | Record key as (namespace, set, primary_key) tuple. |
module | Name of the registered UDF module. |
function | Name of the function within the module. |
args | Optional list of arguments to pass to the function. |
policy | Optional WritePolicy dict. |
Returns: The return value of the UDF function.
- Sync Client
- Async Client
result = client.apply(
("test", "demo", "key1"),
"my_udf",
"my_function",
[1, "hello"],
)
result = await 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.
| Parameter | Description |
|---|---|
predicate | A 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.
| Parameter | Description |
|---|---|
policy | Optional 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.
| Parameter | Description |
|---|---|
callback | Function called with each record. Return False to stop. |
policy | Optional QueryPolicy dict. |
def process(record):
print(record.bins)
query.foreach(process)