Query Builders

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

Bases: _QueryBuilderBase, _WriteVerbs[WriteSegmentBuilder]

Chain reads, writes, UDF calls, filters, and policies before execute.

Start from query(). Use where() for server-side predicates, bins() or bin() for projections, and transition methods such as upsert() for writes. Await execute() for a RecordStream.

Multi-key chains are split into per-node sub-batches, and a node whose sub-batch holds a single key is sent a regular single-record command instead of a batch request — automatically and per-node, so size-1 batches need no special-casing by the caller.

Example:

Set-wide read with filter and projection::

    stream = await (
        session.query(users)
            .where("$.status == 'active'")
            .bins(["user_id", "name"])
            .execute()
    )
    async for row in stream:
        if row.is_ok and row.record:
            print(row.record.bins)

Point read on a key, then chain an upsert::

    stream = await (
        session.query(users.id("u1"))
            .bins(["name"])
            .upsert(users.id("u1"))
            .put({"last_seen": 123})
            .execute()
    )

See also

WriteSegmentBuilder: Bin writes after a write verb. QueryBinBuilder: Per-bin read operations.

async execute(on_error=None)[source]

Execute the query and return a RecordStream.

Handles single-key, batch-key, and dataset queries. When a chain contains multiple operations, each operation is executed and results are combined into a single stream.

Parameters:

on_error (Union[ErrorStrategy, Callable[[Key, int, AerospikeError], None], None]) –

Controls how per-record errors are surfaced.

  • None (default): single-key operations raise on error; batch / multi-key operations embed errors in the stream.

  • ErrorStrategy.IN_STREAM: always embed errors in the stream as RecordResult entries.

  • A callable (key, index, exception) -> None: errors are dispatched to the callback and excluded from the stream.

Return type:

RecordStream

Returns:

A RecordStream of RecordResult rows.

Raises:
  • AerospikeError – If the builder mixes dataset query with per-bin read operations (unsupported combination).

  • AerospikeError – Typed subclasses for timeouts, connection failures, etc. when the client raises instead of embedding errors.

Example:

Single-key read with default error handling::

    stream = await session.query(key).bins(["x"]).execute()
    row = await stream.first_or_raise()

Multi-key read, keep errors in the stream::

    stream = await (
        session.query(k1, k2, k3)
            .execute(on_error=ErrorStrategy.IN_STREAM)
    )
    rows = await stream.collect()

See also

ErrorStrategy: on_error options.

async first(on_error=None)[source]

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

Reading one record by key is the most common thing this client does, and going through execute() costs two awaits for it – one for the stream, one for the row. This is that pair in one call; the stream is closed either way.

Semantics come from RecordStream.first(), not from a second set of rules: per-record failures arrive as data (is_ok=False), while cluster-level errors raise.

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 query matched nothing.

Example:

result = await session.query(key).first()
if result is None:
    print("no such record")
elif result.is_ok:
    print(result.record.bins)

See also

first_or_raise(): Raises instead of returning None. execute(): The stream, for reads that return many rows.

async first_or_raise(on_error=None)[source]

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

The single-await counterpart of (await (await q.execute()).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:

result = await session.query(key).first_or_raise()
record = result.record_or_raise()

See also

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

stream(on_error=None)[source]

Execute lazily — results stream back as each node responds.

The streaming counterpart to execute(). Where execute() awaits every result then returns a materialized stream (writes complete on return), this dispatches the key-batch through PNC’s lazy batch_stream and yields each (index, RecordResult) as its node responds — the first results are available as soon as the first node responds, without waiting for the rest, and peak memory stays bounded to the in-flight node responses. Results arrive in completion order, not input order; use RecordResult.index to correlate.

No writes-complete-on-return guarantee. Per-node work dispatches lazily; a caller that awaits this but never drains the stream may leave writes in-flight. For writes-done-on-return semantics use execute() (buffered).

The result is awaitable and doubles as an async context manager, so async with ....stream() as stream: closes the stream on exit.

Parameters:

on_error (Union[ErrorStrategy, Callable[[Key, int, AerospikeError], None], None]) – Same semantics as execute().

Return type:

AwaitableContext[RecordStream]

Returns:

A lazy RecordStream.

__init__(client, namespace, set_name, behavior, cached_read_policy=None, cached_write_policy=None, cached_read_policy_sc=None, cached_write_policy_sc=None, cached_read_operate_policy=None, cached_read_operate_policy_sc=None, txn=None, namespace_mode_resolver=None, namespace_mode_resolver_blocking=None, sdk_client=None, supports_server_compiled_ael=None, supports_query_selection=None)

Initialize a QueryBuilder.

Parameters:
  • client (Client) – The underlying async client.

  • namespace (str) – The namespace name.

  • set_name (str) – The set name.

  • behavior (Behavior) – The Behavior every policy this builder sends is derived from.

  • cached_read_policy (Optional[ReadPolicy]) – Pre-computed read policy from the session.

  • cached_write_policy (Optional[WritePolicy]) – Pre-computed write policy from the session.

  • cached_read_operate_policy (Optional[WritePolicy]) – Pre-computed policy for single-key operate calls that only read, from the session.

  • txn (Optional[Txn]) – Optional active Txn captured from a transactional session at construction; every policy this builder hands to the PNC gets stamped with it. None means no transaction participation. Callers rarely pass this directly — transactional sessions thread it through automatically.

  • namespace_mode_resolver (Optional[Callable[[str], Awaitable[Mode]]]) – Optional async callable namespace -> Mode used to apply AP vs SC behavior scopes before policies are built. Session-scoped builders supply this; client-only builders omit it.

  • namespace_mode_resolver_blocking (Optional[Callable[[str], Mode]]) – Sync counterpart used by execute_blocking() (the sync path bypassing asyncio).

  • sdk_client (Optional[Any]) – Optional owning SDK client, consulted at execute time for SDK-level settings (implicit batch-write transactions) and cluster MRT capability. None disables implicit transactions for this builder.

add_operation(op)

Append a read operation. Returns self so calls can chain.

Return type:

Self

bin(bin_name)

Start a bin-level read operation.

Returns a QueryBinBuilder for specifying how to read from the named bin (simple get, CDT navigation, or expression read).

Parameters:

bin_name (str) – The bin to operate on.

Return type:

QueryBinBuilder[QueryBuilder]

Returns:

A QueryBinBuilder for method chaining.

Example:

rs = await (
    session.query(users.id(1))
    .bin("settings").on_map_key("theme").get_values()
    .bin("age").get()
    .execute()
)
bins(*bin_names)

Restrict the read to a non-empty set of bin names.

Accepts the names as varargs or as a single sequence, matching with_op_projection() and the other varargs builders.

Mutually exclusive with with_no_bins().

Parameters:

*bin_names (Union[str, Sequence[str]]) – Bin names to return, either as separate arguments or as one sequence of names.

Return type:

Self

Returns:

This builder for method chaining.

Raises:

Example:

Restrict a query or key read to specific bins::

    stream = await session.query(users.id(1)).bins("name", "email").execute()

See also

with_no_bins(): Metadata-only reads without bin payloads. bin(): Per-bin operations (CDT, expressions).

chunk_size(chunk_size)

Tune server-side streaming chunk size (maps to query policy max_records chunking).

This method controls how many records are fetched per chunk from the server when using server-side streaming. The chunk size affects memory usage and network round trips (Larger values reduce round trips; smaller values bound memory per fetch). This is distinct from client-side pagination.

Important

Advancing between chunks is the caller’s job. Iterating the stream yields only the chunk already loaded, so a plain for / async for over a chunked query stops after chunk_size records and the rest are never fetched. Drive has_more_chunks() in an outer loop to read the whole result, as the example below does.

Parameters:

chunk_size (int) – Records per chunk; must be positive.

Return type:

Self

Returns:

This builder for chaining.

Raises:

ValueError – If chunk_size <= 0.

Example:

stream = await session.query(dataset).chunk_size(100).execute()
try:
    while await stream.has_more_chunks():
        async for result in stream:
            print(result.record.bins)
finally:
    stream.close()

See also

limit(): Cap total records returned. has_more_chunks(): Advance to the next server chunk.

default_expire_record_after(duration)

Set a default TTL using a datetime.timedelta.

Equivalent to default_expire_record_after_seconds() with seconds derived from duration — applied to chained operations that lack their own TTL. A duration 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.

default_expire_record_after_seconds(seconds)

Set a default TTL applied to chained operations that lack their own.

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. Not range-checked here — a value the client cannot represent is rejected when the write is built.

Return type:

Self

Returns:

self for method chaining.

default_expire_record_at(when)

Set a default TTL so chained writes expire 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 chained writes should expire.

Return type:

Self

Returns:

self for method chaining.

Raises:

ValueError – If when is not strictly in the future.

default_expiry_from_server_default()

Set the default TTL to the namespace’s server default (TTL = 0).

Return type:

Self

default_never_expire()

Set the default TTL to never expire (TTL = -1).

Return type:

Self

default_where(expression, *params)

Set a filter applied to any chained operation that does not call where().

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

  • self, expression (FilterExpression) → QueryBuilder

When a chain contains multiple operations (reads, writes, UDFs), each operation inherits this filter unless it supplies its own where().

Example:

stream = await (
    session.upsert(k1)
        .bin("status").set_to("active")
        .where(f"$.age >= {min_age}")
    .delete(k2, k3)
    .upsert(k4)
        .bin("flag").set_to(True)
    .default_where("$.active == true")
    .execute()
)
# upsert(k1) keeps its own where(); the delete and
# second upsert inherit default_where.
Parameters:
  • expression (Union[str, FilterExpression]) – AEL string or FilterExpression.

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

Returns:

This builder for chaining.

Raises:
  • TypeError – If params accompany a FilterExpression.

  • ValueError – If the template is not a valid printf format string.

See also

where(): Per-operation filter on the current operation.

default_with_no_change_in_expiration()

Set the default to preserve each record’s existing TTL (TTL = -2).

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()).

effective_allow_scans_with_where()

Resolve whether this query may fall back to a primary-index scan.

Applies the wire precedence: the query’s hint wins when it sets allow_scans_with_where, otherwise the resolved Behavior query setting, otherwise the default (allow the fallback).

Return type:

bool

Returns:

True if a where-clause query may fall back to a primary-index (full-set) scan, False if it is rejected.

execute_udf(*keys)

Finalize the current segment and chain a UDF execution on keys.

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

Parameters:

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

Return type:

UdfFunctionBuilder

Returns:

A UdfFunctionBuilder — call function next.

Raises:

ValueError – If no keys are provided, or if the current query is a dataset (index) query, which cannot be stacked.

Example:

rs = await (
    session.query(users.id(1))
    .bin("name").get()
    .execute_udf(users.id(2))
    .function("my_module", "my_fn")
    .execute()
)

See also

execute_udf(): Start a

chain with a UDF instead.

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.

fail_on_filtered_out()

Surface reads that fail a filter as FILTERED_OUT rows instead of omitting them.

Applies to key-based reads with a where filter. Without this flag, a key whose record exists but fails the filter is absent from the stream, whether or not include_missing_keys() is set. Writes always report a filtered-out key as a FILTERED_OUT row.

Example:

stream = await (
    session.query(customers.ids(20, 21, 22))
    .where("$.name == 'Tim'")
    .fail_on_filtered_out()
    .execute()
)
async for row in stream:
    if row.result_code == ResultCode.FILTERED_OUT:
        print(f"{row.key.value} is not a Tim")
Return type:

Self

Returns:

This builder for chaining.

See also

include_missing_keys(): Rows for keys whose record does not exist.

filter(filter_obj)

Attach an explicit secondary-index filter to the query.

The filter is authoritative: it is sent to the server unchanged as the index access path, bypassing server-side index selection. Any where() clause on the same builder travels beside it as a residual filter expression. An index-selection hint (QueryHint.index_name) does not rewrite an explicit filter; QueryHint.query_duration still applies. A query carries at most one filter.

Example:

stream = await (
    session.query(customers)
        .filter(Filter.range_by_index("idx_customer_age", 30, 65))
        .where("$.status == 'active'")
        .execute()
)
Parameters:

filter_obj (Filter) – The secondary-index filter to attach.

Return type:

Self

Returns:

This builder for method chaining.

Raises:

ValueError – If filter has already been called on this builder.

See also

where(), with_hint()

include_missing_keys()

Emit a row for each requested key whose record does not exist.

Missing keys appear as non-OK RecordResult entries (KEY_NOT_FOUND_ERROR) instead of being skipped. A key whose record exists but fails a where filter is a different outcome and stays omitted; add fail_on_filtered_out() to surface those too.

Example:

stream = await (
    session.query(customers.ids(46, 47, 48))
    .include_missing_keys()
    .execute()
)
async for row in stream:
    if row.result_code == ResultCode.KEY_NOT_FOUND_ERROR:
        print(f"no customer {row.key.value}")
Return type:

Self

Returns:

This builder for chaining.

See also

fail_on_filtered_out(): Rows for keys whose record fails the filter.

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().

limit(limit)

Cap the total number of records the query returns.

Once the limit is reached, the query stops. A query without a limit returns every matching record; there is no value that means “unlimited”, so leave the limit unset instead.

On a key query, only the first limit keys are read, in order across chained reads. A missing key still counts, so ids(1, 3, 5, 7) with limit(3) returns two records when key 5 does not exist.

Example:

stream = await session.query(users).where("$.age > 18").limit(100).execute()
Parameters:

limit (int) – Maximum number of records to return; must be positive.

Return type:

Self

Returns:

This builder for chaining.

Raises:

ValueError – If limit <= 0, or at execute if a key query chain also writes or calls a UDF.

See also

chunk_size(): Records per server round trip, rather than in total.

on_partition(part_id)

Target a specific partition for the query.

This method restricts the query to a single partition. This can be useful for load balancing or when you know the data distribution across partitions. On a key query, keys in other partitions are skipped before anything is sent.

Parameters:

part_id (int) – The partition ID to target (0-4095)

Return type:

Self

Returns:

self for method chaining

Raises:

ValueError – If part_id is out of range, or at execute if a key query chain also writes or calls a UDF.

Example:

query = session.query(dataset).on_partition(5)

See also

on_partition_range(): Target a contiguous span of partitions. partition(): Apply a pre-built partition filter.

on_partition_range(start_incl, end_excl)

Target a range of partitions for the query.

This method restricts the query to a specific range of partitions. This can be useful for load balancing, parallel processing, or when you know the data distribution across partitions.

The partition range can only be set once per query. Subsequent calls with different ranges will overwrite the previous range.

On a key query, keys outside the range are skipped before anything is sent, and limit() then counts only the keys that remain.

Parameters:
  • start_incl (int) – Start partition (inclusive, 0-4095)

  • end_excl (int) – End partition (exclusive, 1-4096)

Return type:

Self

Returns:

self for method chaining

Raises:

ValueError – If partition range is invalid, or at execute if a key query chain also writes or calls a UDF.

Example:

# Query partitions 0-2047 (first half)
query = session.query(dataset).on_partition_range(0, 2048)

# Query partitions 100-199
query = session.query(dataset).on_partition_range(100, 200)

See also

on_partition(): Target a single partition. partition(): Apply a pre-built partition filter.

partition(partition_filter)

Restrict the query using a PNC PartitionFilter.

Prefer on_partition() or on_partition_range() for common cases. A filter reused from an earlier dataset query resumes where that query stopped. On a key query only the filter’s partition range applies: keys outside it are skipped before anything is sent.

Example:

part = PartitionFilter.by_range(0, 2048)
stream = await session.query(users).partition(part).execute()
Parameters:

partition_filter (PartitionFilter) – Built filter (all partitions, by id, by range, etc.).

Return type:

Self

Returns:

This builder for chaining.

Raises:

ValueError – At execute, on a key query, if the filter carries resume state (PartitionFilter.by_key or progress from an earlier query), or if the chain also writes or calls a UDF.

See also

on_partition_range(): Inclusive start, exclusive end partition ids.

query(arg1, *more_keys)

Chain another query with new key(s) for batch/point stacking.

Finalizes the current query segment and begins a new one with the given key(s). Each segment can have its own bins, operations, and filter expression. Dataset (index) queries cannot be stacked.

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

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

Return type:

Self

Returns:

self for method chaining.

Raises:

ValueError – If the current query is a dataset query (no keys).

Example:

rs = await (
    session.query(users.ids(1, 2, 3))
    .bin("map").get()
    .query(users.ids(4, 5, 6))
    .bin("name").get()
    .execute()
)
records_per_second(rps)

Throttle the query to at most rps records per second on each server node.

Example:

stream = await session.query(users).records_per_second(1000).execute()
Parameters:

rps (int) – Maximum records per second; 0 means unthrottled.

Return type:

Self

Returns:

This builder for chaining.

See also

limit(): Cap the total records returned.

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.

touch(arg1, *more_keys)

Open a touch segment (TTL refresh).

Example::

await session.touch(key).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

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().

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.

where(expression, *params)

Apply a server-side filter for dataset queries or keyed reads that support it.

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

  • self, expression (FilterExpression) → QueryBuilder

String arguments are AEL, compiled by the server. Pass a pre-built FilterExpression when constructing filters programmatically.

Supplying params interpolates them into the template with printf syntax. Only trusted values belong here — interpolation does not quote or escape, so it is no safer than an f-string.

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

  • *params (Any) – Values for printf placeholders in an AEL template.

Returns:

This builder for chaining.

Raises:
  • TypeError – If params accompany a FilterExpression.

  • ValueError – If the template is not a valid printf format string, or where has already been called for this operation.

Example:

qb = session.query(ds).where("$.status == 'active'")
qb = session.query(ds).where("$.score > %d", min_score)
qb = session.query(ds).where(f"$.score > {min_score}")

See also

default_where(): Default filter for chained operations without their own.

with_hint(hint)

Attach a query hint for secondary index selection or scheduling.

A hint can redirect which secondary index is used (index_name) or override the expected query duration (query_duration). Only one call to with_hint is allowed per builder.

Example:

stream = await (
    session.query(dataset)
        .filter(Filter.equal("age", 30))
        .with_hint(QueryHint(index_name="age_idx"))
        .execute()
)
Parameters:

hint (QueryHint) – A QueryHint instance.

Return type:

Self

Returns:

This builder for method chaining.

Raises:

ValueError – If with_hint has already been called on this builder.

See also

QueryHint

with_no_bins()

Specify that no bins should be read (header-only query).

This method is useful when you only need to check for record existence or get metadata like generation numbers, without reading the actual data.

This method cannot be used together with bins().

Return type:

Self

Returns:

self for method chaining.

Raises:

ValueError – If used together with bins().

with_op_projection(*ops)

Project query results through one or more read operations.

The server applies ops to every matching record and returns the operation results in place of the configured bin set. Mutually exclusive with bins(): when a projection is set the server ignores the bin list. Subsequent calls replace the previous projection.

The server accepts basic get_bin / get_header ops as well as CDT, expression, bit, and HLL reads — for example CdtOperation.select_values("bin", [...]).

Parameters:

*ops (Any) – One or more native aerospike_native read operations.

Return type:

Self

Returns:

This builder for method chaining.

Example:

from aerospike_sdk import CTX, CdtOperation
stream = await (
    session.query(users)
        .with_op_projection(
            CdtOperation.select_values(
                "inventory", [CTX.map_key("books")]
            ),
        )
        .execute()
)
with_txn(txn)

Opt this builder into (or out of) a specific transaction.

Overrides any transaction captured at construction. Pass None to opt out of an ambient transaction (useful inside a TransactionalSession when a single operation must run outside the MRT). None also opts a multi-key write out of implicit batch-write transactions (implicit_batch_write_transactions), guaranteeing the operation runs in no transaction at all.

Parameters:

txn (Optional[Txn]) – The Txn to participate in, or None to run without a transaction.

Return type:

Self

Returns:

This builder for method chaining.

Example:

async with session.transaction() as tx:
    await tx.upsert(k1).bin("v").set_to(1).execute()
    # Run this one write outside the transaction:
    await tx.upsert(k2).with_txn(None).bin("v").set_to(2).execute()
class aerospike_sdk.aio.operations.query.WriteBinBuilder[source]

Bases: _BinWriteSteps[WriteSegmentBuilder], _WriteVerbs[_WriteSegmentBuilderBase]

Per-bin write builder inside a WriteSegmentBuilder.

Start with WriteSegmentBuilder.bin(). Scalar methods append to the segment; map_* and list_* append collection operations; hll_* and bit_* append HyperLogLog and blob bit operations; nested CDT builders capture context for maps and lists. Write verbs on this class finalize the segment and start a new one on new keys.

Example:

Set a map key and append to a list within the same write::

    await (
        session.upsert(key)
            .bin("config").on_map_key("level").set_to(5)
            .bin("tags").list_append(value="new_tag")
            .execute()
    )

See also

QueryBinBuilder: Read-side analogue for queries.

__init__(segment, bin_name)[source]
bin(bin_name)[source]

Start the next bin operation without leaving the write segment.

Return type:

WriteBinBuilder

query(arg1, *more_keys)[source]

Shortcut: finalize write segment and start a read segment.

Return type:

QueryBuilder

execute_udf(*keys)[source]

Shortcut: finalize the write segment and chain a UDF on keys.

See QueryBuilder.execute_udf() for semantics; the whole chain still executes as one batch.

Return type:

UdfFunctionBuilder

async execute(on_error=None)[source]

Shortcut: execute all accumulated specs.

Return type:

RecordStream

async stream(on_error=None)[source]

Lazy streaming variant — see QueryBuilder.stream().

Return type:

RecordStream

add(value)

Add a numeric value to the bin (Operation.add).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

append(value)

String append (Operation.append).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

bit_add(bit_offset, bit_size, value, signed, action, policy=None)

Add value to the integer encoded in bit_size bits at bit_offset.

action selects overflow behavior (for example WRAP).

Example::

from aerospike_sdk import BitwiseOverflowActions await ( session.update(key) .bin(“blob”) .bit_add(0, 16, 1, False, BitwiseOverflowActions.WRAP) .execute() )

Parameters:
  • bit_offset (int) – Starting bit index of the integer field.

  • bit_size (int) – Width of the integer in bits.

  • value (int) – Amount to add.

  • signed (bool) – True if the stored integer is signed.

  • action (Any) – Overflow policy (BitwiseOverflowActions).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_and(bit_offset, bit_size, value, policy=None)

Bitwise AND value into the bit_size bits at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_and(0, 8, b”xf0”).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • value (Any) – Right-hand side of the AND (typically bytes).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_b64_encode(byte_offset=None, byte_size=None, invert_size=False)

Read this blob bin as base64 text, whole or by byte range.

Without a range the whole blob is encoded. With byte_offset and byte_size (required together) only that byte range is encoded; a negative byte_offset counts back from the end of the blob. When invert_size is True, byte_size counts back from the end instead, so an inverted size of 0 encodes through to the end.

Requires server 8.2.0 or later. The decode direction is str_b64_decode().

Example:

stream = await (
    session.update(key)
    .bin("payload").bit_b64_encode(0, 16)
    .execute()
)
Parameters:
  • byte_offset (Optional[int]) – Starting byte index of the range; negative counts back from the end. Given together with byte_size.

  • byte_size (Optional[int]) – Byte count to encode (or, inverted, the count left off the end).

  • invert_size (bool) – True to measure byte_size back from the end of the blob.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

Raises:

ValueError – If only one of byte_offset / byte_size is given, or invert_size is set without a range.

bit_count(bit_offset, bit_size)

Count bits set to 1 in bit_size bits starting at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_count(0, 8).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_get(bit_offset, bit_size)

Read bit_size bits at bit_offset as raw bytes in a write operate.

For read-only access, use QueryBinBuilder.bit_get().

Example::

await session.update(key).bin(“blob”).bit_get(0, 8).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to read.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_get_int(bit_offset, bit_size, signed)

Decode an integer from bit_size bits at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_get_int(0, 16, False).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Width of the integer in bits.

  • signed (bool) – True to interpret as two’s-complement signed.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_insert(byte_offset, value, policy=None)

Insert value (bytes) at a byte offset in the blob bin.

Example::

await session.update(key).bin(“blob”).bit_insert(0, b”x01x02”).execute()

Parameters:
  • byte_offset (int) – Byte position at which to insert.

  • value (Any) – Bytes to insert.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_remove(): Remove a byte range.

bit_lscan(bit_offset, bit_size, value)

Return the leftmost bit index in the range matching value.

value is True to search for a set bit (1) or False for an unset bit (0).

Example::

await session.update(key).bin(“blob”).bit_lscan(0, 8, True).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

  • value (bool) – True for set bits, False for unset bits.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_lshift(bit_offset, bit_size, shift, policy=None)

Left-shift the bit_size bits at bit_offset by shift bits.

Example::

await session.update(key).bin(“blob”).bit_lshift(0, 16, 2).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • shift (int) – Number of bits to shift left.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_rshift()

bit_not(bit_offset, bit_size, policy=None)

Invert every bit in the range [bit_offset, bit_offset + bit_size).

Example::

await session.update(key).bin(“blob”).bit_not(0, 8).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_or(bit_offset, bit_size, value, policy=None)

Bitwise OR value into the bit_size bits at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_or(0, 8, b”x0f”).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • value (Any) – Right-hand side of the OR (typically bytes).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_remove(byte_offset, byte_size, policy=None)

Remove byte_size bytes starting at byte_offset.

Example::

await session.update(key).bin(“blob”).bit_remove(0, 2).execute()

Parameters:
  • byte_offset (int) – Start of the range to remove.

  • byte_size (int) – Number of bytes to remove.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_insert(): Insert bytes at an offset.

bit_resize(byte_size, resize_flags=None, policy=None)

Grow or shrink the raw bytes backing this bin.

When resize_flags is None, DEFAULT is used. When policy is None, a default BitPolicy is built from DEFAULT.

Example::

await session.upsert(key).bin(“flags”).bit_resize(4).execute()

Parameters:
  • byte_size (int) – Target size of the blob in bytes.

  • resize_flags (Optional[Any]) – Optional BitwiseResizeFlags value; None selects DEFAULT.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_insert(): Insert raw bytes at an offset. QueryBinBuilder.bit_get(): Read bits in a query.

bit_rscan(bit_offset, bit_size, value)

Return the rightmost bit index in the range matching value.

Example::

await session.update(key).bin(“blob”).bit_rscan(0, 8, False).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

  • value (bool) – True for set bits, False for unset bits.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_rshift(bit_offset, bit_size, shift, policy=None)

Right-shift the bit_size bits at bit_offset by shift bits.

Example::

await session.update(key).bin(“blob”).bit_rshift(0, 16, 2).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • shift (int) – Number of bits to shift right.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_lshift()

bit_set(bit_offset, bit_size, value, policy=None)

Overwrite bit_size bits at bit_offset with value.

value is typically a small bytes object whose bits replace the range (see server documentation for encoding).

Example::

await session.update(key).bin(“blob”).bit_set(0, 8, b”xff”).execute()

Parameters:
  • bit_offset (int) – Starting bit index within the blob.

  • bit_size (int) – Width of the field in bits.

  • value (Any) – Bits to write (commonly bytes).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

bit_get(): Read the same range in an operate or query. bit_or(), bit_xor(), bit_and(), bit_not()

bit_set_int(bit_offset, bit_size, value, policy=None)

Write integer value into bit_size bits at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_set_int(0, 16, 42).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Width of the integer in bits.

  • value (int) – Integer to store.

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_subtract(bit_offset, bit_size, value, signed, action, policy=None)

Subtract value from the integer in bit_size bits at bit_offset.

Example::

from aerospike_sdk import BitwiseOverflowActions await ( session.update(key) .bin(“blob”) .bit_subtract(0, 16, 1, False, BitwiseOverflowActions.SATURATE) .execute() )

Parameters:
  • bit_offset (int) – Starting bit index of the integer field.

  • bit_size (int) – Width of the integer in bits.

  • value (int) – Amount to subtract.

  • signed (bool) – True if the stored integer is signed.

  • action (Any) – Overflow policy (BitwiseOverflowActions).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

bit_xor(bit_offset, bit_size, value, policy=None)

Bitwise XOR value into the bit_size bits at bit_offset.

Example::

await session.update(key).bin(“blob”).bit_xor(0, 8, b”xff”).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Field width in bits.

  • value (Any) – Right-hand side of the XOR (typically bytes).

  • policy (Optional[Any]) – Optional BitPolicy; None selects a default policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

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()).

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.

get()

Return the bin value after writes complete (Operation.get_bin).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

hll_add(values, *, config=None, create_only=False, update_only=False, no_fail=False, allow_fold=False)

Add distinct values to the HyperLogLog sketch in this bin.

The server hashes each element into the sketch. Pass config=... to auto-create the sketch on the first call with that precision; omit it to inherit defaults from an existing sketch.

Example:

await (
    session.upsert(key)
    .bin("visitors").hll_add(["user-1", "user-2"])
    .execute()
)
Parameters:
  • values (Sequence[Any]) – Sequence of values (e.g. strings or blobs) to add.

  • config (Optional[HllConfig]) – Optional HLL config used to auto-create the bin on first use. When None, inherits the existing sketch’s bit widths.

  • create_only (bool) – Fail if the bin already exists.

  • update_only (bool) – Fail if the bin does not already exist.

  • no_fail (bool) – Skip the operation silently when a mode constraint blocks it.

  • allow_fold (bool) – Allow folding so unions tolerate mismatched precisions.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

Raises:

ValueError – If create_only and update_only are both true.

See also

hll_init(): Create an empty sketch explicitly. hll_get_count(): Read cardinality in the same operate batch.

hll_describe()

Read index and min-hash bit counts describing the stored sketch.

Example::

await session.update(key).bin(“hll”).hll_describe().execute()

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_describe(): Same read on a query builder.

hll_fold(index_bit_count)

Reduce sketch precision to a lower index_bit_count (merge registers).

Example::

await session.update(key).bin(“hll”).hll_fold(10).execute()

Parameters:

index_bit_count (int) – New (smaller) index bit width after folding.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

hll_init(): Initial precision when creating a sketch.

hll_get_count()

Read the estimated cardinality in a multi-operation write (operate).

The result is returned for this bin when the write completes. For a read-only path, use QueryBinBuilder.hll_get_count().

Example::

stream = await ( session.update(key) .bin(“hll”) .hll_get_count() .execute() )

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_get_count(): Same read on a query builder. hll_add(): Populate the sketch before counting.

hll_get_intersect_count(hll_list)

Read the estimated intersection cardinality with other sketches.

Example::

await ( session.update(key) .bin(“hll”) .hll_get_intersect_count([peer_blob]) .execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches included in the intersection estimate.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_get_intersect_count(): Same read on a query.

hll_get_similarity(hll_list)

Read Jaccard similarity between this sketch and other sketches.

Example::

await ( session.update(key) .bin(“hll”) .hll_get_similarity([peer_blob]) .execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches to compare.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_get_similarity(): Same read on a query.

hll_get_union(hll_list)

Read the union sketch without modifying the stored bin.

Example::

await ( session.update(key) .bin(“hll”) .hll_get_union([peer_blob]) .execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches (blobs) to include in the union result.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_get_union(): Same read on a query builder. hll_set_union(): Persist a union into the bin.

hll_get_union_count(hll_list)

Read the estimated cardinality of the union with other sketches.

Example::

await ( session.update(key) .bin(“hll”) .hll_get_union_count([peer_blob]) .execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches to union for the estimate.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.hll_get_union_count(): Same read on a query.

hll_init(config, *, create_only=False, update_only=False, no_fail=False, allow_fold=False)

Initialize an empty HyperLogLog sketch in this bin.

Use before hll_add() on a new bin. create_only and update_only are mutually exclusive; passing both raises ValueError.

Example:

await (
    session.upsert(key)
    .bin("visitors").hll_init(HllConfig.of(12))
    .execute()
)
Parameters:
  • config (HllConfig) – Index and minhash bit widths for the new sketch.

  • create_only (bool) – Fail if the bin already exists.

  • update_only (bool) – Fail if the bin does not already exist.

  • no_fail (bool) – Skip the operation silently when a mode constraint blocks it.

  • allow_fold (bool) – Allow folding so unions tolerate mismatched precisions.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

Raises:

ValueError – If create_only and update_only are both true.

See also

hll_add(): Add distinct values to the sketch. QueryBinBuilder.hll_get_count(): Read cardinality in a query.

hll_refresh_count()

Refresh the cached cardinality estimate stored with the sketch.

Example::

await session.update(key).bin(“hll”).hll_refresh_count().execute()

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

hll_get_count(): Read the estimate in the same batch.

hll_set_union(hll_list, *, create_only=False, update_only=False, no_fail=False, allow_fold=False)

Merge other HyperLogLog sketches into this bin (destructive union).

Each entry in hll_list is typically another HLL blob (bytes) returned from a prior read.

Example:

await (
    session.upsert(key)
    .bin("merged").hll_set_union([other_hll_blob])
    .execute()
)
Parameters:
  • hll_list (Sequence[Any]) – Sketches to union into the target bin.

  • create_only (bool) – Fail if the bin already exists.

  • update_only (bool) – Fail if the bin does not already exist.

  • no_fail (bool) – Skip the operation silently when a mode constraint blocks it.

  • allow_fold (bool) – Allow folding so unions tolerate mismatched precisions.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

Raises:

ValueError – If create_only and update_only are both true.

See also

hll_get_union(): Non-destructive union read. hll_add(): Add raw values instead of whole sketches.

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(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:

TypeVar(_W, bound= _SupportsBinWrites)

list_add(value, *, unique=False, bounded=False, no_fail=False)

Add value to an ordered list (sorted insert).

Parameters:
  • value (Any) – Element to insert in sorted order.

  • unique (bool) – Reject if the value already exists in the list.

  • bounded (bool) – Reject if index is beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_add_items(items, *, unique=False, bounded=False, no_fail=False, partial=False)

Insert values into an ordered list (sorted positions).

Parameters:
  • items (Any) – Sequence of values to insert in sorted order.

  • unique (bool) – Reject items that already exist in the list.

  • bounded (bool) – Reject inserts beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_append(value, *, unique=False, bounded=False, no_fail=False)

Append value to the end of an unordered list.

Parameters:
  • value (Any) – Value to append.

  • unique (bool) – Reject if the value already exists in the list.

  • bounded (bool) – Reject if index is beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Example::

.bin(“tags”).list_append(value=”python”)

list_append_items(items, *, unique=False, bounded=False, no_fail=False, partial=False)

Append values to an unordered list.

Parameters:
  • items (Any) – Values to append.

  • unique (bool) – Reject items that already exist in the list.

  • bounded (bool) – Reject inserts beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

list_clear()

Remove all elements from the list bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_create(order, *, pad=True, persist_index=False)

Create an empty list with the given order.

Parameters:
  • order (ListOrderType) – List element order.

  • pad (bool) – When creating through a context path, allow the target index to leave a gap, filling the skipped entries with None. Defaults to True. Has no effect on a top-level list, which has no context element to carry the flag.

  • persist_index (bool) – Whether to persist element indices.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_increment(index, value=1)

Add value to the numeric element at index (default increment is 1).

Parameters:
  • index (int) – List index (0-based; negative counts from the end).

  • value (int) – Amount to add; 1 uses a dedicated server path.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

list_set()

list_insert(index, value, *, unique=False, bounded=False, no_fail=False)

Insert value at index in an unordered list.

Parameters:
  • index (int) – List index (0-based; negative counts from the end).

  • value (Any) – Element to insert.

  • unique (bool) – Reject if the value already exists in the list.

  • bounded (bool) – Reject if index is beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_insert_items(index, items, *, unique=False, bounded=False, no_fail=False, partial=False)

Insert a sequence of values starting at index.

Parameters:
  • index (int) – List index at which to insert the first element.

  • items (Sequence[Any]) – Values to insert in order.

  • unique (bool) – Reject items that already exist in the list.

  • bounded (bool) – Reject inserts beyond the current list bounds.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_join(separator=None)

Concatenate the string items of the list (read within operate).

The list must hold only strings; any other element type fails with PARAMETER_ERROR. An empty list joins to an empty string. The inverse of str_split().

Parameters:

separator (Optional[str]) – Inserted between consecutive items. None = no separator.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_pop(index)

Remove and return the element at index (read in the operate result).

Parameters:

index (int) – List index (0-based; negative counts from the end).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

list_pop_range()

list_pop_range(index, count=None)

Pop count elements from index, or from index through the end.

Parameters:
  • index (int) – Starting list index.

  • count (Optional[int]) – Number of elements; None pops through the end.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

list_pop()

list_remove(index)

Remove the element at index.

Parameters:

index (int) – List index (0-based; negative counts from the end).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_remove_range(index, count=None)

Remove count elements starting at index, or all from index onward.

Parameters:
  • index (int) – Starting list index.

  • count (Optional[int]) – Number of elements to remove; None removes through the end.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

list_remove()

list_set(index, value)

Replace the element at index with value.

Parameters:
  • index (int) – List index (0-based; negative counts from the end).

  • value (Any) – New element value.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

list_get()

list_set_order(order)

Set list sort order without changing elements.

Parameters:

order (ListOrderType) – List element order.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_size()

Return the list element count (read within operate).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_sort(flags=ListSortFlags.DEFAULT)

Sort the list bin.

Parameters:

flags (ListSortFlags) – Sort behavior flags.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

list_trim(index, count)

Keep only count elements starting at index; remove the rest.

Parameters:
  • index (int) – Starting list index of the range to keep.

  • count (int) – Number of elements to keep.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_clear()

Remove all entries from the map bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_create(order)

Create an empty map with the given key order.

Parameters:

order (MapOrder) – Map key sort order.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_insert_items(items, *, order=None, persist_index=False, no_fail=False, partial=False)

Put map entries only for keys that do not yet exist.

Parameters:
  • items (Any) – Mapping or sequence of (key, value) pairs.

  • order (MapOrder | None) – Map key order for the policy.

  • persist_index (bool) – Maintain a persistent index on the map.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

map_set_policy(order)

Set map sort order policy without changing entries.

Parameters:

order (MapOrder) – Map key sort order policy.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_size()

Return the map element count (read within operate).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_update_items(items, *, order=None, persist_index=False, no_fail=False, partial=False)

Update existing map entries only (no new keys).

Parameters:
  • items (Any) – Key-value pairs to update for existing keys only.

  • order (MapOrder | None) – Map key order for the policy.

  • persist_index (bool) – Maintain a persistent index on the map.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

map_upsert_items(items, *, order=None, persist_index=False, no_fail=False, partial=False)

Put multiple map entries (create or update each key).

Parameters:
  • items (Any) – Mapping or sequence of (key, value) pairs.

  • order (MapOrder | None) – Map key order for the policy.

  • persist_index (bool) – Maintain a persistent index on the map.

  • no_fail (bool) – Do not raise on write failures.

  • partial (bool) – Allow partial success for bulk operations.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Example::

.bin(“settings”).map_upsert_items({“theme”: “dark”, “lang”: “en”})

on_each_child()

Select every child of this bin, for a path read or modify.

Walks a whole level instead of one element, so the terminal applies across the selection: collect_values() reads them all, modify_by(expr) rewrites them all. Chain again to go deeper.

Example:

await session.update(key).bin("nums").on_each_child().modify_by(
    Exp.num_add([Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(10)])
).execute()
Return type:

CdtPathBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtPathBuilder for further navigation or a terminal.

on_each_child_where(predicate)

Select the children matching predicate.

Parameters:

predicate (Any) – An Exp over the element’s loop variable, e.g. Exp.gt(Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(5)).

Return type:

CdtPathBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtPathBuilder for further navigation or a terminal.

on_list_index(index, *, order=None, pad=False)

Navigate to a list element by index.

Parameters:
  • index (int) – List index (0-based, negative counts from end).

  • order (Optional[ListOrderType]) – If set (or if pad is True), use create-on-missing list context with this order; when only pad is True, defaults to UNORDERED.

  • pad (bool) – When using create-on-missing context, allow sparse indexes.

Return type:

CdtWriteBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteBuilder for writing the targeted element(s).

Example::

.bin(“items”).on_list_index(0).set_to(“first”)

on_list_index_range(index, count=None)

Navigate to list elements by index range.

Parameters:
  • index (int) – List index (0-based, negative counts from end).

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_list_rank(rank)

Navigate to a list element by rank (0 = lowest value).

Parameters:

rank (int) – Rank position (0 = lowest value).

Return type:

CdtWriteBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteBuilder for writing the targeted element(s).

on_list_rank_range(rank, count=None)

Navigate to list elements by rank range.

Parameters:
  • rank (int) – Rank position (0 = lowest value).

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_list_value(value)

Navigate to list elements matching a value.

Parameters:

value (Any) – Value to match.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_list_value_list(values)

Navigate to list elements matching a list of values.

Parameters:

values (List[Any]) – Values to match.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

Raises:

TypeError – If values is a bare str, bytes or bytearray rather than a collection of values.

on_list_value_range(start, end)

Navigate to list elements by value range [start, end).

Parameters:
  • start (Any) – Inclusive range start.

  • end (Any) – Exclusive range end.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_list_value_relative_rank_range(value, rank, count=None)

Navigate to list elements by value rank range relative to an anchor value.

Parameters:
  • value (Any) – Value to match.

  • rank (int) – Rank offset from the anchor value.

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_index(index)

Navigate to a map element by index.

Parameters:

index (int) – List index (0-based, negative counts from end).

Return type:

CdtWriteBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteBuilder for writing the targeted element(s).

on_map_index_range(index, count=None)

Navigate to map elements by index range.

Parameters:
  • index (int) – List index (0-based, negative counts from end).

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_key(key, *, create_type=None)

Navigate to a map element by key.

Parameters:
  • key (Any) – Map key to target.

  • create_type (Optional[MapOrder]) – If set, use a create-on-missing context for this key with the given map key order.

Return type:

CdtWriteBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteBuilder for writing the targeted element(s).

on_map_key_list(keys)

Navigate to map elements matching a list of keys.

Parameters:

keys (List[Any]) – Map keys to match.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

Raises:

TypeError – If keys is a bare str, bytes or bytearray rather than a collection of keys.

on_map_key_range(start, end)

Navigate to map elements by key range [start, end).

Parameters:
  • start (Any) – Inclusive range start.

  • end (Any) – Exclusive range end.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_key_relative_index_range(key, index, count=None)

Navigate to map entries by index range relative to an anchor key.

Parameters:
  • key (Any) – Map key to target.

  • index (int) – Index offset from the anchor key.

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_keys_in(keys)

Select the map entries whose key is in keys, for a path read or modify.

Parameters:

keys (Iterable[Any]) – The map keys to select.

Return type:

CdtPathBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtPathBuilder for further navigation, an and_filter, or a terminal.

Raises:

TypeError – If keys is a bare str, bytes or bytearray rather than a collection of keys.

Example:

add_10 = Exp.num_add([Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(10)])
await (
    session.update(key).bin("m").on_map_keys_in(["a", "c"]).modify_by(add_10).execute()
)
on_map_rank(rank)

Navigate to a map element by rank (0 = lowest value).

Return type:

CdtWriteBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

on_map_rank_range(rank, count=None)

Navigate to map elements by rank range.

Parameters:
  • rank (int) – Rank position (0 = lowest value).

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_value(value)

Navigate to map elements matching a value.

Parameters:

value (Any) – Value to match.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_value_list(values)

Navigate to map elements matching a list of values.

Parameters:

values (List[Any]) – Values to match.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

Raises:

TypeError – If values is a bare str, bytes or bytearray rather than a collection of values.

on_map_value_range(start, end)

Navigate to map elements by value range [start, end).

Parameters:
  • start (Any) – Inclusive range start.

  • end (Any) – Exclusive range end.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

on_map_value_relative_rank_range(value, rank, count=None)

Navigate to map entries by value rank range relative to an anchor value.

Parameters:
  • value (Any) – Value to match.

  • rank (int) – Rank offset from the anchor value.

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtWriteInvertableBuilder[TypeVar(_W, bound= _SupportsBinWrites)]

Returns:

CdtWriteInvertableBuilder for writing the targeted element(s).

prepend(value)

String prepend (Operation.prepend).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

read_as_string()

Register a to-string read: convert any bin to its string representation.

Type-agnostic — the source bin need not be a string, which is why this method carries no str_ prefix (str_to_integer and friends genuinely require a string source). Accepts bool, int, float, string, or blob source types; any other type returns BIN_TYPE_ERROR from the server, and a blob that is not valid UTF-8 returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_UTF8_INVALID). Has no flags argument and no CDT-context support (the wire op has no payload to carry a CTX wrapper).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

remove()

Drop the bin (write None).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

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.

select_from(expression, *, ignore_eval_failure=False)

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

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

set_to(value)

Set the bin to value (Operation.put).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

set_to_geo_json(geo_json)

Set the bin to a GeoJSON value from its string form.

The bin’s server-side particle type is GEOJSON, not STRING. Equivalent to set_to(GeoJSON(geo_json)) but reads naturally for spatial data.

Parameters:

geo_json (str) – A GeoJSON string (e.g. a Point, Polygon, or AeroCircle).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_append(value, *, flags=0)

Register an append modify: add value to the end of the bin.

The single-value form (server sub-op 67). Use str_concat() for the list form.

Parameters:
Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_b64_decode()

Register a base64-decode read: treats the bin as base64 text, returns bytes.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_B64_INVALID) if the bin is not valid base64.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_byte_length()

Register a byte-length read: UTF-8 byte count of this string bin.

Differs from str_strlen() for non-ASCII content (where one codepoint can encode to multiple bytes).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_case_fold(*, flags=0)

Register a case-fold modify: locale-independent lowercase, useful for comparison keys.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_char_at(index)

Register a char-at read: returns the codepoint at index as a one-codepoint string. Negative index counts from the end.

Example::

stream = await session.upsert(key).bin(“s”).str_char_at(1).execute()

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_concat(value, *, flags=0)

Register a concat modify: append value (single string or list of strings).

The wire format is always list-of-strings — passing a single str is wrapped in a 1-element list internally.

Parameters:
Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_contains(needle)

Register a contains read: True iff this bin contains needle.

Result is a Python bool (the server returns a native msgpack boolean for the seven boolean-shaped read ops).

Example::

stream = await session.upsert(key).bin(“s”).str_contains(“hello”).execute()

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_ends_with(suffix)

Register an ends-with read: True iff this bin ends with suffix.

Matching is Unicode canonical, not byte-exact: a suffix in a different normalization form than the stored value still matches.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_find(needle, occurrence=None)

Register a find read: codepoint index of the first occurrence of needle, or the N-th occurrence when occurrence is given.

Returns -1 if the needle is absent. Occurrence numbering is 1-based (1 = first match); -1 selects the last match.

Example::

stream = await session.upsert(key).bin(“s”).str_find(“world”).execute()

Parameters:
  • needle (str) – Substring to locate.

  • occurrence (Optional[int]) – 1-based match index. None means first occurrence.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_insert(index, value, *, flags=0)

Register an insert modify: splice value into this bin at codepoint index.

Negative index counts from the end of the string. Out-of-bounds indexes clamp.

Parameters:
  • index (int) – Codepoint index to splice at.

  • value (str) – String to insert.

  • flags (int | StringWriteFlags | StringRegexFlags) – OR-combined StringWriteFlags bitmask (NO_FAIL suppresses the op on missing-bin error).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_is_lower()

Register an is-lower read: True iff every cased codepoint is lowercase.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_is_numeric(numeric_type=None)

Register an is-numeric read: True iff this bin parses as a number.

Pass numeric_type to restrict to StringNumericType.INT or StringNumericType.FLOAT; default ANY accepts either.

Example:

stream = await (
    session.upsert(key).bin("count")
        .str_is_numeric(StringNumericType.INT)
        .execute()
)
Parameters:

numeric_type (Optional[StringNumericType]) – Restrict to one numeric class. None = either.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_is_upper()

Register an is-upper read: True iff every cased codepoint is uppercase.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_lower(*, flags=0)

Register a lower modify: lowercase the bin in place.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_normalize_nfc(*, flags=0)

Register a normalize-NFC modify: Unicode NFC normalization in place.

Already-normalized strings are unchanged.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_overwrite(index, value, *, flags=0)

Register an overwrite modify: overwrite codepoints starting at index with value.

May extend the bin’s length when value runs past the end.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_pad_end(target_length, pad_string, *, flags=0)

Register a pad-end modify: right-pad with pad_string to target_length codepoints.

No-op when the bin is already at or above target_length.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_pad_start(target_length, pad_string, *, flags=0)

Register a pad-start modify: left-pad with pad_string to target_length codepoints.

No-op when the bin is already at or above target_length.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_prepend(value, *, flags=0)

Register a prepend modify: add value to the start of the bin.

Distinct from str_insert() at index 0 — this is the server’s dedicated prepend sub-op (68).

Parameters:
Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_regex_compare(pattern, flags=0)

Register a regex-compare read: True iff pattern matches this bin.

Uses ICU regex syntax. Combine StringRegexFlags constants with bitwise OR for the flags argument.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_REGEX_LIMIT_EXCEEDED) if matching exceeds the server’s regex resource budget.

Example:

stream = await (
    session.upsert(key).bin("s")
        .str_regex_compare("^hello.*", StringRegexFlags.CASE_INSENSITIVE)
        .execute()
)
Parameters:
Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_regex_replace(pattern, replacement, flags=0, *, write_flags=0)

Register a regex-replace modify.

Replaces the first match of pattern with replacement. Set the GLOBAL bit in flags (StringRegexFlags.GLOBAL) to replace every match.

Note

flags is StringRegexFlags (regex behavior); the StringWriteFlags bitmask travels in write_flags. CREATE_ONLY is a PARAMETER_ERROR here because a regex replace cannot create a bin.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_REGEX_LIMIT_EXCEEDED) if matching exceeds the server’s regex resource budget.

Example:

await (
    session.upsert(key)
        .bin("text").str_regex_replace(
            r"\d", "X", StringRegexFlags.GLOBAL,
            write_flags=StringWriteFlags.UPDATE_ONLY)
        .execute()
)
Parameters:
  • pattern (str) – ICU regex pattern.

  • replacement (str) – Replacement text.

  • flags (int | StringRegexFlags) – OR-combined StringRegexFlags bitmask.

  • write_flags (int | StringWriteFlags) – OR-combined StringWriteFlags bitmask (UPDATE_ONLY / NO_FAIL).

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_repeat(count, *, flags=0)

Register a repeat modify: repeat the bin contents count times.

count must be non-negative.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_replace(needle, replacement, *, flags=0)

Register a replace modify: replace the first occurrence of needle.

Use str_replace_all() to replace every occurrence.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_replace_all(needle, replacement, *, flags=0)

Register a replace-all modify: replace every occurrence of needle.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_snip(start, end=None, *, flags=0)

Register a snip modify: remove the half-open codepoint range [start, end).

When end is omitted, everything from start through the end of the string is removed — str_snip(5) truncates "hello world" to "hello". Negative indexes count from the end of the string.

Note

flags require an explicit end. The server reads the snip arguments by position (start, end, then flags), so the truncate-to-end form is sent without a flags element.

Parameters:
  • start (int) – Codepoint index where the removed range starts.

  • end (int | None) – Exclusive end of the removed range, or None to remove through the end of the string.

  • flags (int | StringWriteFlags | StringRegexFlags) – OR-combined StringWriteFlags bitmask.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_split(separator=None)

Register a split read.

With separator omitted, returns one element per Unicode codepoint (per-codepoint split). With separator set, splits on the substring; absent separator → singleton list with the whole string.

Parameters:

separator (Optional[str]) – Substring to split on. None = codepoint-wise.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_starts_with(prefix)

Register a starts-with read: True iff this bin starts with prefix.

Matching is Unicode canonical, not byte-exact: a prefix in a different normalization form than the stored value still matches.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_strlen()

Register a strlen read: Unicode codepoint count of this string bin.

Returns the codepoint count under this bin’s name (NOT the UTF-8 byte count — use str_byte_length() for bytes).

Example:

stream = await (
    session.upsert(key)
        .bin("greeting").set_to("héllo")
        .bin("greeting").str_strlen()
        .execute()
)
Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

See also

QueryBinBuilder.str_strlen(): Same read on a query builder. str_byte_length(): UTF-8 byte length instead of codepoint count.

str_substr(start, end=None)

Register a substr read.

With end omitted, returns codepoints from start to the end of the string. With end set, returns the half-open codepoint range [start, end). Negative start counts from the end. Out-of-bounds indexes are clamped — no error is raised.

Note

end is end-exclusive (NOT a length). To extract three codepoints starting at index 2, pass start=2, end=5.

Example:

stream = await (
    session.upsert(key)
        .bin("greeting").set_to("hello world")
        .bin("greeting").str_substr(0, 5)  # → "hello"
        .execute()
)
Parameters:
  • start (int) – Codepoint index to start at. Negative counts from end.

  • end (Optional[int]) – End-exclusive codepoint index. None means run to end.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_to_blob()

Register a to-blob read: UTF-8 bytes of this string bin as a blob.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_to_double()

Register a to-double read: parses this bin as float64.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_CONVERSION_FAILED) if the bin doesn’t parse as a double.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_to_integer()

Register a to-integer read: parses this bin as int64.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_CONVERSION_FAILED) if the bin doesn’t parse as an integer.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

Returns:

The parent builder, for chaining.

str_trim(*, flags=0)

Register a trim modify: strip whitespace from both ends of the bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_trim_end(*, flags=0)

Register a trim-end modify: strip whitespace from the end of the bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_trim_start(*, flags=0)

Register a trim-start modify: strip whitespace from the start of the bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

str_upper(*, flags=0)

Register an upper modify: uppercase the bin in place.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

touch(arg1, *more_keys)

Open a touch segment (TTL refresh).

Example::

await session.touch(key).execute()

Return type:

TypeVar(_WSB, bound= _WriteSegmentBuilderBase)

Returns:

WriteSegmentBuilder.

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(expression, *, ignore_op_failure=False, ignore_eval_failure=False, delete_if_null=False)

Write expression result only if bin already exists.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

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(expression, *, ignore_op_failure=False, ignore_eval_failure=False, delete_if_null=False)

Write expression result, creating or overwriting the bin.

Return type:

TypeVar(_W, bound= _SupportsBinWrites)

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

Bases: _WriteVerbs[_WriteSegmentBuilderBase], Generic[_T]

Per-bin reads and CDT navigation for QueryBuilder (and sync twin).

The type parameter is the parent builder type; the parent must implement add_operation. Use get() for whole-bin reads, select_from() for expression reads, on_map_* / on_list_* for paths, hll_* / bit_* for HyperLogLog and blob bit reads, then QueryBuilder.execute(). Write verbs delegate to the parent to chain writes after reads.

Example:

Read map keys and list size in a single query::

    stream = await (
        session.query(key)
            .bin("settings").on_map_key("theme").get_values()
            .bin("tags").list_size()
            .execute()
    )

See also

WriteBinBuilder: Per-bin write builder. CdtReadBuilder: Nested reads.

__init__(parent, bin_name)[source]
get()[source]

Include the bin value in the read result.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent builder for chaining.

See also

select_from(): Virtual bin from an expression.

map_size()[source]

Return the number of entries in the map.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

list_size()[source]

Read list length into the operate/read result.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

list_join(separator=None)[source]

Read the string items of the list concatenated into one string.

The list must hold only strings; any other element type fails with PARAMETER_ERROR. An empty list joins to an empty string. The inverse of str_split().

Parameters:

separator (Optional[str]) – Inserted between consecutive items. None = no separator.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent builder for chaining.

list_get(index)[source]

Read the list element at index into the query result.

Parameters:

index (int) – List index (0-based; negative counts from the end).

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent builder for chaining.

list_get_range(index, count=None)[source]

Read a contiguous slice of the list starting at index.

Parameters:
  • index (int) – Starting list index.

  • count (Optional[int]) – Number of elements; None reads through the end.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent builder for chaining.

See also

list_get()

hll_get_count()[source]

Read the estimated HyperLogLog cardinality for this bin.

The estimate appears under this bin’s name in the record returned from QueryBuilder.execute(). To read during a multi-op write, use WriteBinBuilder.hll_get_count().

Example::

stream = await session.query(key).bin(“visitors”).hll_get_count().execute()

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

hll_describe()[source]

Read index and min-hash bit parameters describing the stored sketch.

Example::

stream = await session.query(key).bin(“visitors”).hll_describe().execute()

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

hll_get_union(hll_list)[source]

Read the union sketch of this bin and hll_list without updating storage.

Example::

stream = await ( session.query(key).bin(“hll”).hll_get_union([peer_blob]).execute() )

Parameters:

hll_list (Sequence[Any]) – Other HLL blobs to include in the union result.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

hll_get_union_count(hll_list)[source]

Read the estimated cardinality of the union with other sketches.

Example::

stream = await ( session.query(key).bin(“hll”).hll_get_union_count([peer_blob]).execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches included in the union estimate.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

hll_get_intersect_count(hll_list)[source]

Read the estimated intersection cardinality with other sketches.

Example::

stream = await ( session.query(key) .bin(“hll”) .hll_get_intersect_count([peer_blob]) .execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches included in the intersection estimate.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

hll_get_similarity(hll_list)[source]

Read Jaccard similarity between this sketch and other sketches.

Example::

stream = await ( session.query(key).bin(“hll”).hll_get_similarity([peer_blob]).execute() )

Parameters:

hll_list (Sequence[Any]) – Other sketches to compare.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_get(bit_offset, bit_size)[source]

Read bit_size bits at bit_offset as raw bytes.

Example::

stream = await session.query(key).bin(“blob”).bit_get(0, 8).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to read.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_count(bit_offset, bit_size)[source]

Count bits set to 1 in the given range.

Example::

stream = await session.query(key).bin(“blob”).bit_count(0, 8).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_lscan(bit_offset, bit_size, value)[source]

Scan from the left for the first set (True) or unset (False) bit.

Example::

stream = await session.query(key).bin(“blob”).bit_lscan(0, 8, True).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

  • value (bool) – True to find a 1 bit, False to find a 0 bit.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_rscan(bit_offset, bit_size, value)[source]

Scan from the right for the first set (True) or unset (False) bit.

Example::

stream = await session.query(key).bin(“blob”).bit_rscan(0, 8, False).execute()

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Number of bits to scan.

  • value (bool) – True to find a 1 bit, False to find a 0 bit.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_get_int(bit_offset, bit_size, signed)[source]

Decode an integer from bit_size bits at bit_offset.

Example::

stream = await ( session.query(key).bin(“blob”).bit_get_int(0, 16, False).execute() )

Parameters:
  • bit_offset (int) – Starting bit index.

  • bit_size (int) – Width of the integer in bits.

  • signed (bool) – True for two’s-complement signed decoding.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

bit_b64_encode(byte_offset=None, byte_size=None, invert_size=False)[source]

Read this blob bin as base64 text, whole or by byte range.

Without a range the whole blob is encoded. With byte_offset and byte_size (required together) only that byte range is encoded; a negative byte_offset counts back from the end of the blob. When invert_size is True, byte_size counts back from the end instead, so an inverted size of 0 encodes through to the end.

Requires server 8.2.0 or later. The decode direction is WriteBinBuilder.str_b64_decode().

Example::

stream = await ( session.query(key).bin(“payload”).bit_b64_encode().execute() )

Parameters:
  • byte_offset (Optional[int]) – Starting byte index of the range; negative counts back from the end. Given together with byte_size.

  • byte_size (Optional[int]) – Byte count to encode (or, inverted, the count left off the end).

  • invert_size (bool) – True to measure byte_size back from the end of the blob.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent query builder for chaining.

Raises:

ValueError – If only one of byte_offset / byte_size is given, or invert_size is set without a range.

str_strlen()[source]

Read the Unicode codepoint count of this string bin (NOT byte count).

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_substr(start, end=None)[source]

Read codepoints from start to end (exclusive); or to bin end when end=None.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_char_at(index)[source]

Read the codepoint at index as a one-codepoint string.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_find(needle, occurrence=None)[source]

Read the codepoint index of the first (or N-th) occurrence of needle; -1 if absent.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_contains(needle)[source]

Read a bool: True iff this bin contains needle as a substring.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_starts_with(prefix)[source]

Read a bool: True iff this bin starts with prefix.

Matching is Unicode canonical, not byte-exact: a prefix in a different normalization form than the stored value still matches.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_ends_with(suffix)[source]

Read a bool: True iff this bin ends with suffix.

Matching is Unicode canonical, not byte-exact: a suffix in a different normalization form than the stored value still matches.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_to_integer()[source]

Parse this bin as an int64.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_CONVERSION_FAILED) on bad input.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_to_double()[source]

Parse this bin as a float64.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_CONVERSION_FAILED) on bad input.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_byte_length()[source]

Read the UTF-8 byte count of this string bin.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_is_numeric(numeric_type=None)[source]

Read a bool: True iff this bin parses as a number.

Pass numeric_type to restrict to StringNumericType.INT / StringNumericType.FLOAT; default ANY accepts either.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_is_upper()[source]

Read a bool: True iff every cased codepoint is uppercase.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_is_lower()[source]

Read a bool: True iff every cased codepoint is lowercase.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_to_blob()[source]

Read the UTF-8 bytes of this string bin as a blob.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_split(separator=None)[source]

Read a list of strings.

With separator=None returns one element per codepoint; with a separator returns the substrings between separator occurrences (singleton list when separator is absent).

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_b64_decode()[source]

Treat this bin as base64-encoded text; return the decoded bytes as a blob.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_B64_INVALID) if the bin is not valid base64.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

str_regex_compare(pattern, flags=0)[source]

Read a bool: True iff the ICU regex pattern matches this bin.

flags is an OR-combined StringRegexFlags bitmask.

Server returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_REGEX_LIMIT_EXCEEDED) if matching exceeds the server’s regex resource budget.

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

read_as_string()[source]

Convert any bin to its string representation.

Type-agnostic — the source bin need not be a string, which is why this method carries no str_ prefix (str_to_integer and friends genuinely require a string source). Accepts bool / int / float / string / blob source types; any other type returns BIN_TYPE_ERROR from the server, and a blob that is not valid UTF-8 returns OP_NOT_APPLICABLE (subcode SubCode.OPNOT_STRING_UTF8_INVALID).

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

select_from(expression, *, ignore_eval_failure=False)[source]

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

The result appears as a virtual bin in the returned record.

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

  • ignore_eval_failure (bool) – If True, silently return None when the expression cannot be evaluated (e.g. missing bin).

Return type:

TypeVar(_T, bound= _SupportsAddOperation)

Returns:

The parent builder for method chaining.

on_map_index(index)[source]

Navigate to a map element by index.

Parameters:

index (int) – List index (0-based, negative counts from end).

Return type:

CdtReadBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadBuilder for reading the targeted element(s).

on_each_child()[source]

Select every child of this bin, for a path read or modify.

Walks a whole level instead of one element, so the terminal applies across the selection: collect_values() reads them all, modify_by(expr) rewrites them all. Chain again to go deeper.

Example:

await session.update(key).bin("nums").on_each_child().modify_by(
    Exp.num_add([Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(10)])
).execute()
Return type:

CdtPathBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtPathBuilder for further navigation or a terminal.

on_each_child_where(predicate)[source]

Select the children matching predicate.

Parameters:

predicate (Any) – An Exp over the element’s loop variable, e.g. Exp.gt(Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(5)).

Return type:

CdtPathBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtPathBuilder for further navigation or a terminal.

on_map_keys_in(keys)[source]

Select the map entries whose key is in keys, for a path read.

Parameters:

keys (Iterable[Any]) – The map keys to select.

Return type:

CdtPathBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtPathBuilder for further navigation, an and_filter, or a terminal.

Raises:

TypeError – If keys is a bare str, bytes or bytearray rather than a collection of keys.

Example:

over_10 = Exp.gt(Exp.int_loop_var(LoopVarPart.VALUE), Exp.val(10))
result = await (
    await session.query(key)
    .bin("m").on_map_keys_in(["a", "b", "c"]).and_filter(over_10).collect_map_entries()
    .execute()
).first_or_raise()
on_map_key(key, *, create_type=None)[source]

Navigate to a map element by key.

Parameters:
  • key (Any) – Map key to target.

  • create_type (Optional[MapOrder]) – If set, use a create-on-missing context for this key with the given map key order.

Return type:

CdtReadBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadBuilder for reading the targeted element(s).

on_map_rank(rank)[source]

Navigate to a map element by rank (0 = lowest value).

Return type:

CdtReadBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_value(value)[source]

Navigate to map elements matching a value.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_index_range(index, count=None)[source]

Navigate to map elements by index range.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_key_range(start, end)[source]

Navigate to map elements by key range [start, end).

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_rank_range(rank, count=None)[source]

Navigate to map elements by rank range.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_value_range(start, end)[source]

Navigate to map elements by value range [start, end).

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_key_relative_index_range(key, index, count=None)[source]

Navigate to map entries by index range relative to an anchor key.

Parameters:
  • key (Any) – Map key to target.

  • index (int) – List index (0-based, negative counts from end).

  • count (Optional[int]) – Maximum entries to select; None for all remaining.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadInvertableBuilder for reading the targeted element(s).

on_map_value_relative_rank_range(value, rank, count=None)[source]

Navigate to map entries by value rank range relative to an anchor value.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_map_key_list(keys)[source]

Navigate to map elements matching a list of keys.

Parameters:

keys (List[Any]) – Map keys to match.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadInvertableBuilder for reading the matched elements.

Raises:

TypeError – If keys is a bare str, bytes or bytearray rather than a collection of keys.

on_map_value_list(values)[source]

Navigate to map elements matching a list of values.

Parameters:

values (List[Any]) – Values to match.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadInvertableBuilder for reading the matched elements.

Raises:

TypeError – If values is a bare str, bytes or bytearray rather than a collection of values.

on_list_index(index, *, order=None, pad=False)[source]

Navigate to a list element by index.

Parameters:
  • order (Optional[ListOrderType]) – If set (or if pad is True), use create-on-missing list context with this order; when only pad is True, defaults to UNORDERED.

  • pad (bool) – When using create-on-missing context, allow sparse indexes.

Return type:

CdtReadBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Example::

.bin(“items”).on_list_index(-1).get_values()

on_list_rank(rank)[source]

Navigate to a list element by rank (0 = lowest value).

Return type:

CdtReadBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_value(value)[source]

Navigate to list elements matching a value.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_index_range(index, count=None)[source]

Navigate to list elements by index range.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_rank_range(rank, count=None)[source]

Navigate to list elements by rank range.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_value_range(start, end)[source]

Navigate to list elements by value range [start, end).

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_value_relative_rank_range(value, rank, count=None)[source]

Navigate to list elements by value rank range relative to an anchor value.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

on_list_value_list(values)[source]

Navigate to list elements matching a list of values.

Parameters:

values (List[Any]) – Values to match.

Return type:

CdtReadInvertableBuilder[TypeVar(_T, bound= _SupportsAddOperation)]

Returns:

CdtReadInvertableBuilder for reading the matched elements.

Raises:

TypeError – If values is a bare str, bytes or bytearray rather than a collection of values.