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:
- 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
Recordor raises.Bypasses the builder chain (
session.query(key).execute()) and theRecordStreamwrapper: one blocking call reaches the underlying client and the resultingRecordis 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:
- Return type:
Record- Returns:
The
Recordforkey.- 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 aRecordResult.
Example:
users = DataSet.of("test", "users") rec = session.get(users.id(1)) name = rec.bins["name"]
- 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:
- truncate(dataset, before_nanos=None)[source]¶
Truncate a set, synchronously (PNC
truncate_blocking).Warning
A
datasetwith no set truncates the entire namespace. Seetruncate().- Return type:
- namespace_sc_status(namespace)[source]¶
Describe whether a namespace is SC; includes a reason when it is not.
- Return type:
NamespaceScStatus
- info(command=None)[source]¶
Sync info: return
InfoCommandsor raw blocking result.- Overloads:
self → InfoCommands
self, command (str) → Dict[str, str]
- 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; callwait_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➜Sessionpath is self-sufficient.- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- 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:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- 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:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
RegisterTask
- remove_udf(server_path, *, policy=None)[source]¶
Remove a UDF module from the cluster (synchronous).
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
UdfRemoveTask
- list_udf()[source]¶
List the UDF modules registered on the cluster (synchronous).
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- list_indexes()[source]¶
List the secondary indexes defined on the cluster (synchronous).
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- 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 aTransactionalSession.max_attempts (
Optional[int]) – Maximum total attempts (initial + retries). Must be>= 1. Omit to use the cluster’sTransactionSettings.sleep_between_retries (
Union[float,timedelta,None]) – How long to wait before retrying a blocked record or failed commit, as seconds or adatetime.timedelta; each wait is jittered +/- 50%. A version mismatch always retries immediately. Omit to use the cluster’s transaction settings; pass0to never wait.
- Return type:
- Returns:
Whatever
operationreturns on the successful attempt.- Raises:
ValueError – If
max_attemptsis 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
Behaviorbound 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 liveTxn. 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, orNoneoutside 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, readingFalsewhen the record is absent; a batch omits absent keys unlessinclude_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: aDataSet(set-wide query), a singleKey, 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:
- Return type:
TypeVar(_QB, bound= _QueryBuilderBase)- Returns:
A query builder to chain
where,bins,execute, etc. The terminalexecute()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()
- 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 stamppolicy.txnunder 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
behavioris 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:
- 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()