Session (sync)

class aerospike_sdk.sync.session.Session[source]

Bases: SessionBase[WriteSegmentBuilder, QueryBuilder, TransactionalSession, DataSetWriteBuilder]

Run session-scoped reads and writes without async/await.

Construct via Cluster.create_session, not directly.

See also

Session: Async equivalent.

__init__(client, behavior)[source]

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

session_for(behavior)[source]

A new session on the same cluster with a different behavior.

Shorthand for cluster.create_session(behavior); this session is left as it is. Called on a transactional session it returns a plain session, outside the transaction.

Parameters:

behavior (Behavior) – The behavior for the new session.

Return type:

Session

Returns:

A new Session.

Example:

reads = session.session_for(Behavior.READ_FAST)
row = reads.query(key).execute().first_or_raise()
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 blocking call reaches the underlying client and the resulting Record is returned unwrapped. Passes the AP + SC cached policies; PNC picks the right one based on the key’s namespace mode (from the in-memory partition map).

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 as the SDK exception type for the failure, without being wrapped in a RecordResult.

Example:

users = DataSet.of("test", "users")
rec = 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.

put(key, bins)[source]

Direct single-key upsert — no builder, no stream — synchronous.

Passes the AP + SC cached policies; PNC picks the right one based on the key’s namespace mode.

Raises:

AerospikeError – Server or client errors are raised as the SDK exception type for the failure.

Return type:

None

truncate(dataset, before_nanos=None)[source]

Truncate a set, synchronously (PNC truncate_blocking).

Warning

A dataset with no set truncates the entire namespace. See truncate().

Return type:

None

namespace_sc_status(namespace)[source]

Describe whether a namespace is SC; includes a reason when it is not.

Return type:

NamespaceScStatus

is_namespace_sc(namespace)[source]

True if namespace is in strong-consistency mode.

Return type:

bool

info(command=None)[source]

Sync info: return InfoCommands or raw blocking result.

Overloads:
  • self → InfoCommands

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

background_task()[source]

Start a background dataset task chain (synchronous).

Return type:

BackgroundTaskSession

execute_udf(*keys)[source]

Begin a foreground UDF invocation (synchronous).

Return type:

UdfFunctionBuilder

index(dataset, /)[source]

Synchronous secondary-index builder for a dataset.

Return type:

IndexBuilder

create_index(dataset, index_name, bin_name=None, index_type=None, collection_type=None, ctx=None, expression=None)[source]

Create a secondary index in one call (synchronous).

Same arguments and rules as the async verb; a dataset and a name alone create a set index.

Return type:

IndexTask

Returns:

An IndexTask; call wait_till_complete_blocking() before querying through the index.

drop_index(dataset, index_name)[source]

Drop a secondary index by name (synchronous).

Return type:

DropIndexTask

register_udf(body, server_path, language=UDFLang.LUA, *, policy=None)[source]

Register a UDF module from bytes (synchronous).

Exposed here so the ClusterDefinition ➜ Cluster ➜ Session path is self-sufficient.

Raises:
Return type:

RegisterTask

register_udf_from_file(client_path, server_path, language=UDFLang.LUA, *, policy=None)[source]

Register a UDF module from a local file (synchronous).

Raises:
Return type:

RegisterTask

register_udf_from_resource(package, resource, server_path, language=UDFLang.LUA, *, policy=None)[source]

Register a UDF from a Python package resource (synchronous).

Raises:
Return type:

RegisterTask

remove_udf(server_path, *, policy=None)[source]

Remove a UDF module from the cluster (synchronous).

Raises:
Return type:

UdfRemoveTask

list_udf()[source]

List the UDF modules registered on the cluster (synchronous).

Raises:
Return type:

list[dict[str, str]]

list_indexes()[source]

List the secondary indexes defined on the cluster (synchronous).

Raises:
Return type:

list[dict[str, str]]

do_in_transaction(operation, *, max_attempts=None, sleep_between_retries=None)[source]

Run a callable inside a retrying multi-record transaction (synchronous).

Parameters:
  • operation (Callable[[TransactionalSession], Any]) – Callable accepting a TransactionalSession.

  • max_attempts (Optional[int]) – Maximum total attempts (initial + retries). Must be >= 1. Omit to use the cluster’s TransactionSettings.

  • sleep_between_retries (Union[float, timedelta, None]) – How long to wait before retrying a blocked record or failed commit, as seconds or a datetime.timedelta; each wait is jittered +/- 50%. A version mismatch always retries immediately. Omit to use the cluster’s transaction settings; pass 0 to never wait.

Return type:

Any

Returns:

Whatever operation returns on the successful attempt.

Raises:
  • ValueError – If max_attempts is given and is less than 1.

  • CommitError – The commit’s roll-forward was abandoned (not retried: the server will eventually commit those writes).

  • AerospikeError – The last-seen transient error after retries are exhausted, or any non-transient error from operation.

Example:

def transfer(tx):
    tx.upsert(src).put({"balance": 90}).execute()
    tx.upsert(dst).put({"balance": 110}).execute()

session.do_in_transaction(transfer)

See also

aerospike_sdk.sync.transactional_session.TransactionalSession.do_in_transaction():

Nested calls join the transaction already in progress.

property behavior: Behavior

Policy bundle applied to operations created from this session.

Returns:

The Behavior bound to this session at creation.

Example:

session = client.create_session(Behavior.DEFAULT)
assert session.behavior is Behavior.DEFAULT

See also

current_transaction: The session’s active transaction, if any.

property current_transaction: Txn | None

The active transaction for this session, or None.

Regular sessions always hold None; only a transactional session inside its active block exposes a live Txn. Builders spawned from the session read this and thread the result through every policy they hand to the PNC, so operations started inside a transaction auto-participate.

Returns:

The active Txn, or None outside a transaction.

Example:

session = client.create_session()
assert session.current_transaction is None

See also

behavior: The session’s policy bundle.

delete(arg1, /, *keys)

Start a delete for one or more keys.

Key resolution matches upsert().

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
session.delete(users.id(1)).execute()

See also

upsert(): Create or update the same keys.

exists(arg1, /, *keys)

Start an existence check for one or more keys.

Key resolution matches upsert(). A single key always yields one row, reading False when the record is absent; a batch omits absent keys unless include_missing_keys() is set on the builder.

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

A write-segment builder whose result reports presence per key.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
present = session.exists(users.id(1)).execute().first().as_bool()

See also

query(): Fetch the record instead of just presence.

insert(arg1, /, *keys)

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

Overloads:
  • self, arg1 (DataSet) → _DSWB

  • self, arg1 (Union[Key, List[Key]]), keys (Key) → _WSB

Key resolution matches upsert().

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

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

See also

upsert(): Create or update.

query(arg1, /, *keys)

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

This session’s behavior is applied to the underlying query builder; use session_for() to run a query under a different one. Supported shapes: a DataSet (set-wide query), a single Key, or multiple keys (varargs or a list). Multi-key queries are split into per-node sub-batches, and a node whose sub-batch holds a single key is sent a regular single-record command automatically — size-1 batches need no special-casing by the caller.

Parameters:
  • arg1 (Union[DataSet, Key, List[Key]]) – A dataset, a key, or a list of keys.

  • *keys (Key) – Additional keys when arg1 is a key.

Return type:

TypeVar(_QB, bound= _QueryBuilderBase)

Returns:

A query builder to chain where, bins, execute, etc. The terminal execute() is awaited on async sessions and blocking on sync sessions.

Raises:
  • TypeError – If the arguments are not a dataset, keys, or a list of keys.

  • ValueError – If a key list is empty.

Example:

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

# A whole set, or a whole namespace with DataSet.of("test"):
rs = await session.query(users).where("$.age > 30").execute()

See also

upsert(): Writes for the same keys.

replace(arg1, /, *keys)

Start a replace-entire-record write (create or replace).

Overloads:
  • self, arg1 (DataSet) → _DSWB

  • self, arg1 (Union[Key, List[Key]]), keys (Key) → _WSB

Key resolution matches upsert().

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
session.replace(users.id(1)).put({"name": "Tim"}).execute()

See also

replace_if_exists(): Replace only when the record exists. upsert(): Merge instead of replace.

replace_if_exists(arg1, /, *keys)

Start a replace-entire-record write that fails if the record is absent.

Key resolution matches upsert().

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
session.replace_if_exists(users.id(1)).put({"name": "Tim"}).execute()

See also

replace(): Create or replace. update(): Merge only when the record exists.

touch(arg1, /, *keys)

Start a touch (bump generation / reset TTL) for one or more keys.

Key resolution matches upsert().

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
session.touch(users.id(1)).execute()

See also

update(): Modify bins as well as metadata.

transaction()

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

Returns a context manager that allocates a fresh Txn. Every operation run on the returned session auto-participates — builders stamp policy.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 block it is aborted.

Defined once here so this session’s behavior is always threaded into the transactional session — the two trees cannot re-drift into dropping it on one side.

Return type:

TypeVar(_TS)

Returns:

The tree’s transactional session (async or sync), bound to this session’s client and behavior.

Example:

async with session.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()

See also

current_transaction: The active transaction, if any.

update(arg1, /, *keys)

Start an update-only write; fails on execute if the record does not exist.

Overloads:
  • self, arg1 (DataSet) → _DSWB

  • self, arg1 (Union[Key, List[Key]]), keys (Key) → _WSB

Key resolution matches upsert().

Returns:

A write-segment builder.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys or a list of keys.

Example:

users = DataSet.of("test", "users")
session.update(users.id(1)).bin("age").set_to(31).execute()

See also

upsert(): Create or update. replace_if_exists(): Replace-entire-record only if present.

upsert(arg1, /, *keys)

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

Overloads:
  • self, arg1 (DataSet) → _DSWB

  • self, arg1 (Union[Key, List[Key]]), keys (Key) → _WSB

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[DataSet, Key, List[Key]]) – A single Key, a list of keys, or a DataSet for a tabular write (rows follow via bins(...)).

  • *keys (Key) – Additional keys when arg1 is a key.

Returns:

A write-segment builder for put, bin, where, execute, etc.

Raises:
  • ValueError – If a key list is empty.

  • TypeError – If the arguments are not keys, a list of keys, or a dataset.

Example:

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

# Several records with the same bins, as rows under a column schema:
session.upsert(users).bins("name", "age").row(1, "Tim", 30).row(2, "Bob", 25).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.