Session

class aerospike_sdk.aio.session.Session[source]

Bases: object

Perform reads and writes against Aerospike with a fixed Behavior.

A session binds a connected Client to policy defaults (timeouts, retries, replica preferences) for every operation started from it. Create sessions with Client.create_session(); do not construct Session directly.

Example

async with Client(“localhost:3000”) as client:

session = client.create_session(Behavior.DEFAULT) users = DataSet.of(“test”, “users”) stream = await session.query(users.id(1)).execute() first = await stream.first_or_raise() await session.upsert(users.id(2)).put({“name”: “Tim”}).execute()

See also

Client.create_session(): How to obtain a session. query(): Point reads, batch reads, and secondary-index queries. upsert(): Create-or-update writes.

__init__(client, behavior)[source]

Attach a client and behavior; prefer Client.create_session().

Parameters:
  • client (Client) – Connected (or not yet connected) Client.

  • behavior (Behavior) – Policy bundle for operations from this session.

Note

Application code should not call Session(...) directly.

See also

Client.create_session().

get_current_transaction()[source]

Return the active transaction for this session, or None.

Regular Session instances always return None; only TransactionalSession inside its async with block returns a live Txn. Builders created from this session call this hook at construction and thread the result through every policy they hand to the PAC.

Return type:

Optional[Txn]

Returns:

The active Txn, or None outside a transaction.

Example

>>> session = client.create_session()
>>> session.get_current_transaction() is None
True
>>> async with session.begin_transaction() as tx:
...     assert tx.get_current_transaction() is tx.txn

See also

begin_transaction(): Enter a multi-record transaction. TransactionalSession

async get(key, bins=None)[source]

Direct single-key point read — returns Record or raises.

Bypasses the builder chain (session.query(key).execute()) and the RecordStream wrapper: one await reaches the underlying client and the resulting Record is returned unwrapped. Use when you have a single key and want minimum per-op overhead; use query() when you need filters, projections, or streaming.

Parameters:
  • key (Key) – Target Key.

  • bins (Optional[List[str]]) – Optional bin-name projection. None (default) reads all bins.

Return type:

Record

Returns:

The Record for key.

Raises:

AerospikeError – Server or client errors (including KEY_NOT_FOUND_ERROR) are raised from the underlying client without being wrapped in a RecordResult.

Example

>>> users = DataSet.of("test", "users")
>>> rec = await session.get(users.id(1))
>>> name = rec.bins["name"]

See also

query(): Builder-based reads for projections, streams, and secondary-index queries. put(): Direct single-key upsert.

async put(key, bins)[source]

Direct single-key upsert — returns None or raises.

Bypasses the builder chain (session.upsert(key).put(...).execute()) and the RecordStream wrapper: one await reaches the underlying client. Use when you have a single key and want minimum per-op overhead; use upsert() when you need atomic multi-op semantics, TTL overrides, generation checks, durable delete, or filter expressions.

Parameters:
  • key (Key) – Target Key.

  • bins (Dict[str, Any]) – Mapping of bin name to value to write. An empty mapping is permitted.

Return type:

None

Returns:

None on success.

Raises:

AerospikeError – Server or client errors are raised from the underlying client.

Example

>>> users = DataSet.of("test", "users")
>>> await session.put(users.id(1), {"name": "Tim", "age": 30})

See also

upsert(): Builder-based writes with full feature set. get(): Direct single-key point read.

property behavior: Behavior

Policy bundle applied to operations created from this session.

Returns:

The Behavior passed to Client.create_session().

property client: Client

SDK client that owns the connection used by this session.

Returns:

The parent Client.

batch()[source]

Start a multi-key batch of mixed write operations executed in one server round trip.

Chain insert, update, upsert, replace, delete, and related bin builders, then await ...execute() to obtain per-key outcomes.

Return type:

BatchOperationBuilder

Returns:

A BatchOperationBuilder for chaining operations.

Raises:

RuntimeError – If the client is not connected.

Example:

results = await (
    session.batch()
    .insert(key1).put({"name": "Alice", "age": 25})
    .update(key2).bin("counter").add(1)
    .upsert(key3).put({"status": "active"})
    .delete(key4)
    .execute()
)
for row in results:
    print(row.key, row.result_code)

See also

upsert(): Single-record writes without batching.

background_task()[source]

Configure a server-side background job (query + scan scope) on a dataset.

Call update, delete, touch, or execute_udf on the returned object, add optional filters (for example where on supported builders), then await ...execute() to start work and receive an async task handle.

Return type:

BackgroundTaskSession

Returns:

A BackgroundTaskSession for chaining the operation type and execution.

Raises:

RuntimeError – If the client is not connected.

Example:

task = await (
    session.background_task()
    .delete(DataSet.of("test", "scratch"))
    .where("$.flag == 1")
    .execute()
)
await task.wait_till_complete(sleep_time=0.2, max_attempts=50)

See also

execute_udf(): Foreground UDF on explicit keys.

execute_udf(*keys)[source]

Run a registered server-side UDF on one or more keys (foreground).

Chain function(package, name) (package is the registered module name without .lua), optional passing(*args) for Lua parameters, optional where for a filter expression, then await ...execute() to obtain a RecordStream. Multiple keys use a batch UDF; results preserve per-key order where applicable.

Parameters:

*keys (Key) – One or more Key targets in the same namespace and set.

Return type:

UdfFunctionBuilder

Returns:

UdfFunctionBuilder — call function next.

Raises:

Example:

users = DataSet.of("test", "users")
stream = await (
    session.execute_udf(users.id("a"))
    .function("my_module", "my_fn")
    .passing("binName", 42)
    .execute()
)
value = await stream.first_udf_result()

See also

query(): Read bins without UDF. background_task(): Dataset-scoped background UDF.

query(arg1=None, arg2=None, *keys, namespace=None, set_name=None, dataset=None, key=None, keys_list=None, behavior=None)[source]
Overloads:
  • self, dataset (DataSet), behavior (Optional[Behavior]) → QueryBuilder

  • self, key (Key), behavior (Optional[Behavior]) → QueryBuilder

  • self, keys (List[Key]), behavior (Optional[Behavior]) → QueryBuilder

  • self, keys (Key), behavior (Optional[Behavior]) → QueryBuilder

  • self, namespace (str), set_name (str), behavior (Optional[Behavior]) → QueryBuilder

Start a read or secondary-index query for keys or a whole set.

This session’s behavior is applied to the underlying QueryBuilder. Supported shapes include a DataSet (set-wide query), a single Key, multiple keys (list or varargs), or explicit namespace / set_name for index scans.

Parameters:
  • arg1 (Union[DataSet, Key, List[Key], str, None]) – Positional dataset, key, list of keys, or namespace string (when paired with arg2 as set name).

  • arg2 (Union[str, Key, None]) – When arg1 is a namespace, the set name; otherwise may be a second key when passing multiple keys positionally.

  • *keys (Key) – Additional keys when the first positional argument is a key.

  • namespace (Optional[str]) – Keyword namespace (with set_name) when not using a dataset.

  • set_name (Optional[str]) – Keyword set name (with namespace).

  • dataset (Optional[DataSet]) – Keyword DataSet.

  • key (Optional[Key]) – Keyword single key.

  • keys_list (Optional[List[Key]]) – Keyword list of keys when not using arg1 or varargs; forwarded to the client as keys.

  • behavior (Optional[Behavior]) – Optional override for this query; defaults to the session’s behavior.

Returns:

A QueryBuilder to chain where, bins, execute, etc.

Raises:
  • TypeError – If positional types do not match the supported overloads.

  • ValueError – If a key list is empty or arguments are inconsistent.

Example

users = DataSet.of(“test”, “users”) rs = await session.query(users.id(1)).bins([“name”]).execute() row = await rs.first_or_raise()

Example

users = DataSet.of(“test”, “users”) rs = await session.query(users.ids(1, 2, 3)).bins([“name”]).execute() rows = await rs.collect()

See also

Client.query(): Same shapes without session behavior. upsert(): Writes for the same keys.

index(namespace=None, set_name=None, *, dataset=None, behavior=None)[source]
Overloads:
  • self, dataset (DataSet), behavior (Optional[Behavior]) → IndexBuilder

  • self, namespace (str), set_name (str), behavior (Optional[Behavior]) → IndexBuilder

Create a secondary index builder for a namespace and set.

Parameters:
  • namespace (Optional[str]) – Namespace name when not using dataset.

  • set_name (Optional[str]) – Set name when not using dataset.

  • dataset (Optional[DataSet]) – Optional DataSet that supplies namespace and set.

  • behavior (Optional[Behavior]) – Reserved for symmetry with query(); forwarded to Client.index() but not used by index operations yet.

Returns:

IndexBuilder for

chaining index definition and creation.

Raises:

ValueError – If dataset is not given and namespace or set_name is missing.

Example:

users = DataSet.of("test", "users")
await session.index(dataset=users).on_bin("age").named("age_idx").numeric().create()

See also

Client.index()

transaction_session()[source]

Create a transactional session using this session’s behavior.

Alias for begin_transaction().

Return type:

TransactionalSession

Returns:

TransactionalSession bound to this session’s client and behavior.

begin_transaction()[source]

Start a multi-record transaction (MRT) using this session’s behavior.

Returns an async context manager that allocates a fresh Txn. Every operation run on the returned session auto-participates in the transaction — builders stamp policy.txn = tx.txn under the hood, so user code never touches a policy object. On clean exit the transaction is committed; if an exception propagates out of the async with block the transaction is aborted.

Example

>>> async with session.begin_transaction() as tx:
...     await tx.upsert(accounts.id("A")).bin("balance").set_to(100).execute()
...     await tx.upsert(accounts.id("B")).bin("balance").set_to(200).execute()
Return type:

TransactionalSession

Returns:

TransactionalSession bound to this session’s client and behavior.

See also

transaction_session(): Alias for this method. do_in_transaction(): Run a callable inside a retrying MRT.

info(command=None)[source]
Overloads:
  • selfInfoCommands

  • self, command (str) → Awaitable[Dict[str, str]]

Execute info commands or get the InfoCommands helper.

With no argument, returns an InfoCommands instance for high-level helpers (namespaces(), namespace_details(), etc.) and for info_on_all_nodes().

With a command string, runs the raw info command and returns its result (awaitable).

Parameters:

command (Optional[str]) – Optional. If given, the raw info command to run (e.g. “sindex-list”, “build”).

Returns:

InfoCommands instance. If command is given: awaitable dict (node -> response).

Return type:

If command is None

Example:

# Raw command (no double .info)
response = await session.info("sindex-list")

# High-level helpers
info = session.info()
namespaces = await info.namespaces()
by_node = await info.info_on_all_nodes("build")
async is_namespace_sc(namespace)[source]

Check if a namespace is in strong consistency (SC) mode.

Strong consistency mode provides linearizable reads and writes at the cost of availability during network partitions.

Parameters:

namespace (str) – The namespace name to check.

Return type:

bool

Returns:

True if the namespace is in strong consistency mode, False otherwise.

Raises:

ValueError – If the namespace is unknown or the info command fails.

Example:

if await session.is_namespace_sc("test"):
    print("Namespace 'test' is in strong consistency mode")
else:
    print("Namespace 'test' is in AP (availability) mode")
async do_in_transaction(operation, *, max_attempts=5, sleep_between_retries=0.0)[source]

Run an async callable inside a retrying multi-record transaction.

Creates a TransactionalSession, invokes operation(tx) inside async with, and retries the whole block when the server signals a transient conflict (MRT_BLOCKED, MRT_VERSION_MISMATCH, or TXN_FAILED). On any non-transient failure the transaction is aborted and the exception re-raised.

Parameters:
  • operation (Callable[[TransactionalSession], Awaitable[Any]]) – Async callable accepting a TransactionalSession and performing zero or more operations on it. Its return value is returned from do_in_transaction().

  • max_attempts (int) – Maximum total attempts (initial + retries). Must be >= 1. Defaults to 5.

  • sleep_between_retries (float) – Optional seconds to await asyncio.sleep between retries. 0 (the default) retries immediately.

Return type:

Any

Returns:

Whatever operation returns on the successful attempt.

Raises:
  • ValueError – If max_attempts < 1.

  • AerospikeError – The last-seen transient error after max_attempts exhausted retries, or any non-transient error raised by operation.

Example

>>> async def transfer(tx):
...     await tx.upsert(accounts.id("A")).bin("bal").add(-10).execute()
...     await tx.upsert(accounts.id("B")).bin("bal").add(10).execute()
...     return "ok"
>>> result = await session.do_in_transaction(transfer)

See also

begin_transaction(): Manual MRT lifecycle. TransactionalSession

upsert(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a create-or-replace write for one or more keys.

If the record exists, bins are merged according to the chained operations; if it does not exist, it is created. Use insert() when the record must not already exist.

Parameters:
  • arg1 (Union[Key, List[Key], None]) – A single Key, a list of keys, or omit and pass key / dataset + key_value / namespace + set_name + key_value.

  • arg2 (Optional[Key]) – Optional second key when passing multiple keys positionally.

  • *keys (Key) – Additional keys when the first positional is a key.

  • key (Optional[Key]) – Single key (keyword form).

  • dataset (Optional[DataSet]) – Dataset used with key_value to build a key.

  • namespace (Optional[str]) – Namespace used with set_name and key_value.

  • set_name (Optional[str]) – Set name used with namespace and key_value.

  • key_value (Union[str, int, bytes, None]) – User key value with dataset or namespace/set_name.

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder for put, bin, where, execute, etc.

Raises:
  • ValueError – If no keys are resolved or lists are empty.

  • TypeError – If positional arguments are not keys or lists of keys.

Example

users = DataSet.of(“test”, “users”) await session.upsert(users.id(1)).put({“name”: “Tim”, “age”: 30}).execute()

See also

insert(): Fails if the record already exists. update(): Fails if the record does not exist. replace(): Replace-entire-record semantics when configured.

insert(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a create-only write; fails on execute if the record already exists.

Key resolution matches upsert().

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

Example

users = DataSet.of(“test”, “users”) await session.insert(users.id(99)).put({“name”: “new”}).execute()

See also

upsert(): Create or update.

update(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start an update-only write; fails on execute if the record is missing.

Key resolution matches upsert().

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

See also

upsert(): Create if missing. replace_if_exists(): Replace semantics when the record exists.

replace(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a full-record replace write (bins replaced per builder rules).

Key resolution matches upsert(). Prefer replace_if_exists() when the record must already exist.

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

See also

replace_if_exists(): Replace only when the record exists.

replace_if_exists(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a replace write that requires an existing record.

Key resolution matches upsert(). On execute, missing keys surface as errors according to error strategy (default may raise).

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

See also

replace(): Unconditional replace semantics.

delete(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a delete for one or more keys.

Key resolution matches upsert(). Chain filters or durable-delete options on the builder, then await ...execute().

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

Example

users = DataSet.of(“test”, “users”) await session.delete(users.id(1)).execute() await session.delete(users.ids(10, 11)).execute()

See also

background_task(): Delete many records via a server job.

touch(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start a touch to refresh TTL without changing bins.

Key resolution matches upsert(). Use the builder to set TTL or related policy, then await ...execute().

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

See also

upsert(): Writes that can also set expiration via the builder.

exists(arg1=None, arg2=None, *keys, key=None, dataset=None, namespace=None, set_name=None, key_value=None)[source]

Start an existence check for one or more keys.

Key resolution matches upsert(). After execute, use as_bool() on each RecordResult or inspect result_code.

Return type:

WriteSegmentBuilder

Returns:

A WriteSegmentBuilder.

Raises:

Example

users = DataSet.of(“test”, “users”) rs = await session.exists(users.id(1)).execute() exists = (await rs.first()).as_bool()

See also

query(): Read record data when the key is known to exist.

async truncate(dataset, before_nanos=None)[source]

Truncate (delete all records) from a set; this cannot be undone.

Parameters:
  • dataset (DataSet) – The DataSet to truncate.

  • before_nanos (Optional[int]) – Optional timestamp in nanoseconds. Only records with last update time (LUT) less than this value are truncated. If None, all records in the set are truncated.

Return type:

None

Returns:

None

Raises:

RuntimeError – If the client is not connected.

Example:

users = DataSet.of("test", "users")
await session.truncate(users)

cutoff_time = time.time_ns() - (24 * 60 * 60 * 10**9)  # 24 hours ago
await session.truncate(users, before_nanos=cutoff_time)