WriteSegmentBuilder

class aerospike_sdk.aio.operations.query.WriteSegmentBuilder[source]

Bases: _WriteSegmentBuilderBase[QueryBuilder], _WriteVerbs[WriteSegmentBuilder]

Accumulate scalar and CDT writes for the current operation’s key(s).

Obtained from QueryBuilder after a write verb or from WriteBinBuilder when chaining. Call put(), bin(), expression helpers, optional where() / TTL / generation guards, then execute() on this object or transition with query() / another write verb on the mixin.

Example:

Upsert two bins, then read the stream of results::

    stream = await (
        session.upsert(key)
            .put({"name": "Ada", "score": 100})
            .execute()
    )

See also

QueryBuilder.execute(): Runs all chained operations.

async execute(on_error=None)[source]

Run the parent QueryBuilder stack (same as self._qb.execute).

Parameters:

on_error (Union[ErrorStrategy, Callable[[Key, int, AerospikeError], None], None]) – Optional ErrorStrategy or error callback; see QueryBuilder.execute().

Return type:

RecordStream

Returns:

RecordStream of results.

Example::

stream = await session.upsert(key).put({“x”: 1}).execute() await stream.first_or_raise()

:raises Same as QueryBuilder.execute().:

async first(on_error=None)[source]

Execute and return the first row, or None when there are none.

The write-side twin of QueryBuilder.first(): one await for the common single-key outcome check instead of a stream plus a row. Semantics come from RecordStream.first(); the stream is closed either way.

Parameters:

on_error (Union[ErrorStrategy, Callable[[Key, int, AerospikeError], None], None]) – Per-operation error handling, as for execute().

Return type:

RecordResult | None

Returns:

The first RecordResult, or None when the operation produced no row.

Example:

exists = (await session.exists(key).first()).as_bool()

See also

first_or_raise(): Raises instead of returning None.

async first_or_raise(on_error=None)[source]

Execute and return the first row, requiring it to exist and be OK.

The write-side twin of QueryBuilder.first_or_raise(). Semantics come from RecordStream.first_or_raise().

Parameters:

on_error (Union[ErrorStrategy, Callable[[Key, int, AerospikeError], None], None]) – Per-operation error handling, as for execute().

Return type:

RecordResult

Returns:

The first successful RecordResult.

Raises:

Example:

row = await session.upsert(key).put({"count": 1}).first_or_raise()

See also

first(): Returns None on an empty result instead.

stream(on_error=None)[source]

Lazy streaming variant — see QueryBuilder.stream().

Return type:

AwaitableContext[RecordStream]

__init__(qb)
add(bin_name, value)

Add a numeric value to a bin.

Return type:

Self

add_operation(op)

Append an operation. Returns self so calls can chain.

Return type:

Self

append(bin_name, value)

Append a string to a bin.

Return type:

Self

bin(bin_name)

Start a bin-level write operation.

Parameters:

bin_name (str) – The bin to operate on.

Return type:

WriteBinBuilder

Returns:

A WriteBinBuilder for method chaining.

default_expire_record_after(duration)

Default TTL from a datetime.timedelta.

Return type:

Self

default_expire_record_after_seconds(seconds)

Default TTL, in seconds, for chained operations without their own.

Return type:

Self

default_expire_record_at(when)

Default TTL expressed as an absolute expiry instant.

Return type:

Self

default_expiry_from_server_default()

Default chained operations to the namespace’s configured TTL.

Return type:

Self

default_never_expire()

Default chained operations to never expire.

Return type:

Self

default_where(expression, *params)

Filter applied to chained operations that do not call where.

Return type:

Self

default_with_durable_delete()

Prefer durable deletes for this segment when resolving behavior defaults.

Return type:

Self

default_with_no_change_in_expiration()

Default chained operations to leave the existing TTL untouched.

Return type:

Self

default_without_durable_delete()

Prefer non-durable deletes for this segment when resolving behavior defaults.

Return type:

Self

delete(arg1, *more_keys)

Open a delete segment.

Example::

await session.delete(key).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder (often followed immediately by execute()).

delete_record()

Add a record-level delete to the current operate call.

Unlike delete() which targets a different key, this deletes the record being operated on as part of the same atomic operation.

Example:

stream = await (
    session.upsert(key)
        .bin("name").get()
        .delete_record()
        .execute()
)

See also

delete(): Start a new delete segment for a key.

Return type:

Self

ensure_generation_is(generation)

Set expected generation for optimistic locking on the current segment.

Parameters:

generation (int) – The expected generation number (must be > 0).

Return type:

Self

Returns:

self for method chaining.

Raises:

ValueError – If generation is <= 0.

execute_udf(*keys)

Finalize the current write segment and chain a UDF execution.

The write segment is packaged as-is; the returned builder targets the new key(s), and the whole chain still executes as one batch. Call function(package, name) next.

Parameters:

*keys (Key) – One or more keys for the UDF segment.

Return type:

UdfFunctionBuilder

Returns:

A UdfFunctionBuilder — call function next.

Raises:

ValueError – If no keys are provided.

Example:

rs = await (
    session.upsert(order_key).put({"status": "paid"})
    .execute_udf(stats_key)
    .function("order_stats", "record_payment")
    .execute()
)
exists(arg1, *more_keys)

Open an exists-check segment.

Example::

stream = await session.exists(key).execute() found = (await stream.first_or_raise()).as_bool()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

expire_record_after(duration)

Set the TTL using a datetime.timedelta.

Equivalent to expire_record_after_seconds() with seconds derived from duration — convenient when the caller already has a timedelta (timedelta(days=30), etc.). A timedelta resolving to -1, -2, or 0 seconds selects the corresponding TTL sentinel.

Parameters:

duration (timedelta) – Time-to-live.

Return type:

Self

Returns:

self for method chaining.

expire_record_after_seconds(seconds)

Set the TTL on the current operation.

Parameters:

seconds (int) – Time-to-live in seconds. A positive value sets an explicit TTL; the sentinels -1, -2, and 0 select never-expire, no-change, and namespace-default respectively (see never_expire(), with_no_change_in_expiration(), and expiry_from_server_default() for named equivalents). The value is not range-checked here — one the client cannot represent is rejected when the operation is built.

Return type:

Self

Returns:

self for method chaining.

expire_record_at(when)

Set the TTL so the record expires at an absolute point in time.

A naive when is interpreted in local time; pass a timezone-aware datetime for explicit UTC or other zones.

Parameters:

when (datetime) – Future point at which the record should expire.

Return type:

Self

Returns:

self for method chaining.

Raises:

ValueError – If when is not strictly in the future.

expiry_from_server_default()

Use the namespace’s default TTL for this record (TTL = 0).

Return type:

Self

fail_on_filtered_out()

Mark filtered-out records with FILTERED_OUT result code.

Return type:

Self

get(bin_name)

Read a bin value back within a write operate.

Return type:

Self

include_missing_keys()

Include results for missing keys in the stream.

Return type:

Self

insert(arg1, *more_keys)

Open a create-only segment (fails if the record exists).

Example::

await session.insert(key).put({“name”: “Ada”}).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder for further bins and execute().

insert_from(bin_name, expression, *, ignore_op_failure=False, ignore_eval_failure=False, delete_if_null=False)

Write expression result only if bin does not already exist.

Return type:

Self

never_expire()

Set this record to never expire (TTL = -1).

Return type:

Self

prepend(bin_name, value)

Prepend a string to a bin.

Return type:

Self

put(bins)

Apply Operation.put for each bin in the mapping.

Parameters:

bins (dict) – Map of bin name to value.

Return type:

Self

Example::

await session.upsert(key).put({“email”: “a@b.com”, “age”: 30}).execute()

See also

bin(): Per-bin CDT or scalar follow-ups.

query(arg1, *more_keys)

Finalize current write segment and start a read segment.

Parameters:
  • arg1 (Union[Key, List[Key]]) – A single Key or List[Key].

  • *more_keys (Key) – Additional keys (varargs).

Return type:

TypeVar(_QB, bound= _QueryBuilderBase)

Returns:

The parent QueryBuilder for method chaining.

remove_bin(bin_name)

Delete a bin from the record.

Return type:

Self

replace(arg1, *more_keys)

Open a full replace segment (removes bins not written in this segment).

Example::

await session.replace(key).put({“a”: 1}).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

replace_if_exists(arg1, *more_keys)

Open replace-if-exists semantics (like replace, but only if the record exists).

Example::

await session.replace_if_exists(key).put({“a”: 1}).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

replace_only()

Change the current segment to replace-if-exists semantics.

The record must already exist; the operation fails with KEY_NOT_FOUND_ERROR if it does not. All existing bins are removed and only the bins specified in this segment are written.

Return type:

Self

select_from(bin_name, expression, *, ignore_eval_failure=False)

Read a computed value into a bin using an AEL expression.

Return type:

Self

set_to(bin_name, value)

Set a bin to value.

Return type:

Self

touch(arg1, *more_keys)

Open a touch segment (TTL refresh).

Example::

await session.touch(key).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

touch_record()

Add a record-level touch to the current operate call.

Resets the record’s TTL as part of an atomic multi-operation call. Combine with expire_record_after_seconds() to set a new TTL.

Example:

stream = await (
    session.upsert(key)
        .bin("score").get()
        .touch_record()
        .expire_record_after_seconds(120)
        .execute()
)

See also

touch(): Start a new touch segment for a key.

Return type:

Self

update(arg1, *more_keys)

Open an update-only segment (fails if the record is missing).

Example::

await session.update(key).bin(“count”).add(1).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder for further bins and execute().

update_from(bin_name, expression, *, ignore_op_failure=False, ignore_eval_failure=False, delete_if_null=False)

Write expression result only if bin already exists.

Return type:

Self

upsert(arg1, *more_keys)

Open a create-or-update segment for the given key(s).

Example::

await session.upsert(key).put({“name”: “Bob”}).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder for put / bin / execute.

See also

upsert(): Session entry point.

upsert_from(bin_name, expression, *, ignore_op_failure=False, ignore_eval_failure=False, delete_if_null=False)

Write expression result, creating or overwriting the bin.

Return type:

Self

where(expression, *params)

Set a filter expression on the current write segment.

Overloads:
  • self, expression (str), params (Any) → Self

  • self, expression (FilterExpression) → Self

Parameters:
  • expression (Union[str, FilterExpression]) – AEL string or pre-built FilterExpression.

  • *params (Any) – Values for printf placeholders in an AEL template. See QueryBuilder.where() for the interpolation contract.

Returns:

self for method chaining.

Raises:

ValueError – If where has already been called on this operation. Each chained operation takes its own.

with_durable_delete()

Enable durable delete on the current segment.

Return type:

Self

with_no_change_in_expiration()

Preserve the record’s existing TTL (TTL = -2).

Return type:

Self

with_txn(txn)

Opt the chain into (or out of) a specific transaction.

Parameters:

txn (Optional[Txn]) – The Txn to participate in, or None to run without a transaction, including an implicit batch-write one.

Return type:

Self

Returns:

This builder for chaining.

without_durable_delete()

Force a non-durable delete for this segment (may be rejected on SC).

Return type:

Self