Skip to content

Redis

The redis adapter provides a complete Redis integration including the concrete adapter, its abstract port interface, index-bound RediSearch handles, and a mock implementation for testing.

Ports

Abstract port interface defining the Redis adapter contract.

Redis port interfaces composed from per-concern mixins.

archipy.adapters.redis.ports.RedisScoreCastType module-attribute

RedisScoreCastType = type | Callable

archipy.adapters.redis.ports.RedisPort

Bases: RedisConnectionPort, RedisClusterPort, RedisKeysPort, RedisListsPort, RedisSetsPort, RedisSortedSetsPort, RedisArraysPort, RedisHashesPort, RedisPubSubPort

Interface for Redis operations providing a standardized access pattern.

Defines the contract for Redis adapters: key-value ops, collections (lists, sets, sorted sets, hashes), cluster admin, and pub/sub.

Source code in archipy/adapters/redis/ports.py
class RedisPort(
    RedisConnectionPort,
    RedisClusterPort,
    RedisKeysPort,
    RedisListsPort,
    RedisSetsPort,
    RedisSortedSetsPort,
    RedisArraysPort,
    RedisHashesPort,
    RedisPubSubPort,
):
    """Interface for Redis operations providing a standardized access pattern.

    Defines the contract for Redis adapters: key-value ops, collections
    (lists, sets, sorted sets, hashes), cluster admin, and pub/sub.
    """

archipy.adapters.redis.ports.RedisPort.publish abstractmethod

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publishes a message to a channel.

Parameters:

Name Type Description Default
channel bytes | str

The channel to publish to.

required
message bytes | str

The message to publish.

required
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType int

The number of subscribers that received the message.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publishes a message to a channel.

    Args:
        channel (bytes | str): The channel to publish to.
        message (bytes | str): The message to publish.
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: The number of subscribers that received the message.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.pubsub_channels abstractmethod

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Lists active channels matching a pattern.

Parameters:

Name Type Description Default
pattern bytes | str

The pattern to match channels. Defaults to "*".

'*'
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

A list of active channels.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Lists active channels matching a pattern.

    Args:
        pattern (bytes | str): The pattern to match channels. Defaults to "*".
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A list of active channels.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.pubsub abstractmethod

pubsub(**kwargs: Any) -> Any

Returns a pub/sub object for subscribing to channels.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
Any Any

A pub/sub object.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
def pubsub(self, **kwargs: Any) -> Any:
    """Returns a pub/sub object for subscribing to channels.

    Args:
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        Any: A pub/sub object.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hdel abstractmethod

hdel(name: str, *keys: str | bytes) -> int

Deletes one or more fields from a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hdel(self, name: str, *keys: str | bytes) -> int:
    """Deletes one or more fields from a hash.

    Args:
        name (str): The key of the hash.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: The number of fields deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hexists abstractmethod

hexists(name: str, key: str) -> bool

Checks if a field exists in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str

The field to check.

required

Returns:

Name Type Description
bool bool

True if the field exists, False otherwise.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hexists(self, name: str, key: str) -> bool:
    """Checks if a field exists in a hash.

    Args:
        name (str): The key of the hash.
        key (str): The field to check.

    Returns:
        bool: True if the field exists, False otherwise.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hget abstractmethod

hget(name: str, key: str) -> bytes | str | None

Gets the value of a field in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str

The field to get.

required

Returns:

Type Description
bytes | str | None

str | None: The value of the field, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hget(self, name: str, key: str) -> bytes | str | None:
    """Gets the value of a field in a hash.

    Args:
        name (str): The key of the hash.
        key (str): The field to get.

    Returns:
        str | None: The value of the field, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hgetall abstractmethod

hgetall(name: str) -> dict[bytes | str, bytes | str]

Gets all fields and values in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: A dictionary of field/value pairs.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Gets all fields and values in a hash.

    Args:
        name (str): The key of the hash.

    Returns:
        dict[str, Any]: A dictionary of field/value pairs.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hkeys abstractmethod

hkeys(name: str) -> list[bytes | str]

Gets all fields in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of fields in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hkeys(self, name: str) -> list[bytes | str]:
    """Gets all fields in a hash.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisListResponseType: A list of fields in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hlen abstractmethod

hlen(name: str) -> int

Gets the number of fields in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hlen(self, name: str) -> int:
    """Gets the number of fields in a hash.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisIntegerResponseType: The number of fields in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hset abstractmethod

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Sets one or more fields in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str | bytes

A single field to set.

None
value str | bytes

The value for the single field.

None
mapping dict

A dictionary of field/value pairs.

None
items list

A list of field/value pairs.

None

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields added or updated.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Sets one or more fields in a hash.

    Args:
        name (str): The key of the hash.
        key (str | bytes, optional): A single field to set.
        value (str | bytes, optional): The value for the single field.
        mapping (dict, optional): A dictionary of field/value pairs.
        items (list, optional): A list of field/value pairs.

    Returns:
        RedisIntegerResponseType: The number of fields added or updated.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hmget abstractmethod

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Gets the values of multiple fields in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
keys list

A list of fields to get.

required
*args str | bytes

Additional fields to get.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

A list of values for the specified fields.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Gets the values of multiple fields in a hash.

    Args:
        name (str): The key of the hash.
        keys (list): A list of fields to get.
        *args (str | bytes): Additional fields to get.

    Returns:
        RedisListResponseType: A list of values for the specified fields.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.hvals abstractmethod

hvals(name: str) -> list[bytes | str]

Gets all values in a hash.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of values in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
def hvals(self, name: str) -> list[bytes | str]:
    """Gets all values in a hash.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisListResponseType: A list of values in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.arset abstractmethod

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Sets one or more contiguous values in the array stored at a key.

Values are stored at consecutive indices beginning at index in the Redis 8.8 array data structure, an index-addressable, sparse-friendly container.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index (0 to 2**64-1) to set values at.

required
*values bytes | str | float

The values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Sets one or more contiguous values in the array stored at a key.

    Values are stored at consecutive indices beginning at ``index`` in the Redis 8.8 array data
    structure, an index-addressable, sparse-friendly container.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index (0 to 2**64-1) to set values at.
        *values (bytes | str | float): The values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.arget abstractmethod

arget(name: bytes | str, index: int) -> bytes | str | None

Gets the value at an index in the array stored at a key.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset or the key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Gets the value at an index in the array stored at a key.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset or the key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.arlen abstractmethod

arlen(name: bytes | str) -> int

Gets the number of populated elements in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
def arlen(self, name: bytes | str) -> int:
    """Gets the number of populated elements in an array.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.ardel abstractmethod

ardel(name: bytes | str, *indices: int) -> int

Deletes one or more indices from an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

The indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
def ardel(self, name: bytes | str, *indices: int) -> int:
    """Deletes one or more indices from an array.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): The indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.arring abstractmethod

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Inserts values into an array as a fixed-size ring buffer (sliding window).

Each value is placed at insert_idx % size, wrapping back to index 0 and overwriting older values once full, in a single atomic operation equivalent to RPUSH + LTRIM.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

The values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Inserts values into an array as a fixed-size ring buffer (sliding window).

    Each value is placed at ``insert_idx % size``, wrapping back to index 0 and overwriting
    older values once full, in a single atomic operation equivalent to ``RPUSH`` + ``LTRIM``.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): The values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zadd abstractmethod

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Adds members with scores to a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
mapping Mapping[bytes | str, bytes | str | float]

A mapping of members to scores.

required
nx bool

If True, only add new elements. Defaults to False.

False
xx bool

If True, only update existing elements. Defaults to False.

False
ch bool

If True, return the number of changed elements. Defaults to False.

False
incr bool

If True, increment scores instead of setting. Defaults to False.

False
gt bool

If True, only update if new score is greater. Defaults to False.

False
lt bool

If True, only update if new score is less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

The number of elements added or updated.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Adds members with scores to a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        mapping (Mapping[bytes | str, bytes | str | float]): A mapping of members to scores.
        nx (bool): If True, only add new elements. Defaults to False.
        xx (bool): If True, only update existing elements. Defaults to False.
        ch (bool): If True, return the number of changed elements. Defaults to False.
        incr (bool): If True, increment scores instead of setting. Defaults to False.
        gt (bool): If True, only update if new score is greater. Defaults to False.
        lt (bool): If True, only update if new score is less. Defaults to False.

    Returns:
        RedisResponseType: The number of elements added or updated.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zcard abstractmethod

zcard(name: bytes | str) -> int

Gets the number of members in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required

Returns:

Name Type Description
RedisResponseType int

The cardinality (size) of the sorted set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zcard(self, name: bytes | str) -> int:
    """Gets the number of members in a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.

    Returns:
        RedisResponseType: The cardinality (size) of the sorted set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zcount abstractmethod

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Counts members in a sorted set within a score range.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
min_ float | str

The minimum score (inclusive).

required
max_ float | str

The maximum score (inclusive).

required

Returns:

Name Type Description
RedisResponseType int

The number of members within the score range.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Counts members in a sorted set within a score range.

    Args:
        name (bytes | str): The key of the sorted set.
        min_ (float | str): The minimum score (inclusive).
        max_ (float | str): The maximum score (inclusive).

    Returns:
        RedisResponseType: The number of members within the score range.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zpopmax abstractmethod

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Removes and returns members with the highest scores from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of (member, score) tuples popped.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Removes and returns members with the highest scores from a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        RedisResponseType: A list of (member, score) tuples popped.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zpopmin abstractmethod

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Removes and returns members with the lowest scores from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of (member, score) tuples popped.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Removes and returns members with the lowest scores from a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        RedisResponseType: A list of (member, score) tuples popped.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zrange abstractmethod

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets a range of members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
start int

The starting index or score (depending on byscore).

required
end int

The ending index or score (depending on byscore).

required
desc bool

If True, sort in descending order. Defaults to False.

False
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float
byscore bool

If True, range by score instead of rank. Defaults to False.

False
bylex bool

If True, range by lexicographical order. Defaults to False.

False
offset int

Offset for byscore or bylex.

None
num int

Number of elements for byscore or bylex.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets a range of members from a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        start (int): The starting index or score (depending on byscore).
        end (int): The ending index or score (depending on byscore).
        desc (bool): If True, sort in descending order. Defaults to False.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.
        byscore (bool): If True, range by score instead of rank. Defaults to False.
        bylex (bool): If True, range by lexicographical order. Defaults to False.
        offset (int, optional): Offset for byscore or bylex.
        num (int, optional): Number of elements for byscore or bylex.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zrevrange abstractmethod

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets a range of members from a sorted set in reverse order.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
start int

The starting index.

required
end int

The ending index.

required
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets a range of members from a sorted set in reverse order.

    Args:
        name (bytes | str): The key of the sorted set.
        start (int): The starting index.
        end (int): The ending index.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zrangebyscore abstractmethod

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets members from a sorted set by score range.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
min_ float | str

The minimum score (inclusive).

required
max_ float | str

The maximum score (inclusive).

required
start int

Starting offset.

None
num int

Number of elements to return.

None
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets members from a sorted set by score range.

    Args:
        name (bytes | str): The key of the sorted set.
        min_ (float | str): The minimum score (inclusive).
        max_ (float | str): The maximum score (inclusive).
        start (int, optional): Starting offset.
        num (int, optional): Number of elements to return.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zrank abstractmethod

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Gets the rank of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
value bytes | str | float

The member to find.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

The rank (index) of the member, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Gets the rank of a member in a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        value (bytes | str | float): The member to find.

    Returns:
        RedisResponseType: The rank (index) of the member, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zrem abstractmethod

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Removes one or more members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

The number of members removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Removes one or more members from a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: The number of members removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zscore abstractmethod

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Gets the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
value bytes | str | float

The member to check.

required

Returns:

Name Type Description
RedisResponseType float | None

The score of the member, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Gets the score of a member in a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        value (bytes | str | float): The member to check.

    Returns:
        RedisResponseType: The score of the member, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zunion abstractmethod

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Computes the union of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str

How to combine scores across sets: "SUM", "MIN", "MAX", or the Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets containing it (or the sum of their weights, if weights are given). Defaults to "SUM".

None
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Computes the union of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str, optional): How to combine scores across sets: "SUM", "MIN", "MAX", or the
            Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets
            containing it (or the sum of their weights, if weights are given). Defaults to "SUM".
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zinter abstractmethod

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Computes the intersection of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str

How to combine scores across sets: "SUM", "MIN", "MAX", or the Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets containing it (or the sum of their weights, if weights are given). Defaults to "SUM".

None
withscores bool

If True, return scores with members. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Computes the intersection of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str, optional): How to combine scores across sets: "SUM", "MIN", "MAX", or the
            Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets
            containing it (or the sum of their weights, if weights are given). Defaults to "SUM".
        withscores (bool): If True, return scores with members. Defaults to False.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.zincrby abstractmethod

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increments the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
amount float

The amount to increment by.

required
value bytes | str | float

The member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

The new score of the member.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increments the score of a member in a sorted set.

    Args:
        name (bytes | str): The key of the sorted set.
        amount (float): The amount to increment by.
        value (bytes | str | float): The member to increment.

    Returns:
        RedisResponseType: The new score of the member.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.sscan abstractmethod

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Iterates over members of a set incrementally.

Parameters:

Name Type Description Default
name bytes | str

The key of the set.

required
cursor int

The cursor position to start scanning. Defaults to 0.

0
match bytes | str

Pattern to match members against.

None
count int

Hint for number of members to return per iteration.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

A tuple of (new_cursor, list_of_members).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Iterates over members of a set incrementally.

    Args:
        name (bytes | str): The key of the set.
        cursor (int): The cursor position to start scanning. Defaults to 0.
        match (bytes | str, optional): Pattern to match members against.
        count (int, optional): Hint for number of members to return per iteration.

    Returns:
        RedisResponseType: A tuple of (new_cursor, list_of_members).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.sscan_iter abstractmethod

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]

Provides an iterator over members of a set.

Parameters:

Name Type Description Default
name bytes | str

The key of the set.

required
match bytes | str

Pattern to match members against.

None
count int

Hint for number of members to return per iteration.

None

Returns:

Name Type Description
Iterator Iterator[bytes | str]

An iterator yielding set members.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]:
    """Provides an iterator over members of a set.

    Args:
        name (bytes | str): The key of the set.
        match (bytes | str, optional): Pattern to match members against.
        count (int, optional): Hint for number of members to return per iteration.

    Returns:
        Iterator: An iterator yielding set members.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.sadd abstractmethod

sadd(name: str, *values: bytes | str | float) -> int

Adds one or more members to a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of members added (excluding duplicates).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Adds one or more members to a set.

    Args:
        name (str): The key of the set.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: The number of members added (excluding duplicates).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.scard abstractmethod

scard(name: str) -> int

Gets the number of members in a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The cardinality (size) of the set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def scard(self, name: str) -> int:
    """Gets the number of members in a set.

    Args:
        name (str): The key of the set.

    Returns:
        RedisIntegerResponseType: The cardinality (size) of the set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.sismember abstractmethod

sismember(name: str, value: str) -> bool

Checks if a value is a member of a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required
value str

The value to check.

required

Returns:

Name Type Description
bool bool

True if the value is a member, False otherwise.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def sismember(self, name: str, value: str) -> bool:
    """Checks if a value is a member of a set.

    Args:
        name (str): The key of the set.
        value (str): The value to check.

    Returns:
        bool: True if the value is a member, False otherwise.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.smembers abstractmethod

smembers(name: str) -> _set[bytes | str]

Gets all members of a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

A set of all members.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def smembers(self, name: str) -> _set[bytes | str]:
    """Gets all members of a set.

    Args:
        name (str): The key of the set.

    Returns:
        RedisSetResponseType: A set of all members.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.spop abstractmethod

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Removes and returns one or more random members from a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: The popped member(s), or None if the set is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Removes and returns one or more random members from a set.

    Args:
        name (str): The key of the set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        bytes | float | int | str | list | None: The popped member(s), or None if the set is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.srem abstractmethod

srem(name: str, *values: bytes | str | float) -> int

Removes one or more members from a set.

Parameters:

Name Type Description Default
name str

The key of the set.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of members removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def srem(self, name: str, *values: bytes | str | float) -> int:
    """Removes one or more members from a set.

    Args:
        name (str): The key of the set.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: The number of members removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.sunion abstractmethod

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Gets the union of multiple sets.

Parameters:

Name Type Description Default
keys bytes | str

Name of the first key.

required
*args bytes | str

Additional key names.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

A set containing members of the resulting union.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Gets the union of multiple sets.

    Args:
        keys (bytes | str): Name of the first key.
        *args (bytes | str): Additional key names.

    Returns:
        RedisSetResponseType: A set containing members of the resulting union.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.llen abstractmethod

llen(name: str) -> int

Gets the length of a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of items in the list.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def llen(self, name: str) -> int:
    """Gets the length of a list.

    Args:
        name (str): The key of the list.

    Returns:
        RedisIntegerResponseType: The number of items in the list.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.lpop abstractmethod

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Removes and returns the first element(s) of a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of elements to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

The popped element(s), or None if the list is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Removes and returns the first element(s) of a list.

    Args:
        name (str): The key of the list.
        count (int, optional): Number of elements to pop. Defaults to None (pops 1).

    Returns:
        Any: The popped element(s), or None if the list is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.lpush abstractmethod

lpush(name: str, *values: bytes | str | float) -> int

Pushes one or more values to the start of a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The length of the list after the push.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Pushes one or more values to the start of a list.

    Args:
        name (str): The key of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: The length of the list after the push.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.lrange abstractmethod

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Gets a range of elements from a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
start int

The starting index (inclusive).

required
end int

The ending index (inclusive).

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of elements in the specified range.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Gets a range of elements from a list.

    Args:
        name (str): The key of the list.
        start (int): The starting index (inclusive).
        end (int): The ending index (inclusive).

    Returns:
        RedisListResponseType: A list of elements in the specified range.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.lrem abstractmethod

lrem(name: str, count: int, value: str) -> int

Removes occurrences of a value from a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of occurrences to remove (0 for all).

required
value str

The value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of elements removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def lrem(self, name: str, count: int, value: str) -> int:
    """Removes occurrences of a value from a list.

    Args:
        name (str): The key of the list.
        count (int): Number of occurrences to remove (0 for all).
        value (str): The value to remove.

    Returns:
        RedisIntegerResponseType: The number of elements removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.lset abstractmethod

lset(name: str, index: int, value: str) -> bool

Sets the value of an element in a list by index.

Parameters:

Name Type Description Default
name str

The key of the list.

required
index int

The index to set.

required
value str

The new value.

required

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def lset(self, name: str, index: int, value: str) -> bool:
    """Sets the value of an element in a list by index.

    Args:
        name (str): The key of the list.
        index (int): The index to set.
        value (str): The new value.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.rpop abstractmethod

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Removes and returns the last element(s) of a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of elements to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

The popped element(s), or None if the list is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Removes and returns the last element(s) of a list.

    Args:
        name (str): The key of the list.
        count (int, optional): Number of elements to pop. Defaults to None (pops 1).

    Returns:
        Any: The popped element(s), or None if the list is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.rpush abstractmethod

rpush(name: str, *values: bytes | str | float) -> int

Pushes one or more values to the end of a list.

Parameters:

Name Type Description Default
name str

The key of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The length of the list after the push.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Pushes one or more values to the end of a list.

    Args:
        name (str): The key of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: The length of the list after the push.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.pttl abstractmethod

pttl(name: bytes | str) -> int

Gets the remaining time to live of a key in milliseconds.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType int

The time to live in milliseconds, or -1 if no TTL, -2 if key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def pttl(self, name: bytes | str) -> int:
    """Gets the remaining time to live of a key in milliseconds.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The time to live in milliseconds, or -1 if no TTL, -2 if key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.incrby abstractmethod

incrby(name: bytes | str, amount: int = 1) -> int

Increments the integer value of a key by the given amount.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
amount int

The amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after incrementing.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increments the integer value of a key by the given amount.

    Args:
        name (bytes | str): The key to increment.
        amount (int): The amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after incrementing.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.increx abstractmethod

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increments a windowed counter with bounds and expiration control (window counter rate limiter).

This wraps the Redis 8.8 INCREX command, a generalized form of INCR/INCRBY/ INCRBYFLOAT with added support for value bounds and conditional expiration, making it suitable for implementing rate limiters directly on the server.

Parameters:

Name Type Description Default
name bytes | str

The key to increment. Created if it doesn't already exist.

required
byfloat float

Increment amount as a float. Mutually exclusive with byint.

None
byint int

Increment amount as an int. Defaults to 1 if neither is set.

None
lbound float | int

Lower bound the resulting value must satisfy.

None
ubound float | int

Upper bound the resulting value must satisfy (token capacity).

None
saturate bool

If True, clamp out-of-bounds results to the bound instead of rejecting the request. Defaults to False.

False
ex int | timedelta

Expiration time in seconds.

None
px int | timedelta

Expiration time in milliseconds.

None
exat int | datetime

Absolute expiration time in seconds.

None
pxat int | datetime

Absolute expiration time in milliseconds.

None
persist bool

If True, remove any existing expiration. Defaults to False.

False
enx bool

If True, set the expiration only when the key does not already have one, preserving the window's original TTL. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increments a windowed counter with bounds and expiration control (window counter rate limiter).

    This wraps the Redis 8.8 ``INCREX`` command, a generalized form of ``INCR``/``INCRBY``/
    ``INCRBYFLOAT`` with added support for value bounds and conditional expiration, making it
    suitable for implementing rate limiters directly on the server.

    Args:
        name (bytes | str): The key to increment. Created if it doesn't already exist.
        byfloat (float, optional): Increment amount as a float. Mutually exclusive with byint.
        byint (int, optional): Increment amount as an int. Defaults to 1 if neither is set.
        lbound (float | int, optional): Lower bound the resulting value must satisfy.
        ubound (float | int, optional): Upper bound the resulting value must satisfy (token capacity).
        saturate (bool): If True, clamp out-of-bounds results to the bound instead of rejecting
            the request. Defaults to False.
        ex (int | timedelta, optional): Expiration time in seconds.
        px (int | timedelta, optional): Expiration time in milliseconds.
        exat (int | datetime, optional): Absolute expiration time in seconds.
        pxat (int | datetime, optional): Absolute expiration time in milliseconds.
        persist (bool): If True, remove any existing expiration. Defaults to False.
        enx (bool): If True, set the expiration only when the key does not already have one,
            preserving the window's original TTL. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of ``[new_value, actual_increment_applied]``.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.set abstractmethod

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Sets a key to a value with optional expiration and conditions.

Parameters:

Name Type Description Default
name bytes | str

The key to set.

required
value int | bytes | str | float

The value to set for the key.

required
ex int | timedelta

Expiration time in seconds or timedelta.

None
px int | timedelta

Expiration time in milliseconds or timedelta.

None
nx bool

If True, set only if the key does not exist. Defaults to False.

False
xx bool

If True, set only if the key already exists. Defaults to False.

False
keepttl bool

If True, retain the existing TTL. Defaults to False.

False
get bool

If True, return the old value before setting. Defaults to False.

False
exat int | datetime

Absolute expiration time as Unix timestamp or datetime.

None
pxat int | datetime

Absolute expiration time in milliseconds or datetime.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

The result of the operation, often "OK" or the old value if get=True.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Sets a key to a value with optional expiration and conditions.

    Args:
        name (bytes | str): The key to set.
        value (int | bytes | str | float): The value to set for the key.
        ex (int | timedelta, optional): Expiration time in seconds or timedelta.
        px (int | timedelta, optional): Expiration time in milliseconds or timedelta.
        nx (bool): If True, set only if the key does not exist. Defaults to False.
        xx (bool): If True, set only if the key already exists. Defaults to False.
        keepttl (bool): If True, retain the existing TTL. Defaults to False.
        get (bool): If True, return the old value before setting. Defaults to False.
        exat (int | datetime, optional): Absolute expiration time as Unix timestamp or datetime.
        pxat (int | datetime, optional): Absolute expiration time in milliseconds or datetime.

    Returns:
        RedisResponseType: The result of the operation, often "OK" or the old value if get=True.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.get abstractmethod

get(key: str) -> bytes | str | None

Retrieves the value of a key.

Parameters:

Name Type Description Default
key str

The key to retrieve.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value associated with the key, or None if the key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def get(self, key: str) -> bytes | str | None:
    """Retrieves the value of a key.

    Args:
        key (str): The key to retrieve.

    Returns:
        RedisResponseType: The value associated with the key, or None if the key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.mget abstractmethod

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Gets the values of multiple keys.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

A single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

A list of values corresponding to the keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Gets the values of multiple keys.

    Args:
        keys (bytes | str | Iterable[bytes | str]): A single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: A list of values corresponding to the keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.mset abstractmethod

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Sets multiple keys to their respective values.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

A mapping of keys to values.

required

Returns:

Name Type Description
RedisResponseType bool

Typically "OK" on success.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Sets multiple keys to their respective values.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): A mapping of keys to values.

    Returns:
        RedisResponseType: Typically "OK" on success.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.keys abstractmethod

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Returns all keys matching a pattern.

Parameters:

Name Type Description Default
pattern bytes | str

The pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

A list of matching keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Returns all keys matching a pattern.

    Args:
        pattern (bytes | str): The pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A list of matching keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.getset abstractmethod

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Sets a key to a value and returns its old value.

Parameters:

Name Type Description Default
key bytes | str

The key to set.

required
value bytes | str | float

The new value to set.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The old value of the key, or None if it didn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Sets a key to a value and returns its old value.

    Args:
        key (bytes | str): The key to set.
        value (bytes | str | float): The new value to set.

    Returns:
        RedisResponseType: The old value of the key, or None if it didn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.getdel abstractmethod

getdel(key: bytes | str) -> bytes | str | None

Gets the value of a key and deletes it.

Parameters:

Name Type Description Default
key bytes | str

The key to get and delete.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key before deletion, or None if it didn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def getdel(self, key: bytes | str) -> bytes | str | None:
    """Gets the value of a key and deletes it.

    Args:
        key (bytes | str): The key to get and delete.

    Returns:
        RedisResponseType: The value of the key before deletion, or None if it didn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.exists abstractmethod

exists(*names: bytes | str) -> int

Checks if one or more keys exist.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of keys to check.

()

Returns:

Name Type Description
RedisResponseType int

The number of keys that exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def exists(self, *names: bytes | str) -> int:
    """Checks if one or more keys exist.

    Args:
        *names (bytes | str): Variable number of keys to check.

    Returns:
        RedisResponseType: The number of keys that exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.delete abstractmethod

delete(*names: bytes | str) -> int

Deletes one or more keys.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of keys to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of keys deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def delete(self, *names: bytes | str) -> int:
    """Deletes one or more keys.

    Args:
        *names (bytes | str): Variable number of keys to delete.

    Returns:
        RedisResponseType: The number of keys deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.append abstractmethod

append(key: bytes | str, value: bytes | str | float) -> int

Appends a value to a key's string value.

Parameters:

Name Type Description Default
key bytes | str

The key to append to.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

The length of the string after appending.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Appends a value to a key's string value.

    Args:
        key (bytes | str): The key to append to.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: The length of the string after appending.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.ttl abstractmethod

ttl(name: bytes | str) -> int

Gets the remaining time to live of a key in seconds.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType int

The time to live in seconds, or -1 if no TTL, -2 if key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def ttl(self, name: bytes | str) -> int:
    """Gets the remaining time to live of a key in seconds.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The time to live in seconds, or -1 if no TTL, -2 if key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.type abstractmethod

type(name: bytes | str) -> bytes | str

Determines the type of value stored at a key.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType bytes | str

The type of the key's value (e.g., "string", "list", etc.).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def type(self, name: bytes | str) -> bytes | str:
    """Determines the type of value stored at a key.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The type of the key's value (e.g., "string", "list", etc.).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.scan abstractmethod

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Iterates over keys in the database incrementally.

Parameters:

Name Type Description Default
cursor int

The cursor position to start scanning. Defaults to 0.

0
match bytes | str

Pattern to match keys against.

None
count int

Hint for number of keys to return per iteration.

None
_type str

Filter by type (e.g., "string", "list").

None
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

A tuple of (new_cursor, list_of_keys).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Iterates over keys in the database incrementally.

    Args:
        cursor (int): The cursor position to start scanning. Defaults to 0.
        match (bytes | str, optional): Pattern to match keys against.
        count (int, optional): Hint for number of keys to return per iteration.
        _type (str, optional): Filter by type (e.g., "string", "list").
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A tuple of (new_cursor, list_of_keys).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.scan_iter abstractmethod

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]

Provides an iterator over keys in the database.

Parameters:

Name Type Description Default
match bytes | str

Pattern to match keys against.

None
count int

Hint for number of keys to return per iteration.

None
_type str

Filter by type (e.g., "string", "list").

None
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
Iterator Iterator[bytes | str]

An iterator yielding keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]:
    """Provides an iterator over keys in the database.

    Args:
        match (bytes | str, optional): Pattern to match keys against.
        count (int, optional): Hint for number of keys to return per iteration.
        _type (str, optional): Filter by type (e.g., "string", "list").
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        Iterator: An iterator yielding keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.cluster_info

cluster_info() -> dict[str, str] | None

Get cluster information.

Returns:

Name Type Description
RedisResponseType dict[str, str] | None

Cluster information or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information.

    Returns:
        RedisResponseType: Cluster information or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.cluster_nodes

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information.

Returns:

Name Type Description
RedisResponseType dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None

Cluster nodes info or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information.

    Returns:
        RedisResponseType: Cluster nodes info or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.cluster_slots

cluster_slots() -> list[Any] | None

Get cluster slots mapping.

Returns:

Name Type Description
RedisResponseType list[Any] | None

Slots mapping or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping.

    Returns:
        RedisResponseType: Slots mapping or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.cluster_key_slot

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key.

Parameters:

Name Type Description Default
key str

The key to get slot for.

required

Returns:

Name Type Description
RedisResponseType int | None

Key slot or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key.

    Args:
        key (str): The key to get slot for.

    Returns:
        RedisResponseType: Key slot or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.cluster_count_keys_in_slot

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot.

Parameters:

Name Type Description Default
slot int

The slot number.

required

Returns:

Name Type Description
RedisResponseType int | None

Key count or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot.

    Args:
        slot (int): The slot number.

    Returns:
        RedisResponseType: Key count or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.cluster_get_keys_in_slot

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot.

Parameters:

Name Type Description Default
slot int

The slot number.

required
count int

Maximum number of keys to return.

required

Returns:

Name Type Description
RedisResponseType list[bytes | str] | None

List of keys or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot.

    Args:
        slot (int): The slot number.
        count (int): Maximum number of keys to return.

    Returns:
        RedisResponseType: List of keys or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.RedisPort.ping abstractmethod

ping() -> bool

Tests the connection to the Redis server.

Returns:

Name Type Description
RedisResponseType bool

The response from the server, typically "PONG".

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def ping(self) -> bool:
    """Tests the connection to the Redis server.

    Returns:
        RedisResponseType: The response from the server, typically "PONG".

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.flushdb abstractmethod

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.get_pipeline abstractmethod

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> Any

Returns a pipeline object for batching commands.

Parameters:

Name Type Description Default
transaction Any

If True, execute commands in a transaction. Defaults to True.

True
shard_hint Any

Hint for sharding in clustered Redis.

None

Returns:

Name Type Description
Any Any

A pipeline object.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def get_pipeline(self, transaction: Any = True, shard_hint: Any = None) -> Any:
    """Returns a pipeline object for batching commands.

    Args:
        transaction (Any): If True, execute commands in a transaction. Defaults to True.
        shard_hint (Any, optional): Hint for sharding in clustered Redis.

    Returns:
        Any: A pipeline object.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.config_set abstractmethod

config_set(name: str, value: str) -> bool

Sets a Redis server configuration parameter.

Commonly used to enable keyspace/subkey notifications via notify-keyspace-events.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def config_set(self, name: str, value: str) -> bool:
    """Sets a Redis server configuration parameter.

    Commonly used to enable keyspace/subkey notifications via ``notify-keyspace-events``.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.config_get abstractmethod

config_get(pattern: str = '*') -> dict[str, str]

Gets Redis server configuration parameters matching a pattern.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

A dictionary of configuration parameter names to values.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Gets Redis server configuration parameters matching a pattern.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: A dictionary of configuration parameter names to values.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.RedisPort.search_index abstractmethod

search_index(name: str) -> RedisSearchHandlePort

Return an index-bound RediSearch handle.

Parameters:

Name Type Description Default
name str

RediSearch index name.

required

Returns:

Name Type Description
RedisSearchHandlePort RedisSearchHandlePort

Handle for index-scoped RediSearch operations.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def search_index(self, name: str) -> RedisSearchHandlePort:
    """Return an index-bound RediSearch handle.

    Args:
        name: RediSearch index name.

    Returns:
        RedisSearchHandlePort: Handle for index-scoped RediSearch operations.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort

Bases: AsyncRedisConnectionPort, AsyncRedisClusterPort, AsyncRedisKeysPort, AsyncRedisListsPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, AsyncRedisArraysPort, AsyncRedisHashesPort, AsyncRedisPubSubPort

Async interface for Redis operations providing a standardized access pattern.

Async counterpart of RedisPort: same surface, async methods throughout.

Source code in archipy/adapters/redis/ports.py
class AsyncRedisPort(
    AsyncRedisConnectionPort,
    AsyncRedisClusterPort,
    AsyncRedisKeysPort,
    AsyncRedisListsPort,
    AsyncRedisSetsPort,
    AsyncRedisSortedSetsPort,
    AsyncRedisArraysPort,
    AsyncRedisHashesPort,
    AsyncRedisPubSubPort,
):
    """Async interface for Redis operations providing a standardized access pattern.

    Async counterpart of RedisPort: same surface, async methods throughout.
    """

archipy.adapters.redis.ports.AsyncRedisPort.publish abstractmethod async

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publishes a message to a channel asynchronously.

Parameters:

Name Type Description Default
channel bytes | str

The channel to publish to.

required
message bytes | str

The message to publish.

required
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType int

The number of subscribers that received the message.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
async def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publishes a message to a channel asynchronously.

    Args:
        channel (bytes | str): The channel to publish to.
        message (bytes | str): The message to publish.
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: The number of subscribers that received the message.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.pubsub_channels abstractmethod async

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Lists active channels matching a pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

The pattern to match channels. Defaults to "*".

'*'
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

A list of active channels.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
async def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Lists active channels matching a pattern asynchronously.

    Args:
        pattern (bytes | str): The pattern to match channels. Defaults to "*".
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A list of active channels.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.pubsub abstractmethod async

pubsub(**kwargs: Any) -> Any

Returns a pub/sub object for subscribing to channels asynchronously.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
Any Any

A pub/sub object.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/pubsub.py
@abstractmethod
async def pubsub(self, **kwargs: Any) -> Any:
    """Returns a pub/sub object for subscribing to channels asynchronously.

    Args:
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        Any: A pub/sub object.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hdel abstractmethod async

hdel(name: str, *keys: str | bytes) -> int

Deletes one or more fields from a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hdel(self, name: str, *keys: str | bytes) -> int:
    """Deletes one or more fields from a hash asynchronously.

    Args:
        name (str): The key of the hash.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: The number of fields deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hexists abstractmethod async

hexists(name: str, key: str) -> bool

Checks if a field exists in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str

The field to check.

required

Returns:

Name Type Description
bool bool

True if the field exists, False otherwise.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hexists(self, name: str, key: str) -> bool:
    """Checks if a field exists in a hash asynchronously.

    Args:
        name (str): The key of the hash.
        key (str): The field to check.

    Returns:
        bool: True if the field exists, False otherwise.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hget abstractmethod async

hget(name: str, key: str) -> bytes | str | None

Gets the value of a field in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str

The field to get.

required

Returns:

Type Description
bytes | str | None

str | None: The value of the field, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hget(self, name: str, key: str) -> bytes | str | None:
    """Gets the value of a field in a hash asynchronously.

    Args:
        name (str): The key of the hash.
        key (str): The field to get.

    Returns:
        str | None: The value of the field, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hgetall abstractmethod async

hgetall(name: str) -> dict[bytes | str, bytes | str]

Gets all fields and values in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: A dictionary of field/value pairs.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Gets all fields and values in a hash asynchronously.

    Args:
        name (str): The key of the hash.

    Returns:
        dict[str, Any]: A dictionary of field/value pairs.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hkeys abstractmethod async

hkeys(name: str) -> list[bytes | str]

Gets all fields in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of fields in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hkeys(self, name: str) -> list[bytes | str]:
    """Gets all fields in a hash asynchronously.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisListResponseType: A list of fields in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hlen abstractmethod async

hlen(name: str) -> int

Gets the number of fields in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hlen(self, name: str) -> int:
    """Gets the number of fields in a hash asynchronously.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisIntegerResponseType: The number of fields in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hset abstractmethod async

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Sets one or more fields in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
key str | bytes

A single field to set.

None
value str | bytes

The value for the single field.

None
mapping dict

A dictionary of field/value pairs.

None
items list

A list of field/value pairs.

None

Returns:

Name Type Description
RedisIntegerResponseType int

The number of fields added or updated.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Sets one or more fields in a hash asynchronously.

    Args:
        name (str): The key of the hash.
        key (str | bytes, optional): A single field to set.
        value (str | bytes, optional): The value for the single field.
        mapping (dict, optional): A dictionary of field/value pairs.
        items (list, optional): A list of field/value pairs.

    Returns:
        RedisIntegerResponseType: The number of fields added or updated.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hmget abstractmethod async

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Gets the values of multiple fields in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required
keys list

A list of fields to get.

required
*args str | bytes

Additional fields to get.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

A list of values for the specified fields.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Gets the values of multiple fields in a hash asynchronously.

    Args:
        name (str): The key of the hash.
        keys (list): A list of fields to get.
        *args (str | bytes): Additional fields to get.

    Returns:
        RedisListResponseType: A list of values for the specified fields.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.hvals abstractmethod async

hvals(name: str) -> list[bytes | str]

Gets all values in a hash asynchronously.

Parameters:

Name Type Description Default
name str

The key of the hash.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of values in the hash.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/hashes.py
@abstractmethod
async def hvals(self, name: str) -> list[bytes | str]:
    """Gets all values in a hash asynchronously.

    Args:
        name (str): The key of the hash.

    Returns:
        RedisListResponseType: A list of values in the hash.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.arset abstractmethod async

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Sets one or more contiguous values in the array stored at a key asynchronously.

Values are stored at consecutive indices beginning at index in the Redis 8.8 array data structure, an index-addressable, sparse-friendly container.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index (0 to 2**64-1) to set values at.

required
*values bytes | str | float

The values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
async def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Sets one or more contiguous values in the array stored at a key asynchronously.

    Values are stored at consecutive indices beginning at ``index`` in the Redis 8.8 array data
    structure, an index-addressable, sparse-friendly container.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index (0 to 2**64-1) to set values at.
        *values (bytes | str | float): The values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.arget abstractmethod async

arget(name: bytes | str, index: int) -> bytes | str | None

Gets the value at an index in the array stored at a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset or the key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
async def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Gets the value at an index in the array stored at a key asynchronously.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset or the key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.arlen abstractmethod async

arlen(name: bytes | str) -> int

Gets the number of populated elements in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
async def arlen(self, name: bytes | str) -> int:
    """Gets the number of populated elements in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.ardel abstractmethod async

ardel(name: bytes | str, *indices: int) -> int

Deletes one or more indices from an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

The indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
async def ardel(self, name: bytes | str, *indices: int) -> int:
    """Deletes one or more indices from an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): The indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.arring abstractmethod async

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Inserts values into an array as a fixed-size ring buffer (sliding window) asynchronously.

Each value is placed at insert_idx % size, wrapping back to index 0 and overwriting older values once full, in a single atomic operation equivalent to RPUSH + LTRIM.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

The values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/arrays.py
@abstractmethod
async def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Inserts values into an array as a fixed-size ring buffer (sliding window) asynchronously.

    Each value is placed at ``insert_idx % size``, wrapping back to index 0 and overwriting
    older values once full, in a single atomic operation equivalent to ``RPUSH`` + ``LTRIM``.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): The values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zadd abstractmethod async

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Adds members with scores to a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
mapping Mapping[bytes | str, bytes | str | float]

A mapping of members to scores.

required
nx bool

If True, only add new elements. Defaults to False.

False
xx bool

If True, only update existing elements. Defaults to False.

False
ch bool

If True, return the number of changed elements. Defaults to False.

False
incr bool

If True, increment scores instead of setting. Defaults to False.

False
gt bool

If True, only update if new score is greater. Defaults to False.

False
lt bool

If True, only update if new score is less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

The number of elements added or updated.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Adds members with scores to a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        mapping (Mapping[bytes | str, bytes | str | float]): A mapping of members to scores.
        nx (bool): If True, only add new elements. Defaults to False.
        xx (bool): If True, only update existing elements. Defaults to False.
        ch (bool): If True, return the number of changed elements. Defaults to False.
        incr (bool): If True, increment scores instead of setting. Defaults to False.
        gt (bool): If True, only update if new score is greater. Defaults to False.
        lt (bool): If True, only update if new score is less. Defaults to False.

    Returns:
        RedisResponseType: The number of elements added or updated.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zcard abstractmethod async

zcard(name: bytes | str) -> int

Gets the number of members in a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required

Returns:

Name Type Description
RedisResponseType int

The cardinality (size) of the sorted set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zcard(self, name: bytes | str) -> int:
    """Gets the number of members in a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.

    Returns:
        RedisResponseType: The cardinality (size) of the sorted set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zcount abstractmethod async

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Counts members in a sorted set within a score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
min_ float | str

The minimum score (inclusive).

required
max_ float | str

The maximum score (inclusive).

required

Returns:

Name Type Description
RedisResponseType int

The number of members within the score range.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Counts members in a sorted set within a score range asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        min_ (float | str): The minimum score (inclusive).
        max_ (float | str): The maximum score (inclusive).

    Returns:
        RedisResponseType: The number of members within the score range.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zpopmax abstractmethod async

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Removes and returns members with the highest scores from a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of (member, score) tuples popped.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Removes and returns members with the highest scores from a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        RedisResponseType: A list of (member, score) tuples popped.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zpopmin abstractmethod async

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Removes and returns members with the lowest scores from a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of (member, score) tuples popped.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Removes and returns members with the lowest scores from a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        RedisResponseType: A list of (member, score) tuples popped.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zrange abstractmethod async

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets a range of members from a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
start int

The starting index or score (depending on byscore).

required
end int

The ending index or score (depending on byscore).

required
desc bool

If True, sort in descending order. Defaults to False.

False
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float
byscore bool

If True, range by score instead of rank. Defaults to False.

False
bylex bool

If True, range by lexicographical order. Defaults to False.

False
offset int

Offset for byscore or bylex.

None
num int

Number of elements for byscore or bylex.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets a range of members from a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        start (int): The starting index or score (depending on byscore).
        end (int): The ending index or score (depending on byscore).
        desc (bool): If True, sort in descending order. Defaults to False.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.
        byscore (bool): If True, range by score instead of rank. Defaults to False.
        bylex (bool): If True, range by lexicographical order. Defaults to False.
        offset (int, optional): Offset for byscore or bylex.
        num (int, optional): Number of elements for byscore or bylex.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zrevrange abstractmethod async

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets a range of members from a sorted set in reverse order asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
start int

The starting index.

required
end int

The ending index.

required
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets a range of members from a sorted set in reverse order asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        start (int): The starting index.
        end (int): The ending index.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zrangebyscore abstractmethod async

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Gets members from a sorted set by score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
min_ float | str

The minimum score (inclusive).

required
max_ float | str

The maximum score (inclusive).

required
start int

Starting offset.

None
num int

Number of elements to return.

None
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Gets members from a sorted set by score range asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        min_ (float | str): The minimum score (inclusive).
        max_ (float | str): The maximum score (inclusive).
        start (int, optional): Starting offset.
        num (int, optional): Number of elements to return.
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zrank abstractmethod async

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Gets the rank of a member in a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
value bytes | str | float

The member to find.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

The rank (index) of the member, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Gets the rank of a member in a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        value (bytes | str | float): The member to find.

    Returns:
        RedisResponseType: The rank (index) of the member, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zrem abstractmethod async

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Removes one or more members from a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

The number of members removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Removes one or more members from a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: The number of members removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zscore abstractmethod async

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Gets the score of a member in a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
value bytes | str | float

The member to check.

required

Returns:

Name Type Description
RedisResponseType float | None

The score of the member, or None if not found.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Gets the score of a member in a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        value (bytes | str | float): The member to check.

    Returns:
        RedisResponseType: The score of the member, or None if not found.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zunion abstractmethod async

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Computes the union of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str

How to combine scores across sets: "SUM", "MIN", "MAX", or the Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets containing it (or the sum of their weights, if weights are given). Defaults to "SUM".

None
withscores bool

If True, return scores with members. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Computes the union of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str, optional): How to combine scores across sets: "SUM", "MIN", "MAX", or the
            Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets
            containing it (or the sum of their weights, if weights are given). Defaults to "SUM".
        withscores (bool): If True, return scores with members. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zinter abstractmethod async

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Computes the intersection of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str

How to combine scores across sets: "SUM", "MIN", "MAX", or the Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets containing it (or the sum of their weights, if weights are given). Defaults to "SUM".

None
withscores bool

If True, return scores with members. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

A list of members (and scores if withscores=True).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Computes the intersection of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str, optional): How to combine scores across sets: "SUM", "MIN", "MAX", or the
            Redis 8.8 "COUNT" aggregator, which scores each element by the number of input sets
            containing it (or the sum of their weights, if weights are given). Defaults to "SUM".
        withscores (bool): If True, return scores with members. Defaults to False.

    Returns:
        RedisResponseType: A list of members (and scores if withscores=True).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.zincrby abstractmethod async

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increments the score of a member in a sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the sorted set.

required
amount float

The amount to increment by.

required
value bytes | str | float

The member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

The new score of the member.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sorted_sets.py
@abstractmethod
async def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increments the score of a member in a sorted set asynchronously.

    Args:
        name (bytes | str): The key of the sorted set.
        amount (float): The amount to increment by.
        value (bytes | str | float): The member to increment.

    Returns:
        RedisResponseType: The new score of the member.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.sscan abstractmethod async

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Iterates over members of a set incrementally asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the set.

required
cursor int

The cursor position to start scanning. Defaults to 0.

0
match bytes | str

Pattern to match members against.

None
count int

Hint for number of members to return per iteration.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

A tuple of (new_cursor, list_of_members).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Iterates over members of a set incrementally asynchronously.

    Args:
        name (bytes | str): The key of the set.
        cursor (int): The cursor position to start scanning. Defaults to 0.
        match (bytes | str, optional): Pattern to match members against.
        count (int, optional): Hint for number of members to return per iteration.

    Returns:
        RedisResponseType: A tuple of (new_cursor, list_of_members).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.sscan_iter abstractmethod async

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]

Provides an iterator over members of a set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the set.

required
match bytes | str

Pattern to match members against.

None
count int

Hint for number of members to return per iteration.

None

Returns:

Name Type Description
Iterator AsyncIterator[bytes | str]

An iterator yielding set members.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]:
    """Provides an iterator over members of a set asynchronously.

    Args:
        name (bytes | str): The key of the set.
        match (bytes | str, optional): Pattern to match members against.
        count (int, optional): Hint for number of members to return per iteration.

    Returns:
        Iterator: An iterator yielding set members.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.sadd abstractmethod async

sadd(name: str, *values: bytes | str | float) -> int

Adds one or more members to a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of members added (excluding duplicates).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Adds one or more members to a set asynchronously.

    Args:
        name (str): The key of the set.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: The number of members added (excluding duplicates).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.scard abstractmethod async

scard(name: str) -> int

Gets the number of members in a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The cardinality (size) of the set.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def scard(self, name: str) -> int:
    """Gets the number of members in a set asynchronously.

    Args:
        name (str): The key of the set.

    Returns:
        RedisIntegerResponseType: The cardinality (size) of the set.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.sismember abstractmethod async

sismember(name: str, value: str) -> bool

Checks if a value is a member of a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required
value str

The value to check.

required

Returns:

Name Type Description
bool bool

True if the value is a member, False otherwise.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def sismember(self, name: str, value: str) -> bool:
    """Checks if a value is a member of a set asynchronously.

    Args:
        name (str): The key of the set.
        value (str): The value to check.

    Returns:
        bool: True if the value is a member, False otherwise.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.smembers abstractmethod async

smembers(name: str) -> _set[bytes | str]

Gets all members of a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

A set of all members.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def smembers(self, name: str) -> _set[bytes | str]:
    """Gets all members of a set asynchronously.

    Args:
        name (str): The key of the set.

    Returns:
        RedisSetResponseType: A set of all members.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.spop abstractmethod async

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Removes and returns one or more random members from a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required
count int

Number of members to pop. Defaults to None (pops 1).

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: The popped member(s), or None if the set is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Removes and returns one or more random members from a set asynchronously.

    Args:
        name (str): The key of the set.
        count (int, optional): Number of members to pop. Defaults to None (pops 1).

    Returns:
        bytes | float | int | str | list | None: The popped member(s), or None if the set is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.srem abstractmethod async

srem(name: str, *values: bytes | str | float) -> int

Removes one or more members from a set asynchronously.

Parameters:

Name Type Description Default
name str

The key of the set.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The number of members removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def srem(self, name: str, *values: bytes | str | float) -> int:
    """Removes one or more members from a set asynchronously.

    Args:
        name (str): The key of the set.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: The number of members removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.sunion abstractmethod async

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Gets the union of multiple sets asynchronously.

Parameters:

Name Type Description Default
keys bytes | str

Name of the first key.

required
*args bytes | str

Additional key names.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

A set containing members of the resulting union.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/sets.py
@abstractmethod
async def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Gets the union of multiple sets asynchronously.

    Args:
        keys (bytes | str): Name of the first key.
        *args (bytes | str): Additional key names.

    Returns:
        RedisSetResponseType: A set containing members of the resulting union.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.llen abstractmethod async

llen(name: str) -> int

Gets the length of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of items in the list.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def llen(self, name: str) -> int:
    """Gets the length of a list asynchronously.

    Args:
        name (str): The key of the list.

    Returns:
        RedisIntegerResponseType: The number of items in the list.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.lpop abstractmethod async

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Removes and returns the first element(s) of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of elements to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

The popped element(s), or None if the list is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Removes and returns the first element(s) of a list asynchronously.

    Args:
        name (str): The key of the list.
        count (int, optional): Number of elements to pop. Defaults to None (pops 1).

    Returns:
        Any: The popped element(s), or None if the list is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.lpush abstractmethod async

lpush(name: str, *values: bytes | str | float) -> int

Pushes one or more values to the start of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The length of the list after the push.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Pushes one or more values to the start of a list asynchronously.

    Args:
        name (str): The key of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: The length of the list after the push.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.lrange abstractmethod async

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Gets a range of elements from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
start int

The starting index (inclusive).

required
end int

The ending index (inclusive).

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

A list of elements in the specified range.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Gets a range of elements from a list asynchronously.

    Args:
        name (str): The key of the list.
        start (int): The starting index (inclusive).
        end (int): The ending index (inclusive).

    Returns:
        RedisListResponseType: A list of elements in the specified range.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.lrem abstractmethod async

lrem(name: str, count: int, value: str) -> int

Removes occurrences of a value from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of occurrences to remove (0 for all).

required
value str

The value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

The number of elements removed.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def lrem(self, name: str, count: int, value: str) -> int:
    """Removes occurrences of a value from a list asynchronously.

    Args:
        name (str): The key of the list.
        count (int): Number of occurrences to remove (0 for all).
        value (str): The value to remove.

    Returns:
        RedisIntegerResponseType: The number of elements removed.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.lset abstractmethod async

lset(name: str, index: int, value: str) -> bool

Sets the value of an element in a list by index asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
index int

The index to set.

required
value str

The new value.

required

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def lset(self, name: str, index: int, value: str) -> bool:
    """Sets the value of an element in a list by index asynchronously.

    Args:
        name (str): The key of the list.
        index (int): The index to set.
        value (str): The new value.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.rpop abstractmethod async

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Removes and returns the last element(s) of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
count int

Number of elements to pop. Defaults to None (pops 1).

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

The popped element(s), or None if the list is empty.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Removes and returns the last element(s) of a list asynchronously.

    Args:
        name (str): The key of the list.
        count (int, optional): Number of elements to pop. Defaults to None (pops 1).

    Returns:
        Any: The popped element(s), or None if the list is empty.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.rpush abstractmethod async

rpush(name: str, *values: bytes | str | float) -> int

Pushes one or more values to the end of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

The length of the list after the push.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/lists.py
@abstractmethod
async def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Pushes one or more values to the end of a list asynchronously.

    Args:
        name (str): The key of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: The length of the list after the push.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.pttl abstractmethod async

pttl(name: bytes | str) -> int

Gets the remaining time to live of a key in milliseconds asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType int

The time to live in milliseconds, or -1 if no TTL, -2 if key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def pttl(self, name: bytes | str) -> int:
    """Gets the remaining time to live of a key in milliseconds asynchronously.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The time to live in milliseconds, or -1 if no TTL, -2 if key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.incrby abstractmethod async

incrby(name: bytes | str, amount: int = 1) -> int

Increments the integer value of a key by the given amount asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
amount int

The amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after incrementing.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increments the integer value of a key by the given amount asynchronously.

    Args:
        name (bytes | str): The key to increment.
        amount (int): The amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after incrementing.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.increx abstractmethod async

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increments a windowed counter with bounds and expiration control (window counter rate limiter).

This wraps the Redis 8.8 INCREX command, a generalized form of INCR/INCRBY/ INCRBYFLOAT with added support for value bounds and conditional expiration, making it suitable for implementing rate limiters directly on the server.

Parameters:

Name Type Description Default
name bytes | str

The key to increment. Created if it doesn't already exist.

required
byfloat float

Increment amount as a float. Mutually exclusive with byint.

None
byint int

Increment amount as an int. Defaults to 1 if neither is set.

None
lbound float | int

Lower bound the resulting value must satisfy.

None
ubound float | int

Upper bound the resulting value must satisfy (token capacity).

None
saturate bool

If True, clamp out-of-bounds results to the bound instead of rejecting the request. Defaults to False.

False
ex int | timedelta

Expiration time in seconds.

None
px int | timedelta

Expiration time in milliseconds.

None
exat int | datetime

Absolute expiration time in seconds.

None
pxat int | datetime

Absolute expiration time in milliseconds.

None
persist bool

If True, remove any existing expiration. Defaults to False.

False
enx bool

If True, set the expiration only when the key does not already have one, preserving the window's original TTL. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increments a windowed counter with bounds and expiration control (window counter rate limiter).

    This wraps the Redis 8.8 ``INCREX`` command, a generalized form of ``INCR``/``INCRBY``/
    ``INCRBYFLOAT`` with added support for value bounds and conditional expiration, making it
    suitable for implementing rate limiters directly on the server.

    Args:
        name (bytes | str): The key to increment. Created if it doesn't already exist.
        byfloat (float, optional): Increment amount as a float. Mutually exclusive with byint.
        byint (int, optional): Increment amount as an int. Defaults to 1 if neither is set.
        lbound (float | int, optional): Lower bound the resulting value must satisfy.
        ubound (float | int, optional): Upper bound the resulting value must satisfy (token capacity).
        saturate (bool): If True, clamp out-of-bounds results to the bound instead of rejecting
            the request. Defaults to False.
        ex (int | timedelta, optional): Expiration time in seconds.
        px (int | timedelta, optional): Expiration time in milliseconds.
        exat (int | datetime, optional): Absolute expiration time in seconds.
        pxat (int | datetime, optional): Absolute expiration time in milliseconds.
        persist (bool): If True, remove any existing expiration. Defaults to False.
        enx (bool): If True, set the expiration only when the key does not already have one,
            preserving the window's original TTL. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of ``[new_value, actual_increment_applied]``.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.set abstractmethod async

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Sets a key to a value with optional expiration and conditions asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to set.

required
value int | bytes | str | float

The value to set for the key.

required
ex int | timedelta

Expiration time in seconds or timedelta.

None
px int | timedelta

Expiration time in milliseconds or timedelta.

None
nx bool

If True, set only if the key does not exist. Defaults to False.

False
xx bool

If True, set only if the key already exists. Defaults to False.

False
keepttl bool

If True, retain the existing TTL. Defaults to False.

False
get bool

If True, return the old value before setting. Defaults to False.

False
exat int | datetime

Absolute expiration time as Unix timestamp or datetime.

None
pxat int | datetime

Absolute expiration time in milliseconds or datetime.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

The result of the operation, often "OK" or the old value if get=True.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Sets a key to a value with optional expiration and conditions asynchronously.

    Args:
        name (bytes | str): The key to set.
        value (int | bytes | str | float): The value to set for the key.
        ex (int | timedelta, optional): Expiration time in seconds or timedelta.
        px (int | timedelta, optional): Expiration time in milliseconds or timedelta.
        nx (bool): If True, set only if the key does not exist. Defaults to False.
        xx (bool): If True, set only if the key already exists. Defaults to False.
        keepttl (bool): If True, retain the existing TTL. Defaults to False.
        get (bool): If True, return the old value before setting. Defaults to False.
        exat (int | datetime, optional): Absolute expiration time as Unix timestamp or datetime.
        pxat (int | datetime, optional): Absolute expiration time in milliseconds or datetime.

    Returns:
        RedisResponseType: The result of the operation, often "OK" or the old value if get=True.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.get abstractmethod async

get(key: str) -> bytes | str | None

Retrieves the value of a key asynchronously.

Parameters:

Name Type Description Default
key str

The key to retrieve.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value associated with the key, or None if the key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def get(self, key: str) -> bytes | str | None:
    """Retrieves the value of a key asynchronously.

    Args:
        key (str): The key to retrieve.

    Returns:
        RedisResponseType: The value associated with the key, or None if the key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.mget abstractmethod async

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Gets the values of multiple keys asynchronously.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

A single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

A list of values corresponding to the keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Gets the values of multiple keys asynchronously.

    Args:
        keys (bytes | str | Iterable[bytes | str]): A single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: A list of values corresponding to the keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.mset abstractmethod async

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Sets multiple keys to their respective values asynchronously.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

A mapping of keys to values.

required

Returns:

Name Type Description
RedisResponseType bool

Typically "OK" on success.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Sets multiple keys to their respective values asynchronously.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): A mapping of keys to values.

    Returns:
        RedisResponseType: Typically "OK" on success.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.keys abstractmethod async

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Returns all keys matching a pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

The pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

A list of matching keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Returns all keys matching a pattern asynchronously.

    Args:
        pattern (bytes | str): The pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A list of matching keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.getset abstractmethod async

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Sets a key to a value and returns its old value asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key to set.

required
value bytes | str | float

The new value to set.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The old value of the key, or None if it didn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Sets a key to a value and returns its old value asynchronously.

    Args:
        key (bytes | str): The key to set.
        value (bytes | str | float): The new value to set.

    Returns:
        RedisResponseType: The old value of the key, or None if it didn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.getdel abstractmethod async

getdel(key: bytes | str) -> bytes | str | None

Gets the value of a key and deletes it asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key to get and delete.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key before deletion, or None if it didn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def getdel(self, key: bytes | str) -> bytes | str | None:
    """Gets the value of a key and deletes it asynchronously.

    Args:
        key (bytes | str): The key to get and delete.

    Returns:
        RedisResponseType: The value of the key before deletion, or None if it didn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.exists abstractmethod async

exists(*names: bytes | str) -> int

Checks if one or more keys exist asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of keys to check.

()

Returns:

Name Type Description
RedisResponseType int

The number of keys that exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def exists(self, *names: bytes | str) -> int:
    """Checks if one or more keys exist asynchronously.

    Args:
        *names (bytes | str): Variable number of keys to check.

    Returns:
        RedisResponseType: The number of keys that exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.delete abstractmethod async

delete(*names: bytes | str) -> int

Deletes one or more keys asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of keys to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of keys deleted.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def delete(self, *names: bytes | str) -> int:
    """Deletes one or more keys asynchronously.

    Args:
        *names (bytes | str): Variable number of keys to delete.

    Returns:
        RedisResponseType: The number of keys deleted.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.append abstractmethod async

append(key: bytes | str, value: bytes | str | float) -> int

Appends a value to a key's string value asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key to append to.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

The length of the string after appending.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Appends a value to a key's string value asynchronously.

    Args:
        key (bytes | str): The key to append to.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: The length of the string after appending.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.ttl abstractmethod async

ttl(name: bytes | str) -> int

Gets the remaining time to live of a key in seconds asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType int

The time to live in seconds, or -1 if no TTL, -2 if key doesn't exist.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def ttl(self, name: bytes | str) -> int:
    """Gets the remaining time to live of a key in seconds asynchronously.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The time to live in seconds, or -1 if no TTL, -2 if key doesn't exist.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.type abstractmethod async

type(name: bytes | str) -> bytes | str

Determines the type of value stored at a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to check.

required

Returns:

Name Type Description
RedisResponseType bytes | str

The type of the key's value (e.g., "string", "list", etc.).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def type(self, name: bytes | str) -> bytes | str:
    """Determines the type of value stored at a key asynchronously.

    Args:
        name (bytes | str): The key to check.

    Returns:
        RedisResponseType: The type of the key's value (e.g., "string", "list", etc.).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.scan abstractmethod async

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Iterates over keys in the database incrementally asynchronously.

Parameters:

Name Type Description Default
cursor int

The cursor position to start scanning. Defaults to 0.

0
match bytes | str

Pattern to match keys against.

None
count int

Hint for number of keys to return per iteration.

None
_type str

Filter by type (e.g., "string", "list").

None
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

A tuple of (new_cursor, list_of_keys).

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Iterates over keys in the database incrementally asynchronously.

    Args:
        cursor (int): The cursor position to start scanning. Defaults to 0.
        match (bytes | str, optional): Pattern to match keys against.
        count (int, optional): Hint for number of keys to return per iteration.
        _type (str, optional): Filter by type (e.g., "string", "list").
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        RedisResponseType: A tuple of (new_cursor, list_of_keys).

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.scan_iter abstractmethod async

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]

Provides an iterator over keys in the database asynchronously.

Parameters:

Name Type Description Default
match bytes | str

Pattern to match keys against.

None
count int

Hint for number of keys to return per iteration.

None
_type str

Filter by type (e.g., "string", "list").

None
**kwargs Any

Additional arguments for the underlying implementation.

{}

Returns:

Name Type Description
Iterator AsyncIterator[bytes | str]

An iterator yielding keys.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/keys.py
@abstractmethod
async def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]:
    """Provides an iterator over keys in the database asynchronously.

    Args:
        match (bytes | str, optional): Pattern to match keys against.
        count (int, optional): Hint for number of keys to return per iteration.
        _type (str, optional): Filter by type (e.g., "string", "list").
        **kwargs (Any): Additional arguments for the underlying implementation.

    Returns:
        Iterator: An iterator yielding keys.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.cluster_info async

cluster_info() -> dict[str, str] | None

Get cluster information asynchronously.

Returns:

Name Type Description
RedisResponseType dict[str, str] | None

Cluster information or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information asynchronously.

    Returns:
        RedisResponseType: Cluster information or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.cluster_nodes async

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information asynchronously.

Returns:

Name Type Description
RedisResponseType dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None

Cluster nodes info or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information asynchronously.

    Returns:
        RedisResponseType: Cluster nodes info or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.cluster_slots async

cluster_slots() -> list[Any] | None

Get cluster slots mapping asynchronously.

Returns:

Name Type Description
RedisResponseType list[Any] | None

Slots mapping or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping asynchronously.

    Returns:
        RedisResponseType: Slots mapping or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.cluster_key_slot async

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key asynchronously.

Parameters:

Name Type Description Default
key str

The key to get slot for.

required

Returns:

Name Type Description
RedisResponseType int | None

Key slot or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key asynchronously.

    Args:
        key (str): The key to get slot for.

    Returns:
        RedisResponseType: Key slot or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.cluster_count_keys_in_slot async

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot asynchronously.

Parameters:

Name Type Description Default
slot int

The slot number.

required

Returns:

Name Type Description
RedisResponseType int | None

Key count or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot asynchronously.

    Args:
        slot (int): The slot number.

    Returns:
        RedisResponseType: Key count or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.cluster_get_keys_in_slot async

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot asynchronously.

Parameters:

Name Type Description Default
slot int

The slot number.

required
count int

Maximum number of keys to return.

required

Returns:

Name Type Description
RedisResponseType list[bytes | str] | None

List of keys or None for standalone mode.

Source code in archipy/adapters/redis/port_mixins/cluster.py
async def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot asynchronously.

    Args:
        slot (int): The slot number.
        count (int): Maximum number of keys to return.

    Returns:
        RedisResponseType: List of keys or None for standalone mode.
    """
    return None

archipy.adapters.redis.ports.AsyncRedisPort.ping abstractmethod async

ping() -> bool

Tests the connection to the Redis server asynchronously.

Returns:

Name Type Description
RedisResponseType bool

The response from the server, typically "PONG".

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
async def ping(self) -> bool:
    """Tests the connection to the Redis server asynchronously.

    Returns:
        RedisResponseType: The response from the server, typically "PONG".

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.flushdb abstractmethod async

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database asynchronously.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
async def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database asynchronously.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.get_pipeline abstractmethod async

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> Any

Returns a pipeline object for batching commands asynchronously.

Parameters:

Name Type Description Default
transaction Any

If True, execute commands in a transaction. Defaults to True.

True
shard_hint Any

Hint for sharding in clustered Redis.

None

Returns:

Name Type Description
Any Any

A pipeline object.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
async def get_pipeline(self, transaction: Any = True, shard_hint: Any = None) -> Any:
    """Returns a pipeline object for batching commands asynchronously.

    Args:
        transaction (Any): If True, execute commands in a transaction. Defaults to True.
        shard_hint (Any, optional): Hint for sharding in clustered Redis.

    Returns:
        Any: A pipeline object.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.config_set abstractmethod async

config_set(name: str, value: str) -> bool

Sets a Redis server configuration parameter asynchronously.

Commonly used to enable keyspace/subkey notifications via notify-keyspace-events.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
async def config_set(self, name: str, value: str) -> bool:
    """Sets a Redis server configuration parameter asynchronously.

    Commonly used to enable keyspace/subkey notifications via ``notify-keyspace-events``.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.config_get abstractmethod async

config_get(pattern: str = '*') -> dict[str, str]

Gets Redis server configuration parameters matching a pattern asynchronously.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

A dictionary of configuration parameter names to values.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
async def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Gets Redis server configuration parameters matching a pattern asynchronously.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: A dictionary of configuration parameter names to values.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

archipy.adapters.redis.ports.AsyncRedisPort.search_index abstractmethod

search_index(name: str) -> AsyncRedisSearchHandlePort

Return an index-bound async RediSearch handle.

Parameters:

Name Type Description Default
name str

RediSearch index name.

required

Returns:

Name Type Description
AsyncRedisSearchHandlePort AsyncRedisSearchHandlePort

Handle for index-scoped async RediSearch operations.

Raises:

Type Description
NotImplementedError

If not implemented by the subclass.

Source code in archipy/adapters/redis/port_mixins/connection.py
@abstractmethod
def search_index(self, name: str) -> AsyncRedisSearchHandlePort:
    """Return an index-bound async RediSearch handle.

    Args:
        name: RediSearch index name.

    Returns:
        AsyncRedisSearchHandlePort: Handle for index-scoped async RediSearch operations.

    Raises:
        NotImplementedError: If not implemented by the subclass.
    """
    raise NotImplementedError

options: show_root_toc_entry: false heading_level: 3

Adapters

Concrete Redis adapter wrapping the Redis client with ArchiPy conventions for cache operations, pub/sub, and key-value management.

Redis adapters composed from per-concern mixins.

archipy.adapters.redis.adapters.RedisAdapter

Bases: RedisConnectionMixin, RedisClusterMixin, RedisKeysMixin, RedisListsMixin, RedisSetsMixin, RedisSortedSetsMixin, RedisArraysMixin, RedisHashesMixin, RedisPubSubMixin, RedisPort

Adapter for Redis operations providing a standardized interface.

Implements RedisPort over sync redis-py clients. Maintains separate read/write clients for replica-friendly deployments.

Parameters:

Name Type Description Default
redis_config RedisConfig | None

Redis settings. Uses global config when None.

None
Source code in archipy/adapters/redis/adapters.py
class RedisAdapter(
    RedisConnectionMixin,
    RedisClusterMixin,
    RedisKeysMixin,
    RedisListsMixin,
    RedisSetsMixin,
    RedisSortedSetsMixin,
    RedisArraysMixin,
    RedisHashesMixin,
    RedisPubSubMixin,
    RedisPort,
):
    """Adapter for Redis operations providing a standardized interface.

    Implements RedisPort over sync redis-py clients. Maintains separate
    read/write clients for replica-friendly deployments.

    Args:
        redis_config: Redis settings. Uses global config when None.
    """

archipy.adapters.redis.adapters.RedisAdapter.client instance-attribute

client: Redis | RedisCluster

archipy.adapters.redis.adapters.RedisAdapter.read_only_client instance-attribute

read_only_client: Redis | RedisCluster

archipy.adapters.redis.adapters.RedisAdapter.publish

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publish a message to a channel.

Parameters:

Name Type Description Default
channel bytes | str

Channel name.

required
message bytes | str

Message to publish.

required
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType int

Number of subscribers that received the message.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publish a message to a channel.

    Args:
        channel (bytes | str): Channel name.
        message (bytes | str): Message to publish.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Number of subscribers that received the message.
    """
    return self.client.publish(channel, message, **kwargs)

archipy.adapters.redis.adapters.RedisAdapter.pubsub_channels

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

List active channels matching a pattern.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match channels. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of channel names.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """List active channels matching a pattern.

    Args:
        pattern (bytes | str): Pattern to match channels. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of channel names.
    """
    return self.client.pubsub_channels(pattern, **kwargs)

archipy.adapters.redis.adapters.RedisAdapter.pubsub

pubsub(**kwargs: Any) -> PubSub

Get a PubSub object for subscribing to channels.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
PubSub PubSub

PubSub object.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def pubsub(self, **kwargs: Any) -> PubSub:
    """Get a PubSub object for subscribing to channels.

    Args:
        **kwargs (Any): Additional arguments.

    Returns:
        PubSub: PubSub object.
    """
    return self.client.pubsub(**kwargs)

archipy.adapters.redis.adapters.RedisAdapter.hdel

hdel(name: str, *keys: str | bytes) -> int

Delete fields from a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields deleted.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hdel(self, name: str, *keys: str | bytes) -> int:
    """Delete fields from a hash.

    Args:
        name (str): The hash key name.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: Number of fields deleted.
    """
    # Convert keys to str for type compatibility with Redis client
    str_keys: tuple[str, ...] = tuple(str(k) if isinstance(k, bytes) else k for k in keys)
    result = self.client.hdel(name, *str_keys)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.hexists

hexists(name: str, key: str) -> bool

Check if a field exists in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to check.

required

Returns:

Name Type Description
bool bool

True if field exists, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hexists(self, name: str, key: str) -> bool:
    """Check if a field exists in a hash.

    Args:
        name (str): The hash key name.
        key (str): Field to check.

    Returns:
        bool: True if field exists, False otherwise.
    """
    result = self.read_only_client.hexists(name, key)
    return bool(result)

archipy.adapters.redis.adapters.RedisAdapter.hget

hget(name: str, key: str) -> bytes | str | None

Get the value of a field in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to get.

required

Returns:

Type Description
bytes | str | None

str | None: Value of the field or None.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hget(self, name: str, key: str) -> bytes | str | None:
    """Get the value of a field in a hash.

    Args:
        name (str): The hash key name.
        key (str): Field to get.

    Returns:
        str | None: Value of the field or None.
    """
    return self.read_only_client.hget(name, key)

archipy.adapters.redis.adapters.RedisAdapter.hgetall

hgetall(name: str) -> dict[bytes | str, bytes | str]

Get all fields and values in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: Dictionary of field-value pairs.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Get all fields and values in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        dict[str, Any]: Dictionary of field-value pairs.
    """
    result = self.read_only_client.hgetall(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    if result:
        return {str(k): v for k, v in result.items()}
    return {}

archipy.adapters.redis.adapters.RedisAdapter.hkeys

hkeys(name: str) -> list[bytes | str]

Get all fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of field names.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hkeys(self, name: str) -> list[bytes | str]:
    """Get all fields in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of field names.
    """
    result = self.read_only_client.hkeys(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.adapters.RedisAdapter.hlen

hlen(name: str) -> int

Get the number of fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hlen(self, name: str) -> int:
    """Get the number of fields in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisIntegerResponseType: Number of fields.
    """
    result = self.read_only_client.hlen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.hset

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Set fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str | bytes | None

Single field name. Defaults to None.

None
value str | bytes | None

Single field value. Defaults to None.

None
mapping dict | None

Dictionary of field-value pairs. Defaults to None.

None
items list | None

List of field-value pairs. Defaults to None.

None

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields set.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Set fields in a hash.

    Args:
        name (str): The hash key name.
        key (str | bytes | None): Single field name. Defaults to None.
        value (str | bytes | None): Single field value. Defaults to None.
        mapping (dict | None): Dictionary of field-value pairs. Defaults to None.
        items (list | None): List of field-value pairs. Defaults to None.

    Returns:
        RedisIntegerResponseType: Number of fields set.
    """
    # Convert bytes to str for type compatibility with Redis client
    str_key: str | None = str(key) if key is not None and isinstance(key, bytes) else key
    str_value: str | None = str(value) if value is not None and isinstance(value, bytes) else value
    result = self.client.hset(name, str_key, str_value, mapping, items)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.hmget

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Get values of multiple fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
keys list

List of field names.

required
*args str | bytes

Additional field names.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

List of field values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Get values of multiple fields in a hash.

    Args:
        name (str): The hash key name.
        keys (list): List of field names.
        *args (str | bytes): Additional field names.

    Returns:
        RedisListResponseType: List of field values.
    """
    # Convert keys list and args for type compatibility, combine into single list
    keys_list: list[str] = [str(k) for k in keys] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.read_only_client.hmget(name, keys_list)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.adapters.RedisAdapter.hvals

hvals(name: str) -> list[bytes | str]

Get all values in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hvals(self, name: str) -> list[bytes | str]:
    """Get all values in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of values.
    """
    result = self.read_only_client.hvals(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.adapters.RedisAdapter.arset

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Set one or more contiguous values in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index to set values at.

required
*values bytes | str | float

Values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Set one or more contiguous values in an array.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index to set values at.
        *values (bytes | str | float): Values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.
    """
    result = self.client.arset(name, index, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.arget

arget(name: bytes | str, index: int) -> bytes | str | None

Get the value at an index in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Get the value at an index in an array.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset.
    """
    return self.read_only_client.arget(name, index)

archipy.adapters.redis.adapters.RedisAdapter.arlen

arlen(name: bytes | str) -> int

Get the number of populated elements in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arlen(self, name: bytes | str) -> int:
    """Get the number of populated elements in an array.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.
    """
    result = self.read_only_client.arlen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.ardel

ardel(name: bytes | str, *indices: int) -> int

Delete one or more indices from an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

Indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def ardel(self, name: bytes | str, *indices: int) -> int:
    """Delete one or more indices from an array.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): Indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.
    """
    result = self.client.ardel(name, *indices)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.arring

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Insert values into an array as a fixed-size ring buffer.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

Values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Insert values into an array as a fixed-size ring buffer.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): Values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.
    """
    result = self.client.arring(name, size, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.zadd

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Add members to a sorted set with scores.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
mapping Mapping[bytes | str, bytes | str | float]

Member-score pairs.

required
nx bool

Only add new elements. Defaults to False.

False
xx bool

Only update existing elements. Defaults to False.

False
ch bool

Return number of changed elements. Defaults to False.

False
incr bool

Increment existing scores. Defaults to False.

False
gt bool

Only update if score is greater. Defaults to False.

False
lt bool

Only update if score is less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

Number of elements added or modified.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Add members to a sorted set with scores.

    Args:
        name (bytes | str): The sorted set key name.
        mapping (Mapping[bytes | str, bytes | str | float]): Member-score pairs.
        nx (bool): Only add new elements. Defaults to False.
        xx (bool): Only update existing elements. Defaults to False.
        ch (bool): Return number of changed elements. Defaults to False.
        incr (bool): Increment existing scores. Defaults to False.
        gt (bool): Only update if score is greater. Defaults to False.
        lt (bool): Only update if score is less. Defaults to False.

    Returns:
        RedisResponseType: Number of elements added or modified.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    str_name = str(name)
    return self.client.zadd(str_name, dict_mapping, nx, xx, ch, incr, gt, lt)

archipy.adapters.redis.adapters.RedisAdapter.zcard

zcard(name: bytes | str) -> int

Get the number of members in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required

Returns:

Name Type Description
RedisResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zcard(self, name: bytes | str) -> int:
    """Get the number of members in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.

    Returns:
        RedisResponseType: Number of members.
    """
    return self.client.zcard(name)

archipy.adapters.redis.adapters.RedisAdapter.zcount

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Count members in a sorted set with scores in range.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required

Returns:

Name Type Description
RedisResponseType int

Number of members in range.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Count members in a sorted set with scores in range.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.

    Returns:
        RedisResponseType: Number of members in range.
    """
    return self.client.zcount(name, min_, max_)

archipy.adapters.redis.adapters.RedisAdapter.zpopmax

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Remove and return members with highest scores from sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Remove and return members with highest scores from sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return self.client.zpopmax(name, count)

archipy.adapters.redis.adapters.RedisAdapter.zpopmin

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Remove and return members with lowest scores from sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Remove and return members with lowest scores from sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return self.client.zpopmin(name, count)

archipy.adapters.redis.adapters.RedisAdapter.zrange

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get a range of members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index or score.

required
end int

End index or score.

required
desc bool

Sort in descending order. Defaults to False.

False
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float
byscore bool

Range by score. Defaults to False.

False
bylex bool

Range by lexicographical order. Defaults to False.

False
offset int | None

Offset for byscore/bylex. Defaults to None.

None
num int | None

Count for byscore/bylex. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get a range of members from a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index or score.
        end (int): End index or score.
        desc (bool): Sort in descending order. Defaults to False.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.
        byscore (bool): Range by score. Defaults to False.
        bylex (bool): Range by lexicographical order. Defaults to False.
        offset (int | None): Offset for byscore/bylex. Defaults to None.
        num (int | None): Count for byscore/bylex. Defaults to None.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrange(
        name,
        start,
        end,
        desc,
        withscores,
        score_cast_func,
        byscore,
        bylex,
        offset,
        num,
    )

archipy.adapters.redis.adapters.RedisAdapter.zrevrange

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get a range of members from a sorted set in reverse order.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index.

required
end int

End index.

required
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get a range of members from a sorted set in reverse order.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index.
        end (int): End index.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrevrange(name, start, end, withscores, score_cast_func)

archipy.adapters.redis.adapters.RedisAdapter.zrangebyscore

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get members from a sorted set by score range.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required
start int | None

Offset. Defaults to None.

None
num int | None

Count. Defaults to None.

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get members from a sorted set by score range.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.
        start (int | None): Offset. Defaults to None.
        num (int | None): Count. Defaults to None.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrangebyscore(name, min_, max_, start, num, withscores, score_cast_func)

archipy.adapters.redis.adapters.RedisAdapter.zrank

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Get the rank of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to find rank for.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

Rank of the member or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Get the rank of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to find rank for.

    Returns:
        RedisResponseType: Rank of the member or None if not found.
    """
    return self.client.zrank(name, value)

archipy.adapters.redis.adapters.RedisAdapter.zrem

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Remove members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Remove members from a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: Number of members removed.
    """
    return self.client.zrem(name, *values)

archipy.adapters.redis.adapters.RedisAdapter.zscore

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Get the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to get score for.

required

Returns:

Name Type Description
RedisResponseType float | None

Score of the member or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Get the score of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to get score for.

    Returns:
        RedisResponseType: Score of the member or None if not found.
    """
    return self.client.zscore(name, value)

archipy.adapters.redis.adapters.RedisAdapter.zunion

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the union of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the union of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zunion(_normalize_zset_keys(keys), aggregate, withscores, score_cast_func)

archipy.adapters.redis.adapters.RedisAdapter.zinter

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the intersection of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the intersection of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zinter(_normalize_zset_keys(keys), aggregate, withscores)

archipy.adapters.redis.adapters.RedisAdapter.zincrby

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increment the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
amount float

Amount to increment by.

required
value bytes | str | float

Member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

New score of the member.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increment the score of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        amount (float): Amount to increment by.
        value (bytes | str | float): Member to increment.

    Returns:
        RedisResponseType: New score of the member.
    """
    return self.client.zincrby(name, amount, value)

archipy.adapters.redis.adapters.RedisAdapter.sscan

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Scan members of a set incrementally.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Scan members of a set incrementally.

    Args:
        name (bytes | str): The set key name.
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        RedisResponseType: Tuple of cursor and list of members.
    """
    return self.read_only_client.sscan(name, cursor, match, count)

archipy.adapters.redis.adapters.RedisAdapter.sscan_iter

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]

Iterate over members of a set.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
Iterator Iterator[bytes | str]

Iterator over set members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]:
    """Iterate over members of a set.

    Args:
        name (bytes | str): The set key name.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        Iterator: Iterator over set members.
    """
    return self.read_only_client.sscan_iter(name, match, count)

archipy.adapters.redis.adapters.RedisAdapter.sadd

sadd(name: str, *values: bytes | str | float) -> int

Add members to a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements added.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Add members to a set.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: Number of elements added.
    """
    result = self.client.sadd(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.scard

scard(name: str) -> int

Get the number of members in a set.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def scard(self, name: str) -> int:
    """Get the number of members in a set.

    Args:
        name (str): The set key name.

    Returns:
        RedisIntegerResponseType: Number of members.
    """
    result = self.client.scard(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.sismember

sismember(name: str, value: str) -> bool

Check if a value is a member of a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
value str

Value to check.

required

Returns:

Name Type Description
bool bool

True if value is a member, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sismember(self, name: str, value: str) -> bool:
    """Check if a value is a member of a set.

    Args:
        name (str): The set key name.
        value (str): Value to check.

    Returns:
        bool: True if value is a member, False otherwise.
    """
    result = self.read_only_client.sismember(name, value)
    return bool(result)

archipy.adapters.redis.adapters.RedisAdapter.smembers

smembers(name: str) -> _set[bytes | str]

Get all members of a set.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set of all members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def smembers(self, name: str) -> _set[bytes | str]:
    """Get all members of a set.

    Args:
        name (str): The set key name.

    Returns:
        RedisSetResponseType: Set of all members.
    """
    result = self.read_only_client.smembers(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return set(result) if result else set()

archipy.adapters.redis.adapters.RedisAdapter.spop

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Remove and return random members from a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: Popped member(s) or None.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Remove and return random members from a set.

    Args:
        name (str): The set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        bytes | float | int | str | list | None: Popped member(s) or None.
    """
    result = self.client.spop(name, count)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    if isinstance(result, set):
        return list(result)
    return result

archipy.adapters.redis.adapters.RedisAdapter.srem

srem(name: str, *values: bytes | str | float) -> int

Remove members from a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def srem(self, name: str, *values: bytes | str | float) -> int:
    """Remove members from a set.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: Number of members removed.
    """
    result = self.client.srem(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.sunion

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Get the union of multiple sets.

Parameters:

Name Type Description Default
keys bytes | str

First set key.

required
*args bytes | str

Additional set keys.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set containing union of all sets.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Get the union of multiple sets.

    Args:
        keys (bytes | str): First set key.
        *args (bytes | str): Additional set keys.

    Returns:
        RedisSetResponseType: Set containing union of all sets.
    """
    # Redis sunion expects a list of keys as first argument
    keys_list: list[str | bytes] = [keys, *list(args)]
    result = self.client.sunion(keys_list)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return set(result) if result else set()

archipy.adapters.redis.adapters.RedisAdapter.llen

llen(name: str) -> int

Get the length of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def llen(self, name: str) -> int:
    """Get the length of a list.

    Args:
        name (str): The key name of the list.

    Returns:
        RedisIntegerResponseType: Length of the list.
    """
    result = self.read_only_client.llen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.lpop

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from the left of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from the left of a list.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    return self.client.lpop(name, count)

archipy.adapters.redis.adapters.RedisAdapter.lpush

lpush(name: str, *values: bytes | str | float) -> int

Push elements to the left of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to the left of a list.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.lpush(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.lrange

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Get a range of elements from a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
start int

Start index.

required
end int

End index.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of elements in the specified range.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Get a range of elements from a list.

    Args:
        name (str): The key name of the list.
        start (int): Start index.
        end (int): End index.

    Returns:
        RedisListResponseType: List of elements in the specified range.
    """
    result = self.read_only_client.lrange(name, start, end)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result)

archipy.adapters.redis.adapters.RedisAdapter.lrem

lrem(name: str, count: int, value: str) -> int

Remove elements from a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int

Number of occurrences to remove.

required
value str

Value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements removed.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lrem(self, name: str, count: int, value: str) -> int:
    """Remove elements from a list.

    Args:
        name (str): The key name of the list.
        count (int): Number of occurrences to remove.
        value (str): Value to remove.

    Returns:
        RedisIntegerResponseType: Number of elements removed.
    """
    result = self.client.lrem(name, count, value)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.lset

lset(name: str, index: int, value: str) -> bool

Set the value of an element in a list by its index.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
index int

Index of the element.

required
value str

New value.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lset(self, name: str, index: int, value: str) -> bool:
    """Set the value of an element in a list by its index.

    Args:
        name (str): The key name of the list.
        index (int): Index of the element.
        value (str): New value.

    Returns:
        bool: True if successful.
    """
    return bool(self.client.lset(name, index, value))

archipy.adapters.redis.adapters.RedisAdapter.rpop

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from the right of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from the right of a list.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    return self.client.rpop(name, count)

archipy.adapters.redis.adapters.RedisAdapter.rpush

rpush(name: str, *values: bytes | str | float) -> int

Push elements to the right of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to the right of a list.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.rpush(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.adapters.RedisAdapter.pttl

pttl(name: bytes | str) -> int

Get the time to live in milliseconds for a key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in milliseconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def pttl(self, name: bytes | str) -> int:
    """Get the time to live in milliseconds for a key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in milliseconds.
    """
    return self.read_only_client.pttl(name)

archipy.adapters.redis.adapters.RedisAdapter.incrby

incrby(name: bytes | str, amount: int = 1) -> int

Increment the integer value of a key by the given amount.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
amount int

Amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after increment.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increment the integer value of a key by the given amount.

    Args:
        name (bytes | str): The key name.
        amount (int): Amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after increment.
    """
    return self.client.incrby(name, amount)

archipy.adapters.redis.adapters.RedisAdapter.increx

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increment a windowed counter with bounds and expiration control.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
byfloat float

Increment amount as a float.

None
byint int

Increment amount as an int.

None
lbound float | int

Lower bound for the resulting value.

None
ubound float | int

Upper bound for the resulting value.

None
saturate bool

Clamp out-of-bounds results instead of rejecting. Defaults to False.

False
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None
persist bool

Remove any existing expiration. Defaults to False.

False
enx bool

Set expiration only if none already exists. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increment a windowed counter with bounds and expiration control.

    Args:
        name (bytes | str): The key to increment.
        byfloat (float, optional): Increment amount as a float.
        byint (int, optional): Increment amount as an int.
        lbound (float | int, optional): Lower bound for the resulting value.
        ubound (float | int, optional): Upper bound for the resulting value.
        saturate (bool): Clamp out-of-bounds results instead of rejecting. Defaults to False.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.
        persist (bool): Remove any existing expiration. Defaults to False.
        enx (bool): Set expiration only if none already exists. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of [new_value, actual_increment_applied].
    """
    return list(
        self.client.increx(
            name,
            byfloat=byfloat,
            byint=byint,
            lbound=lbound,
            ubound=ubound,
            saturate=saturate,
            ex=ex,
            px=px,
            exat=exat,
            pxat=pxat,
            persist=persist,
            enx=enx,
        ),
    )

archipy.adapters.redis.adapters.RedisAdapter.set

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Set the value of a key with optional expiration and conditions.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
value int | bytes | str | float

The value to set.

required
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
nx bool

Only set if key doesn't exist.

False
xx bool

Only set if key exists.

False
keepttl bool

Retain the TTL from the previous value.

False
get bool

Return the old value.

False
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

Result of the operation.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Set the value of a key with optional expiration and conditions.

    Args:
        name (bytes | str): The key name.
        value (int | bytes | str | float): The value to set.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        nx (bool): Only set if key doesn't exist.
        xx (bool): Only set if key exists.
        keepttl (bool): Retain the TTL from the previous value.
        get (bool): Return the old value.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.

    Returns:
        RedisResponseType: Result of the operation.
    """
    return self.client.set(name, value, ex, px, nx, xx, keepttl, get, exat, pxat)

archipy.adapters.redis.adapters.RedisAdapter.get

get(key: str) -> bytes | str | None

Get the value of a key.

Parameters:

Name Type Description Default
key str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None if not exists.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def get(self, key: str) -> bytes | str | None:
    """Get the value of a key.

    Args:
        key (str): The key name.

    Returns:
        RedisResponseType: The value of the key or None if not exists.
    """
    return self.read_only_client.get(key)

archipy.adapters.redis.adapters.RedisAdapter.mget

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Get the values of multiple keys.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

Single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Get the values of multiple keys.

    Args:
        keys (bytes | str | Iterable[bytes | str]): Single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: List of values.
    """
    return self.read_only_client.mget(keys, *args)

archipy.adapters.redis.adapters.RedisAdapter.mset

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Set multiple keys to their respective values.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

Dictionary of key-value pairs.

required

Returns:

Name Type Description
RedisResponseType bool

Always returns 'OK'.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Set multiple keys to their respective values.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): Dictionary of key-value pairs.

    Returns:
        RedisResponseType: Always returns 'OK'.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    return self.client.mset(dict_mapping)

archipy.adapters.redis.adapters.RedisAdapter.keys

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Find all keys matching the given pattern.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Find all keys matching the given pattern.

    Args:
        pattern (bytes | str): Pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of matching keys.
    """
    return self.read_only_client.keys(pattern, **kwargs)

archipy.adapters.redis.adapters.RedisAdapter.getset

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Set the value of a key and return its old value.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The new value.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The previous value or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Set the value of a key and return its old value.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The new value.

    Returns:
        RedisResponseType: The previous value or None.
    """
    return self.client.getset(key, value)

archipy.adapters.redis.adapters.RedisAdapter.getdel

getdel(key: bytes | str) -> bytes | str | None

Get the value of a key and delete it.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def getdel(self, key: bytes | str) -> bytes | str | None:
    """Get the value of a key and delete it.

    Args:
        key (bytes | str): The key name.

    Returns:
        RedisResponseType: The value of the key or None.
    """
    return self.client.getdel(key)

archipy.adapters.redis.adapters.RedisAdapter.exists

exists(*names: bytes | str) -> int

Check if one or more keys exist.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys that exist.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def exists(self, *names: bytes | str) -> int:
    """Check if one or more keys exist.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys that exist.
    """
    return self.read_only_client.exists(*names)

archipy.adapters.redis.adapters.RedisAdapter.delete

delete(*names: bytes | str) -> int

Delete one or more keys.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys deleted.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def delete(self, *names: bytes | str) -> int:
    """Delete one or more keys.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys deleted.
    """
    return self.client.delete(*names)

archipy.adapters.redis.adapters.RedisAdapter.append

append(key: bytes | str, value: bytes | str | float) -> int

Append a value to a key.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

Length of the string after append.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Append a value to a key.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: Length of the string after append.
    """
    return self.client.append(key, value)

archipy.adapters.redis.adapters.RedisAdapter.ttl

ttl(name: bytes | str) -> int

Get the time to live in seconds for a key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in seconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def ttl(self, name: bytes | str) -> int:
    """Get the time to live in seconds for a key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in seconds.
    """
    return self.read_only_client.ttl(name)

archipy.adapters.redis.adapters.RedisAdapter.type

type(name: bytes | str) -> bytes | str

Determine the type stored at key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str

Type of the key's value.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def type(self, name: bytes | str) -> bytes | str:
    """Determine the type stored at key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Type of the key's value.
    """
    return self.read_only_client.type(name)

archipy.adapters.redis.adapters.RedisAdapter.scan

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Scan keys in the database incrementally.

Parameters:

Name Type Description Default
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys to return. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Scan keys in the database incrementally.

    Args:
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys to return. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Tuple of cursor and list of keys.
    """
    return self.read_only_client.scan(cursor, match, count, _type, **kwargs)

archipy.adapters.redis.adapters.RedisAdapter.scan_iter

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]

Iterate over keys in the database.

Parameters:

Name Type Description Default
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys to return. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
Iterator Iterator[bytes | str]

Iterator over matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]:
    """Iterate over keys in the database.

    Args:
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys to return. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        Iterator: Iterator over matching keys.
    """
    return self.read_only_client.scan_iter(match, count, _type, **kwargs)

archipy.adapters.redis.adapters.RedisAdapter.cluster_info

cluster_info() -> dict[str, str] | None

Get cluster information.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_info()
    return None

archipy.adapters.redis.adapters.RedisAdapter.cluster_nodes

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_nodes()
    return None

archipy.adapters.redis.adapters.RedisAdapter.cluster_slots

cluster_slots() -> list[Any] | None

Get cluster slots mapping.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_slots()
    return None

archipy.adapters.redis.adapters.RedisAdapter.cluster_key_slot

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_keyslot(key)
    return None

archipy.adapters.redis.adapters.RedisAdapter.cluster_count_keys_in_slot

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_countkeysinslot(slot)
    return None

archipy.adapters.redis.adapters.RedisAdapter.cluster_get_keys_in_slot

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_get_keys_in_slot(slot, count)
    return None

archipy.adapters.redis.adapters.RedisAdapter.ping

ping() -> bool

Ping the Redis server.

Returns:

Name Type Description
RedisResponseType bool

'PONG' if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def ping(self) -> bool:
    """Ping the Redis server.

    Returns:
        RedisResponseType: 'PONG' if successful.
    """
    return self.client.ping()

archipy.adapters.redis.adapters.RedisAdapter.flushdb

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.
    """
    return self.client.flushdb(asynchronous=asynchronous)

archipy.adapters.redis.adapters.RedisAdapter.get_pipeline

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> Pipeline

Get a pipeline object for executing multiple commands.

Parameters:

Name Type Description Default
transaction Any

Whether to use transactions. Defaults to True.

True
shard_hint Any

Hint for sharding. Defaults to None.

None

Returns:

Name Type Description
Pipeline Pipeline

Pipeline object.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def get_pipeline(self, transaction: Any = True, shard_hint: Any = None) -> Pipeline:
    """Get a pipeline object for executing multiple commands.

    Args:
        transaction (Any): Whether to use transactions. Defaults to True.
        shard_hint (Any): Hint for sharding. Defaults to None.

    Returns:
        Pipeline: Pipeline object.
    """
    return self.client.pipeline(transaction, shard_hint)

archipy.adapters.redis.adapters.RedisAdapter.config_set

config_set(name: str, value: str) -> bool

Set a Redis server configuration parameter.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def config_set(self, name: str, value: str) -> bool:
    """Set a Redis server configuration parameter.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.
    """
    return bool(self.client.config_set(name, value))

archipy.adapters.redis.adapters.RedisAdapter.config_get

config_get(pattern: str = '*') -> dict[str, str]

Get Redis server configuration parameters matching a pattern.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

Dictionary of configuration parameter names to values.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Get Redis server configuration parameters matching a pattern.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: Dictionary of configuration parameter names to values.
    """
    result = self.read_only_client.config_get(pattern)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return {str(k): str(v) for k, v in result.items()} if result else {}

archipy.adapters.redis.adapters.RedisAdapter.search_index

search_index(name: str) -> RedisSearchHandlePort

Return an index-bound RediSearch handle.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def search_index(self, name: str) -> RedisSearchHandlePort:
    """Return an index-bound RediSearch handle."""
    return RedisSearchHandle(self._get_search_client(), name)

archipy.adapters.redis.adapters.RedisAdapter.list_search_indexes

list_search_indexes() -> list[str]

List RediSearch indexes available on the server.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def list_search_indexes(self) -> list[str]:
    """List RediSearch indexes available on the server."""
    return list_redis_search_indexes(self._get_search_client())

archipy.adapters.redis.adapters.AsyncRedisAdapter

Bases: AsyncRedisConnectionMixin, AsyncRedisClusterMixin, AsyncRedisKeysMixin, AsyncRedisListsMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, AsyncRedisArraysMixin, AsyncRedisHashesMixin, AsyncRedisPubSubMixin, AsyncRedisPort

Async adapter for Redis operations providing a standardized interface.

Implements AsyncRedisPort over async redis-py clients. Maintains separate read/write clients for replica-friendly deployments.

Parameters:

Name Type Description Default
redis_config RedisConfig | None

Redis settings. Uses global config when None.

None
Source code in archipy/adapters/redis/adapters.py
class AsyncRedisAdapter(
    AsyncRedisConnectionMixin,
    AsyncRedisClusterMixin,
    AsyncRedisKeysMixin,
    AsyncRedisListsMixin,
    AsyncRedisSetsMixin,
    AsyncRedisSortedSetsMixin,
    AsyncRedisArraysMixin,
    AsyncRedisHashesMixin,
    AsyncRedisPubSubMixin,
    AsyncRedisPort,
):
    """Async adapter for Redis operations providing a standardized interface.

    Implements AsyncRedisPort over async redis-py clients. Maintains separate
    read/write clients for replica-friendly deployments.

    Args:
        redis_config: Redis settings. Uses global config when None.
    """

archipy.adapters.redis.adapters.AsyncRedisAdapter.client instance-attribute

client: Redis | RedisCluster

archipy.adapters.redis.adapters.AsyncRedisAdapter.read_only_client instance-attribute

read_only_client: Redis | RedisCluster

archipy.adapters.redis.adapters.AsyncRedisAdapter.publish async

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publish message to channel asynchronously.

Parameters:

Name Type Description Default
channel bytes | str

Channel name.

required
message bytes | str

Message to publish.

required
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType int

Number of subscribers received message.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publish message to channel asynchronously.

    Args:
        channel (bytes | str): Channel name.
        message (bytes | str): Message to publish.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Number of subscribers received message.
    """
    return await self.client.publish(channel, message, **kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.pubsub_channels async

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

List active channels matching pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of channel names.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """List active channels matching pattern asynchronously.

    Args:
        pattern (bytes | str): Pattern to match. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of channel names.
    """
    return await self.client.pubsub_channels(pattern, **kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.pubsub async

pubsub(**kwargs: Any) -> AsyncPubSub

Get PubSub object for channel subscription asynchronously.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
AsyncPubSub PubSub

PubSub object.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def pubsub(self, **kwargs: Any) -> AsyncPubSub:
    """Get PubSub object for channel subscription asynchronously.

    Args:
        **kwargs (Any): Additional arguments.

    Returns:
        AsyncPubSub: PubSub object.
    """
    return self.client.pubsub(**kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hdel async

hdel(name: str, *keys: str | bytes) -> int

Delete fields from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields deleted.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hdel(self, name: str, *keys: str | bytes) -> int:
    """Delete fields from hash asynchronously.

    Args:
        name (str): The hash key name.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: Number of fields deleted.
    """
    # Convert keys to str for type compatibility
    str_keys: tuple[str, ...] = tuple(str(k) if isinstance(k, bytes) else k for k in keys)
    result = self.client.hdel(name, *str_keys)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hexists async

hexists(name: str, key: str) -> bool

Check if field exists in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to check.

required

Returns:

Name Type Description
bool bool

True if exists, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hexists(self, name: str, key: str) -> bool:
    """Check if field exists in hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str): Field to check.

    Returns:
        bool: True if exists, False otherwise.
    """
    result = self.read_only_client.hexists(name, key)
    return await self._ensure_async_bool(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hget async

hget(name: str, key: str) -> bytes | str | None

Get field value from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to get.

required

Returns:

Type Description
bytes | str | None

str | None: Value or None.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hget(self, name: str, key: str) -> bytes | str | None:
    """Get field value from hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str): Field to get.

    Returns:
        str | None: Value or None.
    """
    result = self.read_only_client.hget(name, key)
    resolved = await self._ensure_async_str(result)
    return str(resolved) if resolved is not None else None

archipy.adapters.redis.adapters.AsyncRedisAdapter.hgetall async

hgetall(name: str) -> dict[bytes | str, bytes | str]

Get all fields and values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: Dictionary of field-value pairs.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Get all fields and values from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        dict[str, Any]: Dictionary of field-value pairs.
    """
    result = self.read_only_client.hgetall(name)
    if isinstance(result, Awaitable):
        awaited_result = await result
        if awaited_result is None:
            return {}
        if isinstance(awaited_result, dict):
            return {str(k): v for k, v in awaited_result.items()}
        if isinstance(awaited_result, Mapping):
            return {str(k): v for k, v in awaited_result.items()}
        return {}
    if result is None:
        return {}
    if isinstance(result, dict):
        return {str(k): v for k, v in result.items()}
    if isinstance(result, Mapping):
        return {str(k): v for k, v in result.items()}
    return {}

archipy.adapters.redis.adapters.AsyncRedisAdapter.hkeys async

hkeys(name: str) -> list[bytes | str]

Get all fields from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of field names.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hkeys(self, name: str) -> list[bytes | str]:
    """Get all fields from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of field names.
    """
    result = self.read_only_client.hkeys(name)
    return await self._ensure_async_list(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hlen async

hlen(name: str) -> int

Get number of fields in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hlen(self, name: str) -> int:
    """Get number of fields in hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisIntegerResponseType: Number of fields.
    """
    result = self.read_only_client.hlen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hset async

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Set fields in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str | bytes | None

Single field name. Defaults to None.

None
value str | bytes | None

Single field value. Defaults to None.

None
mapping dict | None

Field-value pairs dict. Defaults to None.

None
items list | None

Field-value pairs list. Defaults to None.

None

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields set.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Set fields in hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str | bytes | None): Single field name. Defaults to None.
        value (str | bytes | None): Single field value. Defaults to None.
        mapping (dict | None): Field-value pairs dict. Defaults to None.
        items (list | None): Field-value pairs list. Defaults to None.

    Returns:
        RedisIntegerResponseType: Number of fields set.
    """
    # Convert bytes to str for type compatibility with Redis client
    str_key: str | None = str(key) if key is not None and isinstance(key, bytes) else key
    str_value: str | None = str(value) if value is not None and isinstance(value, bytes) else value
    result = self.client.hset(name, str_key, str_value, mapping, items)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hmget async

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Get multiple field values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
keys list

List of field names.

required
*args str | bytes

Additional field names.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

List of field values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Get multiple field values from hash asynchronously.

    Args:
        name (str): The hash key name.
        keys (list): List of field names.
        *args (str | bytes): Additional field names.

    Returns:
        RedisListResponseType: List of field values.
    """
    # Convert keys list and args for type compatibility, combine into single list
    keys_list: list[str] = [str(k) for k in keys] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.read_only_client.hmget(name, keys_list)
    return await self._ensure_async_list(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.hvals async

hvals(name: str) -> list[bytes | str]

Get all values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hvals(self, name: str) -> list[bytes | str]:
    """Get all values from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of values.
    """
    result = self.read_only_client.hvals(name)
    return await self._ensure_async_list(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.arset async

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Set one or more contiguous values in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index to set values at.

required
*values bytes | str | float

Values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Set one or more contiguous values in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index to set values at.
        *values (bytes | str | float): Values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.
    """
    result = self.client.arset(name, index, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.arget async

arget(name: bytes | str, index: int) -> bytes | str | None

Get the value at an index in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Get the value at an index in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset.
    """
    result = self.read_only_client.arget(name, index)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.arlen async

arlen(name: bytes | str) -> int

Get the number of populated elements in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arlen(self, name: bytes | str) -> int:
    """Get the number of populated elements in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.
    """
    result = self.read_only_client.arlen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.ardel async

ardel(name: bytes | str, *indices: int) -> int

Delete one or more indices from an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

Indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def ardel(self, name: bytes | str, *indices: int) -> int:
    """Delete one or more indices from an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): Indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.
    """
    result = self.client.ardel(name, *indices)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.arring async

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Insert values into an array as a fixed-size ring buffer asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

Values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Insert values into an array as a fixed-size ring buffer asynchronously.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): Values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.
    """
    result = self.client.arring(name, size, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zadd async

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Add members to sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
mapping Mapping[bytes | str, bytes | str | float]

Member-score pairs.

required
nx bool

Only add new elements. Defaults to False.

False
xx bool

Only update existing. Defaults to False.

False
ch bool

Return changed count. Defaults to False.

False
incr bool

Increment scores. Defaults to False.

False
gt bool

Only if greater. Defaults to False.

False
lt bool

Only if less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

Number of elements added or modified.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Add members to sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        mapping (Mapping[bytes | str, bytes | str | float]): Member-score pairs.
        nx (bool): Only add new elements. Defaults to False.
        xx (bool): Only update existing. Defaults to False.
        ch (bool): Return changed count. Defaults to False.
        incr (bool): Increment scores. Defaults to False.
        gt (bool): Only if greater. Defaults to False.
        lt (bool): Only if less. Defaults to False.

    Returns:
        RedisResponseType: Number of elements added or modified.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    if isinstance(mapping, dict):
        dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    else:
        dict_mapping = {str(k): v for k, v in mapping.items()}
    str_name = str(name)
    result = self.client.zadd(str_name, dict_mapping, nx, xx, ch, incr, gt, lt)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.zcard async

zcard(name: bytes | str) -> int

Get number of members in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required

Returns:

Name Type Description
RedisResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zcard(self, name: bytes | str) -> int:
    """Get number of members in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.

    Returns:
        RedisResponseType: Number of members.
    """
    return await self.client.zcard(name)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zcount async

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Count members in score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required

Returns:

Name Type Description
RedisResponseType int

Number of members in range.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Count members in score range asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.

    Returns:
        RedisResponseType: Number of members in range.
    """
    return await self.client.zcount(name, min_, max_)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zpopmax async

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Pop highest scored members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Pop highest scored members asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return await self.client.zpopmax(name, count)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zpopmin async

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Pop lowest scored members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Pop lowest scored members asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return await self.client.zpopmin(name, count)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zrange async

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get range from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index or score.

required
end int

End index or score.

required
desc bool

Descending order. Defaults to False.

False
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float
byscore bool

Range by score. Defaults to False.

False
bylex bool

Range by lex. Defaults to False.

False
offset int | None

Offset for byscore/bylex. Defaults to None.

None
num int | None

Count for byscore/bylex. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get range from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index or score.
        end (int): End index or score.
        desc (bool): Descending order. Defaults to False.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.
        byscore (bool): Range by score. Defaults to False.
        bylex (bool): Range by lex. Defaults to False.
        offset (int | None): Offset for byscore/bylex. Defaults to None.
        num (int | None): Count for byscore/bylex. Defaults to None.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrange(
        name,
        start,
        end,
        desc,
        withscores,
        score_cast_func,
        byscore,
        bylex,
        offset,
        num,
    )

archipy.adapters.redis.adapters.AsyncRedisAdapter.zrevrange async

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get reverse range from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index.

required
end int

End index.

required
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get reverse range from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index.
        end (int): End index.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrevrange(name, start, end, withscores, score_cast_func)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zrangebyscore async

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get members by score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required
start int | None

Offset. Defaults to None.

None
num int | None

Count. Defaults to None.

None
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get members by score range asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.
        start (int | None): Offset. Defaults to None.
        num (int | None): Count. Defaults to None.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrangebyscore(name, min_, max_, start, num, withscores, score_cast_func)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zrank async

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Get rank of member in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to find rank for.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

Rank or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Get rank of member in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to find rank for.

    Returns:
        RedisResponseType: Rank or None if not found.
    """
    return await self.client.zrank(name, value)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zrem async

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Remove members from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Remove members from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: Number of members removed.
    """
    return await self.client.zrem(name, *values)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zscore async

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Get score of member in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to get score for.

required

Returns:

Name Type Description
RedisResponseType float | None

Score or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Get score of member in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to get score for.

    Returns:
        RedisResponseType: Score or None if not found.
    """
    return await self.client.zscore(name, value)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zunion async

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the union of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the union of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zunion(_normalize_zset_keys(keys), aggregate, withscores, score_cast_func)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zinter async

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the intersection of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the intersection of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zinter(_normalize_zset_keys(keys), aggregate, withscores)

archipy.adapters.redis.adapters.AsyncRedisAdapter.zincrby async

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increment member score in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
amount float

Amount to increment by.

required
value bytes | str | float

Member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

New score of the member.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increment member score in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        amount (float): Amount to increment by.
        value (bytes | str | float): Member to increment.

    Returns:
        RedisResponseType: New score of the member.
    """
    return await self.client.zincrby(name, amount, value)

archipy.adapters.redis.adapters.AsyncRedisAdapter.sscan async

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Scan set members incrementally asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Scan set members incrementally asynchronously.

    Args:
        name (bytes | str): The set key name.
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        RedisResponseType: Tuple of cursor and list of members.
    """
    result = self.read_only_client.sscan(name, cursor, match, count)
    if isinstance(result, Awaitable):
        awaited_result: tuple[int, list[bytes | str]] = await result
        return awaited_result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.sscan_iter async

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]

Iterate over set members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Type Description
AsyncIterator[bytes | str]

Iterator[Any]: Iterator over set members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]:
    """Iterate over set members asynchronously.

    Args:
        name (bytes | str): The set key name.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        Iterator[Any]: Iterator over set members.
    """
    return self.read_only_client.sscan_iter(name, match, count)

archipy.adapters.redis.adapters.AsyncRedisAdapter.sadd async

sadd(name: str, *values: bytes | str | float) -> int

Add members to a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements added.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Add members to a set asynchronously.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: Number of elements added.
    """
    result = self.client.sadd(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.scard async

scard(name: str) -> int

Get number of members in a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def scard(self, name: str) -> int:
    """Get number of members in a set asynchronously.

    Args:
        name (str): The set key name.

    Returns:
        RedisIntegerResponseType: Number of members.
    """
    result = self.client.scard(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.sismember async

sismember(name: str, value: str) -> bool

Check if value is in set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
value str

Value to check.

required

Returns:

Name Type Description
bool bool

True if value is member, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sismember(self, name: str, value: str) -> bool:
    """Check if value is in set asynchronously.

    Args:
        name (str): The set key name.
        value (str): Value to check.

    Returns:
        bool: True if value is member, False otherwise.
    """
    result = self.read_only_client.sismember(name, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.smembers async

smembers(name: str) -> _set[bytes | str]

Get all members of a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set of all members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def smembers(self, name: str) -> _set[bytes | str]:
    """Get all members of a set asynchronously.

    Args:
        name (str): The set key name.

    Returns:
        RedisSetResponseType: Set of all members.
    """
    result = self.read_only_client.smembers(name)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return set()
    if isinstance(result, set):
        return result
    if isinstance(result, Iterable):
        return set(result)
    return set()

archipy.adapters.redis.adapters.AsyncRedisAdapter.spop async

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Remove and return random set members asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: Popped member(s) or None.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Remove and return random set members asynchronously.

    Args:
        name (str): The set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        bytes | float | int | str | list | None: Popped member(s) or None.
    """
    result = self.client.spop(name, count)
    if isinstance(result, Awaitable):
        awaited_result = await result
        # Type narrowing: result can be any of the return types
        if awaited_result is None or isinstance(awaited_result, (bytes, float, int, str, list)):
            return awaited_result
        raise InvalidArgumentError(
            argument_name="spop_result",
            additional_data={"got": type(awaited_result).__name__},
        )
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.srem async

srem(name: str, *values: bytes | str | float) -> int

Remove members from a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def srem(self, name: str, *values: bytes | str | float) -> int:
    """Remove members from a set asynchronously.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: Number of members removed.
    """
    result = self.client.srem(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.sunion async

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Get union of multiple sets asynchronously.

Parameters:

Name Type Description Default
keys bytes | str

First set key.

required
*args bytes | str

Additional set keys.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set containing union of all sets.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Get union of multiple sets asynchronously.

    Args:
        keys (bytes | str): First set key.
        *args (bytes | str): Additional set keys.

    Returns:
        RedisSetResponseType: Set containing union of all sets.
    """
    # Convert keys to str for type compatibility, combine into list
    keys_list: list[str] = [str(keys)] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.client.sunion(keys_list)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return set()
    if isinstance(result, set):
        return result
    if isinstance(result, Iterable):
        return set(result)
    return set()

archipy.adapters.redis.adapters.AsyncRedisAdapter.llen async

llen(name: str) -> int

Get the length of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def llen(self, name: str) -> int:
    """Get the length of a list asynchronously.

    Args:
        name (str): The key name of the list.

    Returns:
        RedisIntegerResponseType: Length of the list.
    """
    result = self.read_only_client.llen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.lpop async

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from list left asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from list left asynchronously.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    result = self.client.lpop(name, count)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.lpush async

lpush(name: str, *values: bytes | str | float) -> int

Push elements to list left asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to list left asynchronously.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.lpush(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.lrange async

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Get a range of elements from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
start int

Start index.

required
end int

End index.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of elements in range.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Get a range of elements from a list asynchronously.

    Args:
        name (str): The key name of the list.
        start (int): Start index.
        end (int): End index.

    Returns:
        RedisListResponseType: List of elements in range.
    """
    result = self.read_only_client.lrange(name, start, end)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return []
    if isinstance(result, list):
        return result
    if isinstance(result, Iterable):
        return list(result)
    return []

archipy.adapters.redis.adapters.AsyncRedisAdapter.lrem async

lrem(name: str, count: int, value: str) -> int

Remove elements from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int

Number of occurrences to remove.

required
value str

Value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements removed.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lrem(self, name: str, count: int, value: str) -> int:
    """Remove elements from a list asynchronously.

    Args:
        name (str): The key name of the list.
        count (int): Number of occurrences to remove.
        value (str): Value to remove.

    Returns:
        RedisIntegerResponseType: Number of elements removed.
    """
    result = self.client.lrem(name, count, value)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.lset async

lset(name: str, index: int, value: str) -> bool

Set list element by index asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
index int

Index of the element.

required
value str

New value.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lset(self, name: str, index: int, value: str) -> bool:
    """Set list element by index asynchronously.

    Args:
        name (str): The key name of the list.
        index (int): Index of the element.
        value (str): New value.

    Returns:
        bool: True if successful.
    """
    result = self.client.lset(name, index, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.rpop async

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from list right asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from list right asynchronously.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    result = self.client.rpop(name, count)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.rpush async

rpush(name: str, *values: bytes | str | float) -> int

Push elements to list right asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to list right asynchronously.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.rpush(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.pttl async

pttl(name: bytes | str) -> int

Get the time to live in milliseconds for a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in milliseconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def pttl(self, name: bytes | str) -> int:
    """Get the time to live in milliseconds for a key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in milliseconds.
    """
    return await self.read_only_client.pttl(name)

archipy.adapters.redis.adapters.AsyncRedisAdapter.incrby async

incrby(name: bytes | str, amount: int = 1) -> int

Increment the integer value of a key by the given amount asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
amount int

Amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after increment.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increment the integer value of a key by the given amount asynchronously.

    Args:
        name (bytes | str): The key name.
        amount (int): Amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after increment.
    """
    return await self.client.incrby(name, amount)

archipy.adapters.redis.adapters.AsyncRedisAdapter.increx async

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increment a windowed counter with bounds and expiration control asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
byfloat float

Increment amount as a float.

None
byint int

Increment amount as an int.

None
lbound float | int

Lower bound for the resulting value.

None
ubound float | int

Upper bound for the resulting value.

None
saturate bool

Clamp out-of-bounds results instead of rejecting. Defaults to False.

False
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None
persist bool

Remove any existing expiration. Defaults to False.

False
enx bool

Set expiration only if none already exists. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increment a windowed counter with bounds and expiration control asynchronously.

    Args:
        name (bytes | str): The key to increment.
        byfloat (float, optional): Increment amount as a float.
        byint (int, optional): Increment amount as an int.
        lbound (float | int, optional): Lower bound for the resulting value.
        ubound (float | int, optional): Upper bound for the resulting value.
        saturate (bool): Clamp out-of-bounds results instead of rejecting. Defaults to False.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.
        persist (bool): Remove any existing expiration. Defaults to False.
        enx (bool): Set expiration only if none already exists. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of [new_value, actual_increment_applied].
    """
    result = self.client.increx(
        name,
        byfloat=byfloat,
        byint=byint,
        lbound=lbound,
        ubound=ubound,
        saturate=saturate,
        ex=ex,
        px=px,
        exat=exat,
        pxat=pxat,
        persist=persist,
        enx=enx,
    )
    if isinstance(result, Awaitable):
        result = await result
    return list(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.set async

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Set the value of a key with optional expiration asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
value int | bytes | str | float

The value to set.

required
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
nx bool

Only set if key doesn't exist.

False
xx bool

Only set if key exists.

False
keepttl bool

Retain the TTL from the previous value.

False
get bool

Return the old value.

False
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

Result of the operation.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Set the value of a key with optional expiration asynchronously.

    Args:
        name (bytes | str): The key name.
        value (int | bytes | str | float): The value to set.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        nx (bool): Only set if key doesn't exist.
        xx (bool): Only set if key exists.
        keepttl (bool): Retain the TTL from the previous value.
        get (bool): Return the old value.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.

    Returns:
        RedisResponseType: Result of the operation.
    """
    return await self.client.set(name, value, ex, px, nx, xx, keepttl, get, exat, pxat)

archipy.adapters.redis.adapters.AsyncRedisAdapter.get async

get(key: str) -> bytes | str | None

Get the value of a key asynchronously.

Parameters:

Name Type Description Default
key str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None if not exists.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def get(self, key: str) -> bytes | str | None:
    """Get the value of a key asynchronously.

    Args:
        key (str): The key name.

    Returns:
        RedisResponseType: The value of the key or None if not exists.
    """
    return await self.read_only_client.get(key)

archipy.adapters.redis.adapters.AsyncRedisAdapter.mget async

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Get the values of multiple keys asynchronously.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

Single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Get the values of multiple keys asynchronously.

    Args:
        keys (bytes | str | Iterable[bytes | str]): Single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: List of values.
    """
    return await self.read_only_client.mget(keys, *args)

archipy.adapters.redis.adapters.AsyncRedisAdapter.mset async

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Set multiple keys to their values asynchronously.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

Dictionary of key-value pairs.

required

Returns:

Name Type Description
RedisResponseType bool

Always returns 'OK'.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Set multiple keys to their values asynchronously.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): Dictionary of key-value pairs.

    Returns:
        RedisResponseType: Always returns 'OK'.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    return await self.client.mset(dict_mapping)

archipy.adapters.redis.adapters.AsyncRedisAdapter.keys async

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Find all keys matching the pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Find all keys matching the pattern asynchronously.

    Args:
        pattern (bytes | str): Pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of matching keys.
    """
    return await self.read_only_client.keys(pattern, **kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.getset async

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Set a key's value and return its old value asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The new value.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The previous value or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Set a key's value and return its old value asynchronously.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The new value.

    Returns:
        RedisResponseType: The previous value or None.
    """
    return await self.client.getset(key, value)

archipy.adapters.redis.adapters.AsyncRedisAdapter.getdel async

getdel(key: bytes | str) -> bytes | str | None

Get a key's value and delete it asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def getdel(self, key: bytes | str) -> bytes | str | None:
    """Get a key's value and delete it asynchronously.

    Args:
        key (bytes | str): The key name.

    Returns:
        RedisResponseType: The value of the key or None.
    """
    return await self.client.getdel(key)

archipy.adapters.redis.adapters.AsyncRedisAdapter.exists async

exists(*names: bytes | str) -> int

Check if keys exist asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys that exist.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def exists(self, *names: bytes | str) -> int:
    """Check if keys exist asynchronously.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys that exist.
    """
    return await self.read_only_client.exists(*names)

archipy.adapters.redis.adapters.AsyncRedisAdapter.delete async

delete(*names: bytes | str) -> int

Delete keys asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys deleted.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def delete(self, *names: bytes | str) -> int:
    """Delete keys asynchronously.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys deleted.
    """
    return await self.client.delete(*names)

archipy.adapters.redis.adapters.AsyncRedisAdapter.append async

append(key: bytes | str, value: bytes | str | float) -> int

Append a value to a key asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

Length of the string after append.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Append a value to a key asynchronously.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: Length of the string after append.
    """
    return await self.client.append(key, value)

archipy.adapters.redis.adapters.AsyncRedisAdapter.ttl async

ttl(name: bytes | str) -> int

Get the time to live in seconds for a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in seconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def ttl(self, name: bytes | str) -> int:
    """Get the time to live in seconds for a key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in seconds.
    """
    return await self.read_only_client.ttl(name)

archipy.adapters.redis.adapters.AsyncRedisAdapter.type async

type(name: bytes | str) -> bytes | str

Determine the type stored at key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str

Type of the key's value.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def type(self, name: bytes | str) -> bytes | str:
    """Determine the type stored at key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Type of the key's value.
    """
    return await self.read_only_client.type(name)

archipy.adapters.redis.adapters.AsyncRedisAdapter.scan async

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Scan keys in database incrementally asynchronously.

Parameters:

Name Type Description Default
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Scan keys in database incrementally asynchronously.

    Args:
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Tuple of cursor and list of keys.
    """
    return await self.read_only_client.scan(cursor, match, count, _type, **kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.scan_iter async

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]

Iterate over keys in database asynchronously.

Parameters:

Name Type Description Default
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
AsyncIterator[bytes | str]

Iterator[Any]: Iterator over matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]:
    """Iterate over keys in database asynchronously.

    Args:
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        Iterator[Any]: Iterator over matching keys.
    """
    return self.read_only_client.scan_iter(match, count, _type, **kwargs)

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_info async

cluster_info() -> dict[str, str] | None

Get cluster information asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_info()
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_nodes async

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_nodes()
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_slots async

cluster_slots() -> list[Any] | None

Get cluster slots mapping asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_slots()
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_key_slot async

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_keyslot(key)
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_count_keys_in_slot async

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_countkeysinslot(slot)
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.cluster_get_keys_in_slot async

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_get_keys_in_slot(slot, count)
    return None

archipy.adapters.redis.adapters.AsyncRedisAdapter.ping async

ping() -> bool

Ping the Redis server asynchronously.

Returns:

Name Type Description
RedisResponseType bool

'PONG' if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def ping(self) -> bool:
    """Ping the Redis server asynchronously.

    Returns:
        RedisResponseType: 'PONG' if successful.
    """
    result = self.client.ping()
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.flushdb async

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database asynchronously.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database asynchronously.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.
    """
    result = self.client.flushdb(asynchronous=asynchronous)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.get_pipeline async

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> AsyncPipeline | AsyncClusterPipeline

Get pipeline for multiple commands asynchronously.

Parameters:

Name Type Description Default
transaction Any

Use transactions. Defaults to True.

True
shard_hint Any

Sharding hint. Defaults to None.

None

Returns:

Type Description
Pipeline | ClusterPipeline

AsyncPipeline | AsyncClusterPipeline: Pipeline object.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def get_pipeline(
    self,
    transaction: Any = True,
    shard_hint: Any = None,
) -> AsyncPipeline | AsyncClusterPipeline:
    """Get pipeline for multiple commands asynchronously.

    Args:
        transaction (Any): Use transactions. Defaults to True.
        shard_hint (Any): Sharding hint. Defaults to None.

    Returns:
        AsyncPipeline | AsyncClusterPipeline: Pipeline object.
    """
    result = self.client.pipeline(transaction, shard_hint)
    if not isinstance(result, (AsyncPipeline, AsyncClusterPipeline)):
        raise InvalidArgumentError(
            argument_name="pipeline",
            additional_data={"expected": "AsyncPipeline", "got": type(result).__name__},
        )
    return result

archipy.adapters.redis.adapters.AsyncRedisAdapter.config_set async

config_set(name: str, value: str) -> bool

Set a Redis server configuration parameter asynchronously.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def config_set(self, name: str, value: str) -> bool:
    """Set a Redis server configuration parameter asynchronously.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.
    """
    result = self.client.config_set(name, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.adapters.AsyncRedisAdapter.config_get async

config_get(pattern: str = '*') -> dict[str, str]

Get Redis server configuration parameters matching a pattern asynchronously.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

Dictionary of configuration parameter names to values.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Get Redis server configuration parameters matching a pattern asynchronously.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: Dictionary of configuration parameter names to values.
    """
    result = self.read_only_client.config_get(pattern)
    if isinstance(result, Awaitable):
        result = await result
    return {str(k): str(v) for k, v in result.items()} if result else {}

archipy.adapters.redis.adapters.AsyncRedisAdapter.search_index

search_index(name: str) -> AsyncRedisSearchHandlePort

Return an index-bound async RediSearch handle.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def search_index(self, name: str) -> AsyncRedisSearchHandlePort:
    """Return an index-bound async RediSearch handle."""
    return AsyncRedisSearchHandle(self._get_search_client(), name)

archipy.adapters.redis.adapters.AsyncRedisAdapter.list_search_indexes async

list_search_indexes() -> list[str]

List RediSearch indexes available on the server asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def list_search_indexes(self) -> list[str]:
    """List RediSearch indexes available on the server asynchronously."""
    return await list_redis_search_indexes_async(self._get_search_client())

options: show_root_toc_entry: false heading_level: 3

Search Ports

Abstract port interfaces for index-bound RediSearch operations (sync and async).

Port interfaces for Redis Search operations.

archipy.adapters.redis.search_ports.RedisSearchHandlePort

Index-bound RediSearch operations contract.

Source code in archipy/adapters/redis/search_ports.py
class RedisSearchHandlePort:
    """Index-bound RediSearch operations contract."""

    @abstractmethod
    def create_index(
        self,
        schema: IndexSchemaDTO,
        prefix: str,
        index_type: RedisIndexType | None = None,
        **kwargs: Any,
    ) -> bool:
        """Create a RediSearch index."""
        raise NotImplementedError

    @abstractmethod
    def drop_index(self, delete_documents: bool = False) -> bool:
        """Drop the RediSearch index."""
        raise NotImplementedError

    @abstractmethod
    def info(self) -> dict[str, Any]:
        """Return index metadata."""
        raise NotImplementedError

    @abstractmethod
    def alter_schema_add(
        self,
        fields: IndexFieldConfig | list[IndexFieldConfig],
        *,
        index_type: RedisIndexType | None = None,
    ) -> bool:
        """Add fields to an existing index schema."""
        raise NotImplementedError

    @abstractmethod
    def upsert_hash(
        self,
        doc_id: str,
        fields: dict[str, str | int | float],
        vector_field: str | None = None,
        vector: list[float] | None = None,
        *,
        replace: bool = True,
    ) -> bool:
        """Upsert a HASH document and index it."""
        raise NotImplementedError

    @abstractmethod
    def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
        """Upsert a HASH document from a DTO."""
        raise NotImplementedError

    @abstractmethod
    def upsert_json(
        self,
        doc_id: str,
        payload: dict[str, str | int | float | list[float]],
        json_path: str = "$",
    ) -> bool:
        """Upsert a JSON document."""
        raise NotImplementedError

    @abstractmethod
    def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
        """Upsert a JSON document from a DTO."""
        raise NotImplementedError

    @abstractmethod
    def get_document(self, doc_id: str) -> dict[str, Any]:
        """Load a document by ID."""
        raise NotImplementedError

    @abstractmethod
    def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
        """Remove a document from the index."""
        raise NotImplementedError

    @abstractmethod
    def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
        """Execute a RediSearch query (text, KNN, or hybrid)."""
        raise NotImplementedError

    @abstractmethod
    def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
        """Execute a RediSearch aggregation."""
        raise NotImplementedError

    @abstractmethod
    def add_alias(self, alias: str) -> bool:
        """Add an alias for the index."""
        raise NotImplementedError

    @abstractmethod
    def update_alias(self, alias: str) -> bool:
        """Update an alias to point to this index."""
        raise NotImplementedError

    @abstractmethod
    def delete_alias(self, alias: str) -> bool:
        """Delete an alias."""
        raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.create_index abstractmethod

create_index(
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool

Create a RediSearch index.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def create_index(
    self,
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool:
    """Create a RediSearch index."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.drop_index abstractmethod

drop_index(delete_documents: bool = False) -> bool

Drop the RediSearch index.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def drop_index(self, delete_documents: bool = False) -> bool:
    """Drop the RediSearch index."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.info abstractmethod

info() -> dict[str, Any]

Return index metadata.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def info(self) -> dict[str, Any]:
    """Return index metadata."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.alter_schema_add abstractmethod

alter_schema_add(
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool

Add fields to an existing index schema.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def alter_schema_add(
    self,
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool:
    """Add fields to an existing index schema."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.upsert_hash abstractmethod

upsert_hash(
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool

Upsert a HASH document and index it.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def upsert_hash(
    self,
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool:
    """Upsert a HASH document and index it."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.upsert_hash_dto abstractmethod

upsert_hash_dto(
    document: HashDocumentUpsertDTO, *, replace: bool = True
) -> bool

Upsert a HASH document from a DTO.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
    """Upsert a HASH document from a DTO."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.upsert_json abstractmethod

upsert_json(
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool

Upsert a JSON document.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def upsert_json(
    self,
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool:
    """Upsert a JSON document."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.upsert_json_dto abstractmethod

upsert_json_dto(document: JsonDocumentUpsertDTO) -> bool

Upsert a JSON document from a DTO.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
    """Upsert a JSON document from a DTO."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.get_document abstractmethod

get_document(doc_id: str) -> dict[str, Any]

Load a document by ID.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def get_document(self, doc_id: str) -> dict[str, Any]:
    """Load a document by ID."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.delete_document abstractmethod

delete_document(
    doc_id: str, *, delete_actual_document: bool = True
) -> int

Remove a document from the index.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
    """Remove a document from the index."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.search abstractmethod

search(
    query: SearchQueryDTO, **kwargs: Any
) -> SearchResultDTO

Execute a RediSearch query (text, KNN, or hybrid).

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
    """Execute a RediSearch query (text, KNN, or hybrid)."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.aggregate abstractmethod

aggregate(
    aggregation: AggregationDTO, **kwargs: Any
) -> dict[str, Any]

Execute a RediSearch aggregation.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
    """Execute a RediSearch aggregation."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.add_alias abstractmethod

add_alias(alias: str) -> bool

Add an alias for the index.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def add_alias(self, alias: str) -> bool:
    """Add an alias for the index."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.update_alias abstractmethod

update_alias(alias: str) -> bool

Update an alias to point to this index.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def update_alias(self, alias: str) -> bool:
    """Update an alias to point to this index."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.RedisSearchHandlePort.delete_alias abstractmethod

delete_alias(alias: str) -> bool

Delete an alias.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
def delete_alias(self, alias: str) -> bool:
    """Delete an alias."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort

Asynchronous index-bound RediSearch operations contract.

Source code in archipy/adapters/redis/search_ports.py
class AsyncRedisSearchHandlePort:
    """Asynchronous index-bound RediSearch operations contract."""

    @abstractmethod
    async def create_index(
        self,
        schema: IndexSchemaDTO,
        prefix: str,
        index_type: RedisIndexType | None = None,
        **kwargs: Any,
    ) -> bool:
        """Create a RediSearch index asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def drop_index(self, delete_documents: bool = False) -> bool:
        """Drop the RediSearch index asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def info(self) -> dict[str, Any]:
        """Return index metadata asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def alter_schema_add(
        self,
        fields: IndexFieldConfig | list[IndexFieldConfig],
        *,
        index_type: RedisIndexType | None = None,
    ) -> bool:
        """Add fields to an existing index schema asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def upsert_hash(
        self,
        doc_id: str,
        fields: dict[str, str | int | float],
        vector_field: str | None = None,
        vector: list[float] | None = None,
        *,
        replace: bool = True,
    ) -> bool:
        """Upsert a HASH document and index it asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
        """Upsert a HASH document from a DTO asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def upsert_json(
        self,
        doc_id: str,
        payload: dict[str, str | int | float | list[float]],
        json_path: str = "$",
    ) -> bool:
        """Upsert a JSON document asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
        """Upsert a JSON document from a DTO asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def get_document(self, doc_id: str) -> dict[str, Any]:
        """Load a document by ID asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
        """Remove a document from the index asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
        """Execute a RediSearch query asynchronously (text, KNN, or hybrid)."""
        raise NotImplementedError

    @abstractmethod
    async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
        """Execute a RediSearch aggregation asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def add_alias(self, alias: str) -> bool:
        """Add an alias for the index asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def update_alias(self, alias: str) -> bool:
        """Update an alias to point to this index asynchronously."""
        raise NotImplementedError

    @abstractmethod
    async def delete_alias(self, alias: str) -> bool:
        """Delete an alias asynchronously."""
        raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.create_index abstractmethod async

create_index(
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool

Create a RediSearch index asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def create_index(
    self,
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool:
    """Create a RediSearch index asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.drop_index abstractmethod async

drop_index(delete_documents: bool = False) -> bool

Drop the RediSearch index asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def drop_index(self, delete_documents: bool = False) -> bool:
    """Drop the RediSearch index asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.info abstractmethod async

info() -> dict[str, Any]

Return index metadata asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def info(self) -> dict[str, Any]:
    """Return index metadata asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.alter_schema_add abstractmethod async

alter_schema_add(
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool

Add fields to an existing index schema asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def alter_schema_add(
    self,
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool:
    """Add fields to an existing index schema asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.upsert_hash abstractmethod async

upsert_hash(
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool

Upsert a HASH document and index it asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def upsert_hash(
    self,
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool:
    """Upsert a HASH document and index it asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.upsert_hash_dto abstractmethod async

upsert_hash_dto(
    document: HashDocumentUpsertDTO, *, replace: bool = True
) -> bool

Upsert a HASH document from a DTO asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
    """Upsert a HASH document from a DTO asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.upsert_json abstractmethod async

upsert_json(
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool

Upsert a JSON document asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def upsert_json(
    self,
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool:
    """Upsert a JSON document asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.upsert_json_dto abstractmethod async

upsert_json_dto(document: JsonDocumentUpsertDTO) -> bool

Upsert a JSON document from a DTO asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
    """Upsert a JSON document from a DTO asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.get_document abstractmethod async

get_document(doc_id: str) -> dict[str, Any]

Load a document by ID asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def get_document(self, doc_id: str) -> dict[str, Any]:
    """Load a document by ID asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.delete_document abstractmethod async

delete_document(
    doc_id: str, *, delete_actual_document: bool = True
) -> int

Remove a document from the index asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
    """Remove a document from the index asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.search abstractmethod async

search(
    query: SearchQueryDTO, **kwargs: Any
) -> SearchResultDTO

Execute a RediSearch query asynchronously (text, KNN, or hybrid).

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
    """Execute a RediSearch query asynchronously (text, KNN, or hybrid)."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.aggregate abstractmethod async

aggregate(
    aggregation: AggregationDTO, **kwargs: Any
) -> dict[str, Any]

Execute a RediSearch aggregation asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
    """Execute a RediSearch aggregation asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.add_alias abstractmethod async

add_alias(alias: str) -> bool

Add an alias for the index asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def add_alias(self, alias: str) -> bool:
    """Add an alias for the index asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.update_alias abstractmethod async

update_alias(alias: str) -> bool

Update an alias to point to this index asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def update_alias(self, alias: str) -> bool:
    """Update an alias to point to this index asynchronously."""
    raise NotImplementedError

archipy.adapters.redis.search_ports.AsyncRedisSearchHandlePort.delete_alias abstractmethod async

delete_alias(alias: str) -> bool

Delete an alias asynchronously.

Source code in archipy/adapters/redis/search_ports.py
@abstractmethod
async def delete_alias(self, alias: str) -> bool:
    """Delete an alias asynchronously."""
    raise NotImplementedError

options: show_root_toc_entry: false heading_level: 3

Search Adapters

Concrete RediSearch handle implementations, plus pack_vector() and unpack_vector() helpers for float32 vector encoding. Supports FLAT, HNSW, and SVS-VAMANA vector indexes, KNN and VECTOR_RANGE queries, and runtime tuning parameters including cluster shard_k_ratio.

Redis Search adapter implementations.

archipy.adapters.redis.search.RedisSearchHandle

Bases: RedisSearchHandlePort

Synchronous index-bound RediSearch handle.

Source code in archipy/adapters/redis/search.py
class RedisSearchHandle(RedisSearchHandlePort):
    """Synchronous index-bound RediSearch handle."""

    def __init__(self, client: Redis | RedisCluster, index_name: str) -> None:
        """Initialize the handle.

        Args:
            client: Binary-safe Redis client (`decode_responses=False`).
            index_name: RediSearch index name.
        """
        self._client = client
        self._index_name = index_name
        self._search = Search(client, index_name)
        self._index_type: RedisIndexType | None = None

    def _effective_index_type(self) -> RedisIndexType | None:
        """Return the cached index type or resolve it from FT.INFO."""
        if self._index_type is not None:
            return self._index_type
        resolved = _index_type_from_info(_normalize_info_dict(dict(self._search.info())))
        if resolved is not None:
            self._index_type = resolved
        return resolved

    @override
    def create_index(
        self,
        schema: IndexSchemaDTO,
        prefix: str,
        index_type: RedisIndexType | None = None,
        **kwargs: Any,
    ) -> bool:
        """Create a RediSearch index."""
        resolved_type = index_type or schema.index_type
        self._index_type = resolved_type
        definition = IndexDefinition(prefix=[prefix], index_type=_resolve_index_type(resolved_type))
        return bool(
            self._search.create_index(
                _build_redis_fields(schema.fields, index_type=resolved_type),
                definition=definition,
                **kwargs,
            ),
        )

    @override
    def drop_index(self, delete_documents: bool = False) -> bool:
        """Drop the RediSearch index."""
        return bool(self._search.dropindex(delete_documents=delete_documents))

    @override
    def info(self) -> dict[str, Any]:
        """Return index metadata."""
        return _normalize_info_dict(dict(self._search.info()))

    @override
    def alter_schema_add(
        self,
        fields: IndexFieldConfig | list[IndexFieldConfig],
        *,
        index_type: RedisIndexType | None = None,
    ) -> bool:
        """Add fields to an existing index schema."""
        field_list = fields if isinstance(fields, list) else [fields]
        resolved_type = index_type or self._index_type or self._effective_index_type()
        redis_fields = _build_redis_fields(field_list, index_type=resolved_type)
        if len(redis_fields) == 1:
            return bool(self._search.alter_schema_add(redis_fields[0]))
        return bool(self._search.alter_schema_add(redis_fields))

    @override
    def upsert_hash(
        self,
        doc_id: str,
        fields: dict[str, str | int | float],
        vector_field: str | None = None,
        vector: list[float] | None = None,
        *,
        replace: bool = True,
    ) -> bool:
        """Upsert a HASH document and index it."""
        _write_hash_document(self._client, doc_id, fields, vector_field, vector)
        return True

    @override
    def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
        """Upsert a HASH document from a DTO."""
        return self.upsert_hash(
            document.doc_id,
            document.fields,
            vector_field=document.vector_field,
            vector=document.vector,
            replace=replace,
        )

    @override
    def upsert_json(
        self,
        doc_id: str,
        payload: dict[str, str | int | float | list[float]],
        json_path: str = "$",
    ) -> bool:
        """Upsert a JSON document."""
        self._client.json().set(doc_id, json_path, payload)
        return True

    @override
    def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
        """Upsert a JSON document from a DTO."""
        return self.upsert_json(document.doc_id, document.payload, document.json_path)

    @override
    def get_document(self, doc_id: str) -> dict[str, Any]:
        """Load a document by ID."""
        key_type = _normalize_key_type(self._client.type(doc_id))
        if key_type == "ReJSON-RL":
            payload = _normalize_json_payload(self._client.json().get(doc_id, "$"))
            return {"id": doc_id, **payload}
        document = self._search.load_document(doc_id)
        return {"id": document.id, **_document_fields(document)}

    @override
    def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
        """Remove a document from the index."""
        return int(self._search.delete_document(doc_id, delete_actual_document=delete_actual_document))

    @override
    def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
        """Execute a RediSearch query."""
        if query.is_hybrid:
            redis_query, query_params = _build_hybrid_search_query(query)
            if kwargs.pop("raw", False):
                return cast(
                    "SearchResultDTO",
                    self._search.search(redis_query, query_params=query_params, **kwargs),
                )
            result = self._search.search(redis_query, query_params=query_params, **kwargs)
            return _result_to_dto(result)

        if query.is_range:
            redis_query, query_params = _build_range_query(query)
            if kwargs.pop("raw", False):
                return cast("SearchResultDTO", self._search.search(redis_query, query_params=query_params, **kwargs))
            result = self._search.search(redis_query, query_params=query_params, **kwargs)
            return _result_to_dto(result)

        redis_query, query_params = _build_search_query(query)
        if kwargs.pop("raw", False):
            return cast("SearchResultDTO", self._search.search(redis_query, query_params=query_params, **kwargs))
        result = self._search.search(redis_query, query_params=query_params, **kwargs)
        return _result_to_dto(result)

    @override
    def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
        """Execute a RediSearch aggregation."""
        request = _build_aggregate_request(aggregation)
        if kwargs.pop("raw", False):
            return cast("dict[str, Any]", self._search.aggregate(request, **kwargs))
        result = self._search.aggregate(request, **kwargs)
        if isinstance(result, dict):
            norm = {k.decode() if isinstance(k, bytes) else k: v for k, v in result.items()}
            return {
                "total": norm.get("total_results", 0),
                "rows": [row.get("extra_attributes", row) for row in norm.get("results", [])],
            }
        return {"total": result.total, "rows": result.rows}

    @override
    def add_alias(self, alias: str) -> bool:
        """Add an alias for the index."""
        return bool(self._search.aliasadd(alias))

    @override
    def update_alias(self, alias: str) -> bool:
        """Update an alias to point to this index."""
        return bool(self._search.aliasupdate(alias))

    @override
    def delete_alias(self, alias: str) -> bool:
        """Delete an alias."""
        return bool(self._search.aliasdel(alias))

archipy.adapters.redis.search.RedisSearchHandle.create_index

create_index(
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool

Create a RediSearch index.

Source code in archipy/adapters/redis/search.py
@override
def create_index(
    self,
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool:
    """Create a RediSearch index."""
    resolved_type = index_type or schema.index_type
    self._index_type = resolved_type
    definition = IndexDefinition(prefix=[prefix], index_type=_resolve_index_type(resolved_type))
    return bool(
        self._search.create_index(
            _build_redis_fields(schema.fields, index_type=resolved_type),
            definition=definition,
            **kwargs,
        ),
    )

archipy.adapters.redis.search.RedisSearchHandle.drop_index

drop_index(delete_documents: bool = False) -> bool

Drop the RediSearch index.

Source code in archipy/adapters/redis/search.py
@override
def drop_index(self, delete_documents: bool = False) -> bool:
    """Drop the RediSearch index."""
    return bool(self._search.dropindex(delete_documents=delete_documents))

archipy.adapters.redis.search.RedisSearchHandle.info

info() -> dict[str, Any]

Return index metadata.

Source code in archipy/adapters/redis/search.py
@override
def info(self) -> dict[str, Any]:
    """Return index metadata."""
    return _normalize_info_dict(dict(self._search.info()))

archipy.adapters.redis.search.RedisSearchHandle.alter_schema_add

alter_schema_add(
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool

Add fields to an existing index schema.

Source code in archipy/adapters/redis/search.py
@override
def alter_schema_add(
    self,
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool:
    """Add fields to an existing index schema."""
    field_list = fields if isinstance(fields, list) else [fields]
    resolved_type = index_type or self._index_type or self._effective_index_type()
    redis_fields = _build_redis_fields(field_list, index_type=resolved_type)
    if len(redis_fields) == 1:
        return bool(self._search.alter_schema_add(redis_fields[0]))
    return bool(self._search.alter_schema_add(redis_fields))

archipy.adapters.redis.search.RedisSearchHandle.upsert_hash

upsert_hash(
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool

Upsert a HASH document and index it.

Source code in archipy/adapters/redis/search.py
@override
def upsert_hash(
    self,
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool:
    """Upsert a HASH document and index it."""
    _write_hash_document(self._client, doc_id, fields, vector_field, vector)
    return True

archipy.adapters.redis.search.RedisSearchHandle.upsert_hash_dto

upsert_hash_dto(
    document: HashDocumentUpsertDTO, *, replace: bool = True
) -> bool

Upsert a HASH document from a DTO.

Source code in archipy/adapters/redis/search.py
@override
def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
    """Upsert a HASH document from a DTO."""
    return self.upsert_hash(
        document.doc_id,
        document.fields,
        vector_field=document.vector_field,
        vector=document.vector,
        replace=replace,
    )

archipy.adapters.redis.search.RedisSearchHandle.upsert_json

upsert_json(
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool

Upsert a JSON document.

Source code in archipy/adapters/redis/search.py
@override
def upsert_json(
    self,
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool:
    """Upsert a JSON document."""
    self._client.json().set(doc_id, json_path, payload)
    return True

archipy.adapters.redis.search.RedisSearchHandle.upsert_json_dto

upsert_json_dto(document: JsonDocumentUpsertDTO) -> bool

Upsert a JSON document from a DTO.

Source code in archipy/adapters/redis/search.py
@override
def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
    """Upsert a JSON document from a DTO."""
    return self.upsert_json(document.doc_id, document.payload, document.json_path)

archipy.adapters.redis.search.RedisSearchHandle.get_document

get_document(doc_id: str) -> dict[str, Any]

Load a document by ID.

Source code in archipy/adapters/redis/search.py
@override
def get_document(self, doc_id: str) -> dict[str, Any]:
    """Load a document by ID."""
    key_type = _normalize_key_type(self._client.type(doc_id))
    if key_type == "ReJSON-RL":
        payload = _normalize_json_payload(self._client.json().get(doc_id, "$"))
        return {"id": doc_id, **payload}
    document = self._search.load_document(doc_id)
    return {"id": document.id, **_document_fields(document)}

archipy.adapters.redis.search.RedisSearchHandle.delete_document

delete_document(
    doc_id: str, *, delete_actual_document: bool = True
) -> int

Remove a document from the index.

Source code in archipy/adapters/redis/search.py
@override
def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
    """Remove a document from the index."""
    return int(self._search.delete_document(doc_id, delete_actual_document=delete_actual_document))

archipy.adapters.redis.search.RedisSearchHandle.search

search(
    query: SearchQueryDTO, **kwargs: Any
) -> SearchResultDTO

Execute a RediSearch query.

Source code in archipy/adapters/redis/search.py
@override
def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
    """Execute a RediSearch query."""
    if query.is_hybrid:
        redis_query, query_params = _build_hybrid_search_query(query)
        if kwargs.pop("raw", False):
            return cast(
                "SearchResultDTO",
                self._search.search(redis_query, query_params=query_params, **kwargs),
            )
        result = self._search.search(redis_query, query_params=query_params, **kwargs)
        return _result_to_dto(result)

    if query.is_range:
        redis_query, query_params = _build_range_query(query)
        if kwargs.pop("raw", False):
            return cast("SearchResultDTO", self._search.search(redis_query, query_params=query_params, **kwargs))
        result = self._search.search(redis_query, query_params=query_params, **kwargs)
        return _result_to_dto(result)

    redis_query, query_params = _build_search_query(query)
    if kwargs.pop("raw", False):
        return cast("SearchResultDTO", self._search.search(redis_query, query_params=query_params, **kwargs))
    result = self._search.search(redis_query, query_params=query_params, **kwargs)
    return _result_to_dto(result)

archipy.adapters.redis.search.RedisSearchHandle.aggregate

aggregate(
    aggregation: AggregationDTO, **kwargs: Any
) -> dict[str, Any]

Execute a RediSearch aggregation.

Source code in archipy/adapters/redis/search.py
@override
def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
    """Execute a RediSearch aggregation."""
    request = _build_aggregate_request(aggregation)
    if kwargs.pop("raw", False):
        return cast("dict[str, Any]", self._search.aggregate(request, **kwargs))
    result = self._search.aggregate(request, **kwargs)
    if isinstance(result, dict):
        norm = {k.decode() if isinstance(k, bytes) else k: v for k, v in result.items()}
        return {
            "total": norm.get("total_results", 0),
            "rows": [row.get("extra_attributes", row) for row in norm.get("results", [])],
        }
    return {"total": result.total, "rows": result.rows}

archipy.adapters.redis.search.RedisSearchHandle.add_alias

add_alias(alias: str) -> bool

Add an alias for the index.

Source code in archipy/adapters/redis/search.py
@override
def add_alias(self, alias: str) -> bool:
    """Add an alias for the index."""
    return bool(self._search.aliasadd(alias))

archipy.adapters.redis.search.RedisSearchHandle.update_alias

update_alias(alias: str) -> bool

Update an alias to point to this index.

Source code in archipy/adapters/redis/search.py
@override
def update_alias(self, alias: str) -> bool:
    """Update an alias to point to this index."""
    return bool(self._search.aliasupdate(alias))

archipy.adapters.redis.search.RedisSearchHandle.delete_alias

delete_alias(alias: str) -> bool

Delete an alias.

Source code in archipy/adapters/redis/search.py
@override
def delete_alias(self, alias: str) -> bool:
    """Delete an alias."""
    return bool(self._search.aliasdel(alias))

archipy.adapters.redis.search.AsyncRedisSearchHandle

Bases: AsyncRedisSearchHandlePort

Asynchronous index-bound RediSearch handle.

Source code in archipy/adapters/redis/search.py
class AsyncRedisSearchHandle(AsyncRedisSearchHandlePort):
    """Asynchronous index-bound RediSearch handle."""

    def __init__(self, client: AsyncRedis | AsyncRedisCluster, index_name: str) -> None:
        """Initialize the async handle.

        Args:
            client: Binary-safe async Redis client (`decode_responses=False`).
            index_name: RediSearch index name.
        """
        self._client = client
        self._index_name = index_name
        self._search = Search(client, index_name)
        self._index_type: RedisIndexType | None = None

    async def _effective_index_type(self) -> RedisIndexType | None:
        """Return the cached index type or resolve it from FT.INFO asynchronously."""
        if self._index_type is not None:
            return self._index_type
        info = await self._await_result(self._search.info())
        resolved = _index_type_from_info(_normalize_info_dict(dict(info)))
        if resolved is not None:
            self._index_type = resolved
        return resolved

    async def _await_result(self, value: Any) -> Any:
        """Await a result when the underlying client returns a coroutine."""
        if isinstance(value, Awaitable):
            return await value
        return value

    @override
    async def create_index(
        self,
        schema: IndexSchemaDTO,
        prefix: str,
        index_type: RedisIndexType | None = None,
        **kwargs: Any,
    ) -> bool:
        """Create a RediSearch index asynchronously."""
        resolved_type = index_type or schema.index_type
        self._index_type = resolved_type
        definition = IndexDefinition(prefix=[prefix], index_type=_resolve_index_type(resolved_type))
        result = await self._await_result(
            self._search.create_index(
                _build_redis_fields(schema.fields, index_type=resolved_type),
                definition=definition,
                **kwargs,
            ),
        )
        return bool(result)

    @override
    async def drop_index(self, delete_documents: bool = False) -> bool:
        """Drop the RediSearch index asynchronously."""
        result = await self._await_result(self._search.dropindex(delete_documents=delete_documents))
        return bool(result)

    @override
    async def info(self) -> dict[str, Any]:
        """Return index metadata asynchronously."""
        result = await self._await_result(self._search.info())
        return _normalize_info_dict(dict(result))

    @override
    async def alter_schema_add(
        self,
        fields: IndexFieldConfig | list[IndexFieldConfig],
        *,
        index_type: RedisIndexType | None = None,
    ) -> bool:
        """Add fields to an existing index schema asynchronously."""
        field_list = fields if isinstance(fields, list) else [fields]
        resolved_type = index_type or self._index_type or await self._effective_index_type()
        redis_fields = _build_redis_fields(field_list, index_type=resolved_type)
        if len(redis_fields) == 1:
            result = await self._await_result(self._search.alter_schema_add(redis_fields[0]))
        else:
            result = await self._await_result(self._search.alter_schema_add(redis_fields))
        return bool(result)

    @override
    async def upsert_hash(
        self,
        doc_id: str,
        fields: dict[str, str | int | float],
        vector_field: str | None = None,
        vector: list[float] | None = None,
        *,
        replace: bool = True,
    ) -> bool:
        """Upsert a HASH document and index it asynchronously."""
        for key, value in fields.items():
            await self._client.hset(doc_id, key, value)
        if vector_field is not None and vector is not None:
            await self._client.hset(doc_id, vector_field, pack_vector(vector))
        return True

    @override
    async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
        """Upsert a HASH document from a DTO asynchronously."""
        return await self.upsert_hash(
            document.doc_id,
            document.fields,
            vector_field=document.vector_field,
            vector=document.vector,
            replace=replace,
        )

    @override
    async def upsert_json(
        self,
        doc_id: str,
        payload: dict[str, str | int | float | list[float]],
        json_path: str = "$",
    ) -> bool:
        """Upsert a JSON document asynchronously."""
        await self._client.json().set(doc_id, json_path, payload)
        return True

    @override
    async def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
        """Upsert a JSON document from a DTO asynchronously."""
        return await self.upsert_json(document.doc_id, document.payload, document.json_path)

    @override
    async def get_document(self, doc_id: str) -> dict[str, Any]:
        """Load a document by ID asynchronously."""
        key_type = _normalize_key_type(await self._client.type(doc_id))
        if key_type == "ReJSON-RL":
            payload = _normalize_json_payload(await self._await_result(self._client.json().get(doc_id, "$")))
            return {"id": doc_id, **payload}
        document = await self._await_result(self._search.load_document(doc_id))
        return {"id": document.id, **_document_fields(document)}

    @override
    async def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
        """Remove a document from the index asynchronously."""
        result = await self._await_result(
            self._search.delete_document(doc_id, delete_actual_document=delete_actual_document),
        )
        return int(result)

    @override
    async def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
        """Execute a RediSearch query asynchronously."""
        if query.is_hybrid:
            redis_query, query_params = _build_hybrid_search_query(query)
            if kwargs.pop("raw", False):
                return cast(
                    "SearchResultDTO",
                    await self._await_result(
                        self._search.search(redis_query, query_params=query_params, **kwargs),
                    ),
                )
            result = await self._await_result(
                self._search.search(redis_query, query_params=query_params, **kwargs),
            )
            return _result_to_dto(result)

        if query.is_range:
            redis_query, query_params = _build_range_query(query)
            if kwargs.pop("raw", False):
                return cast(
                    "SearchResultDTO",
                    await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs)),
                )
            result = await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs))
            return _result_to_dto(result)

        redis_query, query_params = _build_search_query(query)
        if kwargs.pop("raw", False):
            return cast(
                "SearchResultDTO",
                await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs)),
            )
        result = await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs))
        return _result_to_dto(result)

    @override
    async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
        """Execute a RediSearch aggregation asynchronously."""
        request = _build_aggregate_request(aggregation)
        if kwargs.pop("raw", False):
            return cast("dict[str, Any]", await self._await_result(self._search.aggregate(request, **kwargs)))
        result = await self._await_result(self._search.aggregate(request, **kwargs))
        return {"total": result.total, "rows": result.rows}

    @override
    async def add_alias(self, alias: str) -> bool:
        """Add an alias for the index asynchronously."""
        result = await self._await_result(self._search.aliasadd(alias))
        return bool(result)

    @override
    async def update_alias(self, alias: str) -> bool:
        """Update an alias to point to this index asynchronously."""
        result = await self._await_result(self._search.aliasupdate(alias))
        return bool(result)

    @override
    async def delete_alias(self, alias: str) -> bool:
        """Delete an alias asynchronously."""
        result = await self._await_result(self._search.aliasdel(alias))
        return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.create_index async

create_index(
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool

Create a RediSearch index asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def create_index(
    self,
    schema: IndexSchemaDTO,
    prefix: str,
    index_type: RedisIndexType | None = None,
    **kwargs: Any,
) -> bool:
    """Create a RediSearch index asynchronously."""
    resolved_type = index_type or schema.index_type
    self._index_type = resolved_type
    definition = IndexDefinition(prefix=[prefix], index_type=_resolve_index_type(resolved_type))
    result = await self._await_result(
        self._search.create_index(
            _build_redis_fields(schema.fields, index_type=resolved_type),
            definition=definition,
            **kwargs,
        ),
    )
    return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.drop_index async

drop_index(delete_documents: bool = False) -> bool

Drop the RediSearch index asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def drop_index(self, delete_documents: bool = False) -> bool:
    """Drop the RediSearch index asynchronously."""
    result = await self._await_result(self._search.dropindex(delete_documents=delete_documents))
    return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.info async

info() -> dict[str, Any]

Return index metadata asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def info(self) -> dict[str, Any]:
    """Return index metadata asynchronously."""
    result = await self._await_result(self._search.info())
    return _normalize_info_dict(dict(result))

archipy.adapters.redis.search.AsyncRedisSearchHandle.alter_schema_add async

alter_schema_add(
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool

Add fields to an existing index schema asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def alter_schema_add(
    self,
    fields: IndexFieldConfig | list[IndexFieldConfig],
    *,
    index_type: RedisIndexType | None = None,
) -> bool:
    """Add fields to an existing index schema asynchronously."""
    field_list = fields if isinstance(fields, list) else [fields]
    resolved_type = index_type or self._index_type or await self._effective_index_type()
    redis_fields = _build_redis_fields(field_list, index_type=resolved_type)
    if len(redis_fields) == 1:
        result = await self._await_result(self._search.alter_schema_add(redis_fields[0]))
    else:
        result = await self._await_result(self._search.alter_schema_add(redis_fields))
    return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.upsert_hash async

upsert_hash(
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool

Upsert a HASH document and index it asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def upsert_hash(
    self,
    doc_id: str,
    fields: dict[str, str | int | float],
    vector_field: str | None = None,
    vector: list[float] | None = None,
    *,
    replace: bool = True,
) -> bool:
    """Upsert a HASH document and index it asynchronously."""
    for key, value in fields.items():
        await self._client.hset(doc_id, key, value)
    if vector_field is not None and vector is not None:
        await self._client.hset(doc_id, vector_field, pack_vector(vector))
    return True

archipy.adapters.redis.search.AsyncRedisSearchHandle.upsert_hash_dto async

upsert_hash_dto(
    document: HashDocumentUpsertDTO, *, replace: bool = True
) -> bool

Upsert a HASH document from a DTO asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool:
    """Upsert a HASH document from a DTO asynchronously."""
    return await self.upsert_hash(
        document.doc_id,
        document.fields,
        vector_field=document.vector_field,
        vector=document.vector,
        replace=replace,
    )

archipy.adapters.redis.search.AsyncRedisSearchHandle.upsert_json async

upsert_json(
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool

Upsert a JSON document asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def upsert_json(
    self,
    doc_id: str,
    payload: dict[str, str | int | float | list[float]],
    json_path: str = "$",
) -> bool:
    """Upsert a JSON document asynchronously."""
    await self._client.json().set(doc_id, json_path, payload)
    return True

archipy.adapters.redis.search.AsyncRedisSearchHandle.upsert_json_dto async

upsert_json_dto(document: JsonDocumentUpsertDTO) -> bool

Upsert a JSON document from a DTO asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def upsert_json_dto(self, document: JsonDocumentUpsertDTO) -> bool:
    """Upsert a JSON document from a DTO asynchronously."""
    return await self.upsert_json(document.doc_id, document.payload, document.json_path)

archipy.adapters.redis.search.AsyncRedisSearchHandle.get_document async

get_document(doc_id: str) -> dict[str, Any]

Load a document by ID asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def get_document(self, doc_id: str) -> dict[str, Any]:
    """Load a document by ID asynchronously."""
    key_type = _normalize_key_type(await self._client.type(doc_id))
    if key_type == "ReJSON-RL":
        payload = _normalize_json_payload(await self._await_result(self._client.json().get(doc_id, "$")))
        return {"id": doc_id, **payload}
    document = await self._await_result(self._search.load_document(doc_id))
    return {"id": document.id, **_document_fields(document)}

archipy.adapters.redis.search.AsyncRedisSearchHandle.delete_document async

delete_document(
    doc_id: str, *, delete_actual_document: bool = True
) -> int

Remove a document from the index asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def delete_document(self, doc_id: str, *, delete_actual_document: bool = True) -> int:
    """Remove a document from the index asynchronously."""
    result = await self._await_result(
        self._search.delete_document(doc_id, delete_actual_document=delete_actual_document),
    )
    return int(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.search async

search(
    query: SearchQueryDTO, **kwargs: Any
) -> SearchResultDTO

Execute a RediSearch query asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def search(self, query: SearchQueryDTO, **kwargs: Any) -> SearchResultDTO:
    """Execute a RediSearch query asynchronously."""
    if query.is_hybrid:
        redis_query, query_params = _build_hybrid_search_query(query)
        if kwargs.pop("raw", False):
            return cast(
                "SearchResultDTO",
                await self._await_result(
                    self._search.search(redis_query, query_params=query_params, **kwargs),
                ),
            )
        result = await self._await_result(
            self._search.search(redis_query, query_params=query_params, **kwargs),
        )
        return _result_to_dto(result)

    if query.is_range:
        redis_query, query_params = _build_range_query(query)
        if kwargs.pop("raw", False):
            return cast(
                "SearchResultDTO",
                await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs)),
            )
        result = await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs))
        return _result_to_dto(result)

    redis_query, query_params = _build_search_query(query)
    if kwargs.pop("raw", False):
        return cast(
            "SearchResultDTO",
            await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs)),
        )
    result = await self._await_result(self._search.search(redis_query, query_params=query_params, **kwargs))
    return _result_to_dto(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.aggregate async

aggregate(
    aggregation: AggregationDTO, **kwargs: Any
) -> dict[str, Any]

Execute a RediSearch aggregation asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any]:
    """Execute a RediSearch aggregation asynchronously."""
    request = _build_aggregate_request(aggregation)
    if kwargs.pop("raw", False):
        return cast("dict[str, Any]", await self._await_result(self._search.aggregate(request, **kwargs)))
    result = await self._await_result(self._search.aggregate(request, **kwargs))
    return {"total": result.total, "rows": result.rows}

archipy.adapters.redis.search.AsyncRedisSearchHandle.add_alias async

add_alias(alias: str) -> bool

Add an alias for the index asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def add_alias(self, alias: str) -> bool:
    """Add an alias for the index asynchronously."""
    result = await self._await_result(self._search.aliasadd(alias))
    return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.update_alias async

update_alias(alias: str) -> bool

Update an alias to point to this index asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def update_alias(self, alias: str) -> bool:
    """Update an alias to point to this index asynchronously."""
    result = await self._await_result(self._search.aliasupdate(alias))
    return bool(result)

archipy.adapters.redis.search.AsyncRedisSearchHandle.delete_alias async

delete_alias(alias: str) -> bool

Delete an alias asynchronously.

Source code in archipy/adapters/redis/search.py
@override
async def delete_alias(self, alias: str) -> bool:
    """Delete an alias asynchronously."""
    result = await self._await_result(self._search.aliasdel(alias))
    return bool(result)

archipy.adapters.redis.search.list_redis_search_indexes

list_redis_search_indexes(
    client: Redis | RedisCluster,
) -> list[str]

List RediSearch index names from a standalone or cluster client.

Source code in archipy/adapters/redis/search.py
def list_redis_search_indexes(client: Redis | RedisCluster) -> list[str]:
    """List RediSearch index names from a standalone or cluster client."""
    if isinstance(client, RedisCluster):
        target_node = _cluster_ft_list_target(client)
        if target_node is None:
            return []
        result = client.execute_command("FT._LIST", target_nodes=target_node)
    else:
        result = client.execute_command("FT._LIST")
    return _normalize_index_names(result)

archipy.adapters.redis.search.list_redis_search_indexes_async async

list_redis_search_indexes_async(
    client: Redis | RedisCluster,
) -> list[str]

List RediSearch index names from an async standalone or cluster client.

Source code in archipy/adapters/redis/search.py
async def list_redis_search_indexes_async(client: AsyncRedis | AsyncRedisCluster) -> list[str]:
    """List RediSearch index names from an async standalone or cluster client."""
    if isinstance(client, AsyncRedisCluster):
        target_node = _cluster_ft_list_target(client)
        if target_node is None:
            return []
        result = await client.execute_command("FT._LIST", target_nodes=target_node)
    else:
        result = client.execute_command("FT._LIST")
        if isinstance(result, Awaitable):
            result = await result
    return _normalize_index_names(result)

archipy.adapters.redis.search.pack_vector

pack_vector(vector: list[float]) -> bytes

Pack a float vector into float32 little-endian bytes for RediSearch.

Parameters:

Name Type Description Default
vector list[float]

Embedding values.

required

Returns:

Type Description
bytes

Binary blob suitable for Redis VECTOR fields and KNN params.

Source code in archipy/adapters/redis/search.py
def pack_vector(vector: list[float]) -> bytes:
    """Pack a float vector into float32 little-endian bytes for RediSearch.

    Args:
        vector: Embedding values.

    Returns:
        Binary blob suitable for Redis VECTOR fields and KNN params.
    """
    return struct.pack(f"{len(vector)}f", *vector)

archipy.adapters.redis.search.unpack_vector

unpack_vector(blob: bytes, dim: int) -> list[float]

Unpack float32 little-endian bytes into a vector.

Parameters:

Name Type Description Default
blob bytes

Binary vector data from Redis.

required
dim int

Expected vector dimensionality.

required

Returns:

Type Description
list[float]

Decoded embedding values.

Source code in archipy/adapters/redis/search.py
def unpack_vector(blob: bytes, dim: int) -> list[float]:
    """Unpack float32 little-endian bytes into a vector.

    Args:
        blob: Binary vector data from Redis.
        dim: Expected vector dimensionality.

    Returns:
        Decoded embedding values.
    """
    return list(struct.unpack(f"{dim}f", blob))

options: show_root_toc_entry: false heading_level: 3

Mocks

In-memory mock implementation of the Redis port for use in unit tests and BDD scenarios.

Mock Redis adapters for testing.

archipy.adapters.redis.mocks.FakeRedisClusterWrapper

Bases: FakeRedis

Wrapper around FakeRedis that adds cluster-specific methods.

Source code in archipy/adapters/redis/mocks.py
class FakeRedisClusterWrapper(fakeredis.FakeRedis):
    """Wrapper around FakeRedis that adds cluster-specific methods."""

    def cluster_info(self) -> dict[str, Any]:
        """Return fake cluster info."""
        return _fake_cluster_info()

    def cluster_nodes(self) -> str:
        """Return fake cluster nodes info."""
        return "fake cluster nodes info"

    def cluster_slots(self) -> list[tuple[int, int, list[str]]]:
        """Return fake cluster slots info."""
        return _fake_cluster_slots()

    def cluster_keyslot(self, key: str) -> int:
        """Return fake cluster keyslot for a key."""
        return hash(key) % 16384

    def cluster_countkeysinslot(self, slot: int) -> int:
        """Return fake count of keys in a slot."""
        return 0

    def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[str]:
        """Return fake keys in a slot."""
        return []

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_info

cluster_info() -> dict[str, Any]

Return fake cluster info.

Source code in archipy/adapters/redis/mocks.py
def cluster_info(self) -> dict[str, Any]:
    """Return fake cluster info."""
    return _fake_cluster_info()

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_nodes

cluster_nodes() -> str

Return fake cluster nodes info.

Source code in archipy/adapters/redis/mocks.py
def cluster_nodes(self) -> str:
    """Return fake cluster nodes info."""
    return "fake cluster nodes info"

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_slots

cluster_slots() -> list[tuple[int, int, list[str]]]

Return fake cluster slots info.

Source code in archipy/adapters/redis/mocks.py
def cluster_slots(self) -> list[tuple[int, int, list[str]]]:
    """Return fake cluster slots info."""
    return _fake_cluster_slots()

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_keyslot

cluster_keyslot(key: str) -> int

Return fake cluster keyslot for a key.

Source code in archipy/adapters/redis/mocks.py
def cluster_keyslot(self, key: str) -> int:
    """Return fake cluster keyslot for a key."""
    return hash(key) % 16384

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_countkeysinslot

cluster_countkeysinslot(slot: int) -> int

Return fake count of keys in a slot.

Source code in archipy/adapters/redis/mocks.py
def cluster_countkeysinslot(self, slot: int) -> int:
    """Return fake count of keys in a slot."""
    return 0

archipy.adapters.redis.mocks.FakeRedisClusterWrapper.cluster_get_keys_in_slot

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[str]

Return fake keys in a slot.

Source code in archipy/adapters/redis/mocks.py
def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[str]:
    """Return fake keys in a slot."""
    return []

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper

Bases: FakeAsyncRedis

Wrapper around FakeAsyncRedis that adds cluster-specific methods.

Source code in archipy/adapters/redis/mocks.py
class FakeAsyncRedisClusterWrapper(FakeAsyncRedis):
    """Wrapper around FakeAsyncRedis that adds cluster-specific methods."""

    async def cluster_info(self) -> dict[str, Any]:
        """Return fake cluster info."""
        return _fake_cluster_info()

    async def cluster_nodes(self) -> str:
        """Return fake cluster nodes info."""
        return "fake cluster nodes info"

    async def cluster_slots(self) -> list[tuple[int, int, list[str]]]:
        """Return fake cluster slots info."""
        return _fake_cluster_slots()

    async def cluster_keyslot(self, key: str) -> int:
        """Return fake cluster keyslot for a key."""
        return hash(key) % 16384

    async def cluster_countkeysinslot(self, slot: int) -> int:
        """Return fake count of keys in a slot."""
        return 0

    async def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[str]:
        """Return fake keys in a slot."""
        return []

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_info async

cluster_info() -> dict[str, Any]

Return fake cluster info.

Source code in archipy/adapters/redis/mocks.py
async def cluster_info(self) -> dict[str, Any]:
    """Return fake cluster info."""
    return _fake_cluster_info()

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_nodes async

cluster_nodes() -> str

Return fake cluster nodes info.

Source code in archipy/adapters/redis/mocks.py
async def cluster_nodes(self) -> str:
    """Return fake cluster nodes info."""
    return "fake cluster nodes info"

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_slots async

cluster_slots() -> list[tuple[int, int, list[str]]]

Return fake cluster slots info.

Source code in archipy/adapters/redis/mocks.py
async def cluster_slots(self) -> list[tuple[int, int, list[str]]]:
    """Return fake cluster slots info."""
    return _fake_cluster_slots()

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_keyslot async

cluster_keyslot(key: str) -> int

Return fake cluster keyslot for a key.

Source code in archipy/adapters/redis/mocks.py
async def cluster_keyslot(self, key: str) -> int:
    """Return fake cluster keyslot for a key."""
    return hash(key) % 16384

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_countkeysinslot async

cluster_countkeysinslot(slot: int) -> int

Return fake count of keys in a slot.

Source code in archipy/adapters/redis/mocks.py
async def cluster_countkeysinslot(self, slot: int) -> int:
    """Return fake count of keys in a slot."""
    return 0

archipy.adapters.redis.mocks.FakeAsyncRedisClusterWrapper.cluster_get_keys_in_slot async

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[str]

Return fake keys in a slot.

Source code in archipy/adapters/redis/mocks.py
async def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[str]:
    """Return fake keys in a slot."""
    return []

archipy.adapters.redis.mocks.RedisMock

Bases: RedisAdapter

A Redis adapter implementation using fakeredis for testing.

Source code in archipy/adapters/redis/mocks.py
class RedisMock(RedisAdapter):
    """A Redis adapter implementation using fakeredis for testing."""

    def __init__(self, redis_config: RedisConfig | None = None) -> None:
        """Initialize RedisMock."""
        # Skip the parent's __init__ which would create real Redis connections
        self.config = redis_config or BaseConfig.global_config().REDIS
        self._configs = self.config
        self._server = FakeServer()
        self._search_client: Redis | RedisCluster | None = None

        # Create fake redis clients based on mode
        self._setup_fake_clients()

    def _setup_fake_clients(self) -> None:
        """Setup fake Redis clients that simulate different modes."""
        decode_responses = self.config.DECODE_RESPONSES
        if self.config.MODE == RedisMode.CLUSTER:
            fake_client: Redis = FakeRedisClusterWrapper(
                decode_responses=decode_responses,
                server=self._server,
            )
        else:
            fake_client = fakeredis.FakeRedis(
                decode_responses=decode_responses,
                server=self._server,
            )

        self.client = fake_client
        self.read_only_client = fake_client

    def _set_clients(self, configs: RedisConfig) -> None:
        # Override to prevent actual connection setup
        pass

    def _get_client(self, host: str, configs: RedisConfig, *, decode_responses: bool | None = None) -> Redis:
        return fakeredis.FakeRedis(
            decode_responses=configs.DECODE_RESPONSES if decode_responses is None else decode_responses,
            server=self._server,
        )

    def _get_search_client(self) -> Redis | RedisCluster:
        if self._search_client is None:
            self._search_client = fakeredis.FakeRedis(
                decode_responses=False,
                server=self._server,
            )
        return self._search_client

archipy.adapters.redis.mocks.RedisMock.config instance-attribute

config = redis_config or BaseConfig.global_config().REDIS

archipy.adapters.redis.mocks.RedisMock.client instance-attribute

client: Redis | RedisCluster

archipy.adapters.redis.mocks.RedisMock.read_only_client instance-attribute

read_only_client: Redis | RedisCluster

archipy.adapters.redis.mocks.RedisMock.publish

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publish a message to a channel.

Parameters:

Name Type Description Default
channel bytes | str

Channel name.

required
message bytes | str

Message to publish.

required
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType int

Number of subscribers that received the message.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publish a message to a channel.

    Args:
        channel (bytes | str): Channel name.
        message (bytes | str): Message to publish.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Number of subscribers that received the message.
    """
    return self.client.publish(channel, message, **kwargs)

archipy.adapters.redis.mocks.RedisMock.pubsub_channels

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

List active channels matching a pattern.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match channels. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of channel names.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """List active channels matching a pattern.

    Args:
        pattern (bytes | str): Pattern to match channels. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of channel names.
    """
    return self.client.pubsub_channels(pattern, **kwargs)

archipy.adapters.redis.mocks.RedisMock.pubsub

pubsub(**kwargs: Any) -> PubSub

Get a PubSub object for subscribing to channels.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
PubSub PubSub

PubSub object.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
def pubsub(self, **kwargs: Any) -> PubSub:
    """Get a PubSub object for subscribing to channels.

    Args:
        **kwargs (Any): Additional arguments.

    Returns:
        PubSub: PubSub object.
    """
    return self.client.pubsub(**kwargs)

archipy.adapters.redis.mocks.RedisMock.hdel

hdel(name: str, *keys: str | bytes) -> int

Delete fields from a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields deleted.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hdel(self, name: str, *keys: str | bytes) -> int:
    """Delete fields from a hash.

    Args:
        name (str): The hash key name.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: Number of fields deleted.
    """
    # Convert keys to str for type compatibility with Redis client
    str_keys: tuple[str, ...] = tuple(str(k) if isinstance(k, bytes) else k for k in keys)
    result = self.client.hdel(name, *str_keys)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.hexists

hexists(name: str, key: str) -> bool

Check if a field exists in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to check.

required

Returns:

Name Type Description
bool bool

True if field exists, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hexists(self, name: str, key: str) -> bool:
    """Check if a field exists in a hash.

    Args:
        name (str): The hash key name.
        key (str): Field to check.

    Returns:
        bool: True if field exists, False otherwise.
    """
    result = self.read_only_client.hexists(name, key)
    return bool(result)

archipy.adapters.redis.mocks.RedisMock.hget

hget(name: str, key: str) -> bytes | str | None

Get the value of a field in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to get.

required

Returns:

Type Description
bytes | str | None

str | None: Value of the field or None.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hget(self, name: str, key: str) -> bytes | str | None:
    """Get the value of a field in a hash.

    Args:
        name (str): The hash key name.
        key (str): Field to get.

    Returns:
        str | None: Value of the field or None.
    """
    return self.read_only_client.hget(name, key)

archipy.adapters.redis.mocks.RedisMock.hgetall

hgetall(name: str) -> dict[bytes | str, bytes | str]

Get all fields and values in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: Dictionary of field-value pairs.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Get all fields and values in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        dict[str, Any]: Dictionary of field-value pairs.
    """
    result = self.read_only_client.hgetall(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    if result:
        return {str(k): v for k, v in result.items()}
    return {}

archipy.adapters.redis.mocks.RedisMock.hkeys

hkeys(name: str) -> list[bytes | str]

Get all fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of field names.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hkeys(self, name: str) -> list[bytes | str]:
    """Get all fields in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of field names.
    """
    result = self.read_only_client.hkeys(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.mocks.RedisMock.hlen

hlen(name: str) -> int

Get the number of fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hlen(self, name: str) -> int:
    """Get the number of fields in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisIntegerResponseType: Number of fields.
    """
    result = self.read_only_client.hlen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.hset

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Set fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str | bytes | None

Single field name. Defaults to None.

None
value str | bytes | None

Single field value. Defaults to None.

None
mapping dict | None

Dictionary of field-value pairs. Defaults to None.

None
items list | None

List of field-value pairs. Defaults to None.

None

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields set.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Set fields in a hash.

    Args:
        name (str): The hash key name.
        key (str | bytes | None): Single field name. Defaults to None.
        value (str | bytes | None): Single field value. Defaults to None.
        mapping (dict | None): Dictionary of field-value pairs. Defaults to None.
        items (list | None): List of field-value pairs. Defaults to None.

    Returns:
        RedisIntegerResponseType: Number of fields set.
    """
    # Convert bytes to str for type compatibility with Redis client
    str_key: str | None = str(key) if key is not None and isinstance(key, bytes) else key
    str_value: str | None = str(value) if value is not None and isinstance(value, bytes) else value
    result = self.client.hset(name, str_key, str_value, mapping, items)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.hmget

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Get values of multiple fields in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required
keys list

List of field names.

required
*args str | bytes

Additional field names.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

List of field values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Get values of multiple fields in a hash.

    Args:
        name (str): The hash key name.
        keys (list): List of field names.
        *args (str | bytes): Additional field names.

    Returns:
        RedisListResponseType: List of field values.
    """
    # Convert keys list and args for type compatibility, combine into single list
    keys_list: list[str] = [str(k) for k in keys] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.read_only_client.hmget(name, keys_list)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.mocks.RedisMock.hvals

hvals(name: str) -> list[bytes | str]

Get all values in a hash.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
def hvals(self, name: str) -> list[bytes | str]:
    """Get all values in a hash.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of values.
    """
    result = self.read_only_client.hvals(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result) if result else []

archipy.adapters.redis.mocks.RedisMock.arset

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Set one or more contiguous values in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index to set values at.

required
*values bytes | str | float

Values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Set one or more contiguous values in an array.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index to set values at.
        *values (bytes | str | float): Values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.
    """
    result = self.client.arset(name, index, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.arget

arget(name: bytes | str, index: int) -> bytes | str | None

Get the value at an index in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Get the value at an index in an array.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset.
    """
    return self.read_only_client.arget(name, index)

archipy.adapters.redis.mocks.RedisMock.arlen

arlen(name: bytes | str) -> int

Get the number of populated elements in an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arlen(self, name: bytes | str) -> int:
    """Get the number of populated elements in an array.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.
    """
    result = self.read_only_client.arlen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.ardel

ardel(name: bytes | str, *indices: int) -> int

Delete one or more indices from an array.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

Indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def ardel(self, name: bytes | str, *indices: int) -> int:
    """Delete one or more indices from an array.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): Indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.
    """
    result = self.client.ardel(name, *indices)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.arring

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Insert values into an array as a fixed-size ring buffer.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

Values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Insert values into an array as a fixed-size ring buffer.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): Values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.
    """
    result = self.client.arring(name, size, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.zadd

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Add members to a sorted set with scores.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
mapping Mapping[bytes | str, bytes | str | float]

Member-score pairs.

required
nx bool

Only add new elements. Defaults to False.

False
xx bool

Only update existing elements. Defaults to False.

False
ch bool

Return number of changed elements. Defaults to False.

False
incr bool

Increment existing scores. Defaults to False.

False
gt bool

Only update if score is greater. Defaults to False.

False
lt bool

Only update if score is less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

Number of elements added or modified.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Add members to a sorted set with scores.

    Args:
        name (bytes | str): The sorted set key name.
        mapping (Mapping[bytes | str, bytes | str | float]): Member-score pairs.
        nx (bool): Only add new elements. Defaults to False.
        xx (bool): Only update existing elements. Defaults to False.
        ch (bool): Return number of changed elements. Defaults to False.
        incr (bool): Increment existing scores. Defaults to False.
        gt (bool): Only update if score is greater. Defaults to False.
        lt (bool): Only update if score is less. Defaults to False.

    Returns:
        RedisResponseType: Number of elements added or modified.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    str_name = str(name)
    return self.client.zadd(str_name, dict_mapping, nx, xx, ch, incr, gt, lt)

archipy.adapters.redis.mocks.RedisMock.zcard

zcard(name: bytes | str) -> int

Get the number of members in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required

Returns:

Name Type Description
RedisResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zcard(self, name: bytes | str) -> int:
    """Get the number of members in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.

    Returns:
        RedisResponseType: Number of members.
    """
    return self.client.zcard(name)

archipy.adapters.redis.mocks.RedisMock.zcount

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Count members in a sorted set with scores in range.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required

Returns:

Name Type Description
RedisResponseType int

Number of members in range.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Count members in a sorted set with scores in range.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.

    Returns:
        RedisResponseType: Number of members in range.
    """
    return self.client.zcount(name, min_, max_)

archipy.adapters.redis.mocks.RedisMock.zpopmax

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Remove and return members with highest scores from sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Remove and return members with highest scores from sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return self.client.zpopmax(name, count)

archipy.adapters.redis.mocks.RedisMock.zpopmin

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Remove and return members with lowest scores from sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Remove and return members with lowest scores from sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return self.client.zpopmin(name, count)

archipy.adapters.redis.mocks.RedisMock.zrange

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get a range of members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index or score.

required
end int

End index or score.

required
desc bool

Sort in descending order. Defaults to False.

False
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float
byscore bool

Range by score. Defaults to False.

False
bylex bool

Range by lexicographical order. Defaults to False.

False
offset int | None

Offset for byscore/bylex. Defaults to None.

None
num int | None

Count for byscore/bylex. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get a range of members from a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index or score.
        end (int): End index or score.
        desc (bool): Sort in descending order. Defaults to False.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.
        byscore (bool): Range by score. Defaults to False.
        bylex (bool): Range by lexicographical order. Defaults to False.
        offset (int | None): Offset for byscore/bylex. Defaults to None.
        num (int | None): Count for byscore/bylex. Defaults to None.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrange(
        name,
        start,
        end,
        desc,
        withscores,
        score_cast_func,
        byscore,
        bylex,
        offset,
        num,
    )

archipy.adapters.redis.mocks.RedisMock.zrevrange

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get a range of members from a sorted set in reverse order.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index.

required
end int

End index.

required
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get a range of members from a sorted set in reverse order.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index.
        end (int): End index.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrevrange(name, start, end, withscores, score_cast_func)

archipy.adapters.redis.mocks.RedisMock.zrangebyscore

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get members from a sorted set by score range.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required
start int | None

Offset. Defaults to None.

None
num int | None

Count. Defaults to None.

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get members from a sorted set by score range.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.
        start (int | None): Offset. Defaults to None.
        num (int | None): Count. Defaults to None.
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zrangebyscore(name, min_, max_, start, num, withscores, score_cast_func)

archipy.adapters.redis.mocks.RedisMock.zrank

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Get the rank of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to find rank for.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

Rank of the member or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Get the rank of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to find rank for.

    Returns:
        RedisResponseType: Rank of the member or None if not found.
    """
    return self.client.zrank(name, value)

archipy.adapters.redis.mocks.RedisMock.zrem

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Remove members from a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Remove members from a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: Number of members removed.
    """
    return self.client.zrem(name, *values)

archipy.adapters.redis.mocks.RedisMock.zscore

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Get the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to get score for.

required

Returns:

Name Type Description
RedisResponseType float | None

Score of the member or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Get the score of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to get score for.

    Returns:
        RedisResponseType: Score of the member or None if not found.
    """
    return self.client.zscore(name, value)

archipy.adapters.redis.mocks.RedisMock.zunion

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the union of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the union of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zunion(_normalize_zset_keys(keys), aggregate, withscores, score_cast_func)

archipy.adapters.redis.mocks.RedisMock.zinter

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the intersection of multiple sorted sets.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the intersection of multiple sorted sets.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return self.client.zinter(_normalize_zset_keys(keys), aggregate, withscores)

archipy.adapters.redis.mocks.RedisMock.zincrby

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increment the score of a member in a sorted set.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
amount float

Amount to increment by.

required
value bytes | str | float

Member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

New score of the member.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increment the score of a member in a sorted set.

    Args:
        name (bytes | str): The sorted set key name.
        amount (float): Amount to increment by.
        value (bytes | str | float): Member to increment.

    Returns:
        RedisResponseType: New score of the member.
    """
    return self.client.zincrby(name, amount, value)

archipy.adapters.redis.mocks.RedisMock.sscan

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Scan members of a set incrementally.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Scan members of a set incrementally.

    Args:
        name (bytes | str): The set key name.
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        RedisResponseType: Tuple of cursor and list of members.
    """
    return self.read_only_client.sscan(name, cursor, match, count)

archipy.adapters.redis.mocks.RedisMock.sscan_iter

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]

Iterate over members of a set.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
Iterator Iterator[bytes | str]

Iterator over set members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> Iterator[bytes | str]:
    """Iterate over members of a set.

    Args:
        name (bytes | str): The set key name.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        Iterator: Iterator over set members.
    """
    return self.read_only_client.sscan_iter(name, match, count)

archipy.adapters.redis.mocks.RedisMock.sadd

sadd(name: str, *values: bytes | str | float) -> int

Add members to a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements added.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Add members to a set.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: Number of elements added.
    """
    result = self.client.sadd(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.scard

scard(name: str) -> int

Get the number of members in a set.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def scard(self, name: str) -> int:
    """Get the number of members in a set.

    Args:
        name (str): The set key name.

    Returns:
        RedisIntegerResponseType: Number of members.
    """
    result = self.client.scard(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.sismember

sismember(name: str, value: str) -> bool

Check if a value is a member of a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
value str

Value to check.

required

Returns:

Name Type Description
bool bool

True if value is a member, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sismember(self, name: str, value: str) -> bool:
    """Check if a value is a member of a set.

    Args:
        name (str): The set key name.
        value (str): Value to check.

    Returns:
        bool: True if value is a member, False otherwise.
    """
    result = self.read_only_client.sismember(name, value)
    return bool(result)

archipy.adapters.redis.mocks.RedisMock.smembers

smembers(name: str) -> _set[bytes | str]

Get all members of a set.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set of all members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def smembers(self, name: str) -> _set[bytes | str]:
    """Get all members of a set.

    Args:
        name (str): The set key name.

    Returns:
        RedisSetResponseType: Set of all members.
    """
    result = self.read_only_client.smembers(name)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return set(result) if result else set()

archipy.adapters.redis.mocks.RedisMock.spop

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Remove and return random members from a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: Popped member(s) or None.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Remove and return random members from a set.

    Args:
        name (str): The set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        bytes | float | int | str | list | None: Popped member(s) or None.
    """
    result = self.client.spop(name, count)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    if isinstance(result, set):
        return list(result)
    return result

archipy.adapters.redis.mocks.RedisMock.srem

srem(name: str, *values: bytes | str | float) -> int

Remove members from a set.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def srem(self, name: str, *values: bytes | str | float) -> int:
    """Remove members from a set.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: Number of members removed.
    """
    result = self.client.srem(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.sunion

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Get the union of multiple sets.

Parameters:

Name Type Description Default
keys bytes | str

First set key.

required
*args bytes | str

Additional set keys.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set containing union of all sets.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Get the union of multiple sets.

    Args:
        keys (bytes | str): First set key.
        *args (bytes | str): Additional set keys.

    Returns:
        RedisSetResponseType: Set containing union of all sets.
    """
    # Redis sunion expects a list of keys as first argument
    keys_list: list[str | bytes] = [keys, *list(args)]
    result = self.client.sunion(keys_list)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return set(result) if result else set()

archipy.adapters.redis.mocks.RedisMock.llen

llen(name: str) -> int

Get the length of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def llen(self, name: str) -> int:
    """Get the length of a list.

    Args:
        name (str): The key name of the list.

    Returns:
        RedisIntegerResponseType: Length of the list.
    """
    result = self.read_only_client.llen(name)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.lpop

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from the left of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from the left of a list.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    return self.client.lpop(name, count)

archipy.adapters.redis.mocks.RedisMock.lpush

lpush(name: str, *values: bytes | str | float) -> int

Push elements to the left of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to the left of a list.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.lpush(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.lrange

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Get a range of elements from a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
start int

Start index.

required
end int

End index.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of elements in the specified range.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Get a range of elements from a list.

    Args:
        name (str): The key name of the list.
        start (int): Start index.
        end (int): End index.

    Returns:
        RedisListResponseType: List of elements in the specified range.
    """
    result = self.read_only_client.lrange(name, start, end)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return list(result)

archipy.adapters.redis.mocks.RedisMock.lrem

lrem(name: str, count: int, value: str) -> int

Remove elements from a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int

Number of occurrences to remove.

required
value str

Value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements removed.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lrem(self, name: str, count: int, value: str) -> int:
    """Remove elements from a list.

    Args:
        name (str): The key name of the list.
        count (int): Number of occurrences to remove.
        value (str): Value to remove.

    Returns:
        RedisIntegerResponseType: Number of elements removed.
    """
    result = self.client.lrem(name, count, value)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.lset

lset(name: str, index: int, value: str) -> bool

Set the value of an element in a list by its index.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
index int

Index of the element.

required
value str

New value.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def lset(self, name: str, index: int, value: str) -> bool:
    """Set the value of an element in a list by its index.

    Args:
        name (str): The key name of the list.
        index (int): Index of the element.
        value (str): New value.

    Returns:
        bool: True if successful.
    """
    return bool(self.client.lset(name, index, value))

archipy.adapters.redis.mocks.RedisMock.rpop

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from the right of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from the right of a list.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    return self.client.rpop(name, count)

archipy.adapters.redis.mocks.RedisMock.rpush

rpush(name: str, *values: bytes | str | float) -> int

Push elements to the right of a list.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to the right of a list.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.rpush(name, *values)
    return self._ensure_sync_int(result)

archipy.adapters.redis.mocks.RedisMock.pttl

pttl(name: bytes | str) -> int

Get the time to live in milliseconds for a key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in milliseconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def pttl(self, name: bytes | str) -> int:
    """Get the time to live in milliseconds for a key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in milliseconds.
    """
    return self.read_only_client.pttl(name)

archipy.adapters.redis.mocks.RedisMock.incrby

incrby(name: bytes | str, amount: int = 1) -> int

Increment the integer value of a key by the given amount.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
amount int

Amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after increment.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increment the integer value of a key by the given amount.

    Args:
        name (bytes | str): The key name.
        amount (int): Amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after increment.
    """
    return self.client.incrby(name, amount)

archipy.adapters.redis.mocks.RedisMock.increx

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increment a windowed counter with bounds and expiration control.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
byfloat float

Increment amount as a float.

None
byint int

Increment amount as an int.

None
lbound float | int

Lower bound for the resulting value.

None
ubound float | int

Upper bound for the resulting value.

None
saturate bool

Clamp out-of-bounds results instead of rejecting. Defaults to False.

False
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None
persist bool

Remove any existing expiration. Defaults to False.

False
enx bool

Set expiration only if none already exists. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increment a windowed counter with bounds and expiration control.

    Args:
        name (bytes | str): The key to increment.
        byfloat (float, optional): Increment amount as a float.
        byint (int, optional): Increment amount as an int.
        lbound (float | int, optional): Lower bound for the resulting value.
        ubound (float | int, optional): Upper bound for the resulting value.
        saturate (bool): Clamp out-of-bounds results instead of rejecting. Defaults to False.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.
        persist (bool): Remove any existing expiration. Defaults to False.
        enx (bool): Set expiration only if none already exists. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of [new_value, actual_increment_applied].
    """
    return list(
        self.client.increx(
            name,
            byfloat=byfloat,
            byint=byint,
            lbound=lbound,
            ubound=ubound,
            saturate=saturate,
            ex=ex,
            px=px,
            exat=exat,
            pxat=pxat,
            persist=persist,
            enx=enx,
        ),
    )

archipy.adapters.redis.mocks.RedisMock.set

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Set the value of a key with optional expiration and conditions.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
value int | bytes | str | float

The value to set.

required
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
nx bool

Only set if key doesn't exist.

False
xx bool

Only set if key exists.

False
keepttl bool

Retain the TTL from the previous value.

False
get bool

Return the old value.

False
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

Result of the operation.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Set the value of a key with optional expiration and conditions.

    Args:
        name (bytes | str): The key name.
        value (int | bytes | str | float): The value to set.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        nx (bool): Only set if key doesn't exist.
        xx (bool): Only set if key exists.
        keepttl (bool): Retain the TTL from the previous value.
        get (bool): Return the old value.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.

    Returns:
        RedisResponseType: Result of the operation.
    """
    return self.client.set(name, value, ex, px, nx, xx, keepttl, get, exat, pxat)

archipy.adapters.redis.mocks.RedisMock.get

get(key: str) -> bytes | str | None

Get the value of a key.

Parameters:

Name Type Description Default
key str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None if not exists.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def get(self, key: str) -> bytes | str | None:
    """Get the value of a key.

    Args:
        key (str): The key name.

    Returns:
        RedisResponseType: The value of the key or None if not exists.
    """
    return self.read_only_client.get(key)

archipy.adapters.redis.mocks.RedisMock.mget

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Get the values of multiple keys.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

Single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Get the values of multiple keys.

    Args:
        keys (bytes | str | Iterable[bytes | str]): Single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: List of values.
    """
    return self.read_only_client.mget(keys, *args)

archipy.adapters.redis.mocks.RedisMock.mset

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Set multiple keys to their respective values.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

Dictionary of key-value pairs.

required

Returns:

Name Type Description
RedisResponseType bool

Always returns 'OK'.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Set multiple keys to their respective values.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): Dictionary of key-value pairs.

    Returns:
        RedisResponseType: Always returns 'OK'.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    return self.client.mset(dict_mapping)

archipy.adapters.redis.mocks.RedisMock.keys

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Find all keys matching the given pattern.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Find all keys matching the given pattern.

    Args:
        pattern (bytes | str): Pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of matching keys.
    """
    return self.read_only_client.keys(pattern, **kwargs)

archipy.adapters.redis.mocks.RedisMock.getset

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Set the value of a key and return its old value.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The new value.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The previous value or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Set the value of a key and return its old value.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The new value.

    Returns:
        RedisResponseType: The previous value or None.
    """
    return self.client.getset(key, value)

archipy.adapters.redis.mocks.RedisMock.getdel

getdel(key: bytes | str) -> bytes | str | None

Get the value of a key and delete it.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def getdel(self, key: bytes | str) -> bytes | str | None:
    """Get the value of a key and delete it.

    Args:
        key (bytes | str): The key name.

    Returns:
        RedisResponseType: The value of the key or None.
    """
    return self.client.getdel(key)

archipy.adapters.redis.mocks.RedisMock.exists

exists(*names: bytes | str) -> int

Check if one or more keys exist.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys that exist.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def exists(self, *names: bytes | str) -> int:
    """Check if one or more keys exist.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys that exist.
    """
    return self.read_only_client.exists(*names)

archipy.adapters.redis.mocks.RedisMock.delete

delete(*names: bytes | str) -> int

Delete one or more keys.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys deleted.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def delete(self, *names: bytes | str) -> int:
    """Delete one or more keys.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys deleted.
    """
    return self.client.delete(*names)

archipy.adapters.redis.mocks.RedisMock.append

append(key: bytes | str, value: bytes | str | float) -> int

Append a value to a key.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

Length of the string after append.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Append a value to a key.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: Length of the string after append.
    """
    return self.client.append(key, value)

archipy.adapters.redis.mocks.RedisMock.ttl

ttl(name: bytes | str) -> int

Get the time to live in seconds for a key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in seconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def ttl(self, name: bytes | str) -> int:
    """Get the time to live in seconds for a key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in seconds.
    """
    return self.read_only_client.ttl(name)

archipy.adapters.redis.mocks.RedisMock.type

type(name: bytes | str) -> bytes | str

Determine the type stored at key.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str

Type of the key's value.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def type(self, name: bytes | str) -> bytes | str:
    """Determine the type stored at key.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Type of the key's value.
    """
    return self.read_only_client.type(name)

archipy.adapters.redis.mocks.RedisMock.scan

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Scan keys in the database incrementally.

Parameters:

Name Type Description Default
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys to return. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Scan keys in the database incrementally.

    Args:
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys to return. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Tuple of cursor and list of keys.
    """
    return self.read_only_client.scan(cursor, match, count, _type, **kwargs)

archipy.adapters.redis.mocks.RedisMock.scan_iter

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]

Iterate over keys in the database.

Parameters:

Name Type Description Default
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys to return. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
Iterator Iterator[bytes | str]

Iterator over matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> Iterator[bytes | str]:
    """Iterate over keys in the database.

    Args:
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys to return. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        Iterator: Iterator over matching keys.
    """
    return self.read_only_client.scan_iter(match, count, _type, **kwargs)

archipy.adapters.redis.mocks.RedisMock.cluster_info

cluster_info() -> dict[str, str] | None

Get cluster information.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_info()
    return None

archipy.adapters.redis.mocks.RedisMock.cluster_nodes

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_nodes()
    return None

archipy.adapters.redis.mocks.RedisMock.cluster_slots

cluster_slots() -> list[Any] | None

Get cluster slots mapping.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_slots()
    return None

archipy.adapters.redis.mocks.RedisMock.cluster_key_slot

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_keyslot(key)
    return None

archipy.adapters.redis.mocks.RedisMock.cluster_count_keys_in_slot

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_countkeysinslot(slot)
    return None

archipy.adapters.redis.mocks.RedisMock.cluster_get_keys_in_slot

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot."""
    if isinstance(self.client, RedisCluster):
        return self.client.cluster_get_keys_in_slot(slot, count)
    return None

archipy.adapters.redis.mocks.RedisMock.ping

ping() -> bool

Ping the Redis server.

Returns:

Name Type Description
RedisResponseType bool

'PONG' if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def ping(self) -> bool:
    """Ping the Redis server.

    Returns:
        RedisResponseType: 'PONG' if successful.
    """
    return self.client.ping()

archipy.adapters.redis.mocks.RedisMock.flushdb

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.
    """
    return self.client.flushdb(asynchronous=asynchronous)

archipy.adapters.redis.mocks.RedisMock.get_pipeline

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> Pipeline

Get a pipeline object for executing multiple commands.

Parameters:

Name Type Description Default
transaction Any

Whether to use transactions. Defaults to True.

True
shard_hint Any

Hint for sharding. Defaults to None.

None

Returns:

Name Type Description
Pipeline Pipeline

Pipeline object.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def get_pipeline(self, transaction: Any = True, shard_hint: Any = None) -> Pipeline:
    """Get a pipeline object for executing multiple commands.

    Args:
        transaction (Any): Whether to use transactions. Defaults to True.
        shard_hint (Any): Hint for sharding. Defaults to None.

    Returns:
        Pipeline: Pipeline object.
    """
    return self.client.pipeline(transaction, shard_hint)

archipy.adapters.redis.mocks.RedisMock.config_set

config_set(name: str, value: str) -> bool

Set a Redis server configuration parameter.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def config_set(self, name: str, value: str) -> bool:
    """Set a Redis server configuration parameter.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.
    """
    return bool(self.client.config_set(name, value))

archipy.adapters.redis.mocks.RedisMock.config_get

config_get(pattern: str = '*') -> dict[str, str]

Get Redis server configuration parameters matching a pattern.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

Dictionary of configuration parameter names to values.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Get Redis server configuration parameters matching a pattern.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: Dictionary of configuration parameter names to values.
    """
    result = self.read_only_client.config_get(pattern)
    if isinstance(result, Awaitable):
        raise InternalError(error_code="SYNC_REDIS_AWAITABLE")
    return {str(k): str(v) for k, v in result.items()} if result else {}

archipy.adapters.redis.mocks.RedisMock.search_index

search_index(name: str) -> RedisSearchHandlePort

Return an index-bound RediSearch handle.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def search_index(self, name: str) -> RedisSearchHandlePort:
    """Return an index-bound RediSearch handle."""
    return RedisSearchHandle(self._get_search_client(), name)

archipy.adapters.redis.mocks.RedisMock.list_search_indexes

list_search_indexes() -> list[str]

List RediSearch indexes available on the server.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def list_search_indexes(self) -> list[str]:
    """List RediSearch indexes available on the server."""
    return list_redis_search_indexes(self._get_search_client())

archipy.adapters.redis.mocks.AsyncRedisMock

Bases: AsyncRedisAdapter

An async Redis adapter implementation using FakeAsyncRedis for testing.

Source code in archipy/adapters/redis/mocks.py
class AsyncRedisMock(AsyncRedisAdapter):
    """An async Redis adapter implementation using FakeAsyncRedis for testing."""

    def __init__(self, redis_config: RedisConfig | None = None) -> None:
        """Initialize AsyncRedisMock."""
        # Skip the parent's __init__ which would create real Redis connections
        self.config = redis_config or BaseConfig.global_config().REDIS
        self._configs = self.config
        self._server = FakeServer()
        self._search_client: AsyncRedis | AsyncRedisCluster | None = None

        # Create fake async redis clients based on mode
        self._setup_async_fake_clients()

    def _setup_async_fake_clients(self) -> None:
        """Setup fake async Redis clients that simulate different modes."""
        decode_responses = self.config.DECODE_RESPONSES
        if self.config.MODE == RedisMode.CLUSTER:
            fake_client: AsyncRedis = FakeAsyncRedisClusterWrapper(
                decode_responses=decode_responses,
                server=self._server,
            )
        else:
            fake_client = FakeAsyncRedis(
                decode_responses=decode_responses,
                server=self._server,
            )

        self.client = fake_client
        self.read_only_client = fake_client

    def _set_clients(self, configs: RedisConfig) -> None:
        # Override to prevent actual connection setup
        pass

    def _get_client(self, host: str, configs: RedisConfig, *, decode_responses: bool | None = None) -> AsyncRedis:
        return FakeAsyncRedis(
            decode_responses=configs.DECODE_RESPONSES if decode_responses is None else decode_responses,
            server=self._server,
        )

    def _get_search_client(self) -> AsyncRedis | AsyncRedisCluster:
        if self._search_client is None:
            self._search_client = FakeAsyncRedis(
                decode_responses=False,
                server=self._server,
            )
        return self._search_client

archipy.adapters.redis.mocks.AsyncRedisMock.config instance-attribute

config = redis_config or BaseConfig.global_config().REDIS

archipy.adapters.redis.mocks.AsyncRedisMock.client instance-attribute

client: Redis | RedisCluster

archipy.adapters.redis.mocks.AsyncRedisMock.read_only_client instance-attribute

read_only_client: Redis | RedisCluster

archipy.adapters.redis.mocks.AsyncRedisMock.publish async

publish(
    channel: bytes | str,
    message: bytes | str,
    **kwargs: Any,
) -> int

Publish message to channel asynchronously.

Parameters:

Name Type Description Default
channel bytes | str

Channel name.

required
message bytes | str

Message to publish.

required
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType int

Number of subscribers received message.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> int:
    """Publish message to channel asynchronously.

    Args:
        channel (bytes | str): Channel name.
        message (bytes | str): Message to publish.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Number of subscribers received message.
    """
    return await self.client.publish(channel, message, **kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.pubsub_channels async

pubsub_channels(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

List active channels matching pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of channel names.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """List active channels matching pattern asynchronously.

    Args:
        pattern (bytes | str): Pattern to match. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of channel names.
    """
    return await self.client.pubsub_channels(pattern, **kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.pubsub async

pubsub(**kwargs: Any) -> AsyncPubSub

Get PubSub object for channel subscription asynchronously.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
AsyncPubSub PubSub

PubSub object.

Source code in archipy/adapters/redis/adapter_mixins/pubsub.py
async def pubsub(self, **kwargs: Any) -> AsyncPubSub:
    """Get PubSub object for channel subscription asynchronously.

    Args:
        **kwargs (Any): Additional arguments.

    Returns:
        AsyncPubSub: PubSub object.
    """
    return self.client.pubsub(**kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.hdel async

hdel(name: str, *keys: str | bytes) -> int

Delete fields from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
*keys str | bytes

Fields to delete.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields deleted.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hdel(self, name: str, *keys: str | bytes) -> int:
    """Delete fields from hash asynchronously.

    Args:
        name (str): The hash key name.
        *keys (str | bytes): Fields to delete.

    Returns:
        RedisIntegerResponseType: Number of fields deleted.
    """
    # Convert keys to str for type compatibility
    str_keys: tuple[str, ...] = tuple(str(k) if isinstance(k, bytes) else k for k in keys)
    result = self.client.hdel(name, *str_keys)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hexists async

hexists(name: str, key: str) -> bool

Check if field exists in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to check.

required

Returns:

Name Type Description
bool bool

True if exists, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hexists(self, name: str, key: str) -> bool:
    """Check if field exists in hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str): Field to check.

    Returns:
        bool: True if exists, False otherwise.
    """
    result = self.read_only_client.hexists(name, key)
    return await self._ensure_async_bool(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hget async

hget(name: str, key: str) -> bytes | str | None

Get field value from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str

Field to get.

required

Returns:

Type Description
bytes | str | None

str | None: Value or None.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hget(self, name: str, key: str) -> bytes | str | None:
    """Get field value from hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str): Field to get.

    Returns:
        str | None: Value or None.
    """
    result = self.read_only_client.hget(name, key)
    resolved = await self._ensure_async_str(result)
    return str(resolved) if resolved is not None else None

archipy.adapters.redis.mocks.AsyncRedisMock.hgetall async

hgetall(name: str) -> dict[bytes | str, bytes | str]

Get all fields and values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Type Description
dict[bytes | str, bytes | str]

dict[str, Any]: Dictionary of field-value pairs.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hgetall(self, name: str) -> dict[bytes | str, bytes | str]:
    """Get all fields and values from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        dict[str, Any]: Dictionary of field-value pairs.
    """
    result = self.read_only_client.hgetall(name)
    if isinstance(result, Awaitable):
        awaited_result = await result
        if awaited_result is None:
            return {}
        if isinstance(awaited_result, dict):
            return {str(k): v for k, v in awaited_result.items()}
        if isinstance(awaited_result, Mapping):
            return {str(k): v for k, v in awaited_result.items()}
        return {}
    if result is None:
        return {}
    if isinstance(result, dict):
        return {str(k): v for k, v in result.items()}
    if isinstance(result, Mapping):
        return {str(k): v for k, v in result.items()}
    return {}

archipy.adapters.redis.mocks.AsyncRedisMock.hkeys async

hkeys(name: str) -> list[bytes | str]

Get all fields from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of field names.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hkeys(self, name: str) -> list[bytes | str]:
    """Get all fields from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of field names.
    """
    result = self.read_only_client.hkeys(name)
    return await self._ensure_async_list(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hlen async

hlen(name: str) -> int

Get number of fields in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hlen(self, name: str) -> int:
    """Get number of fields in hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisIntegerResponseType: Number of fields.
    """
    result = self.read_only_client.hlen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hset async

hset(
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int

Set fields in hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
key str | bytes | None

Single field name. Defaults to None.

None
value str | bytes | None

Single field value. Defaults to None.

None
mapping dict | None

Field-value pairs dict. Defaults to None.

None
items list | None

Field-value pairs list. Defaults to None.

None

Returns:

Name Type Description
RedisIntegerResponseType int

Number of fields set.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hset(
    self,
    name: str,
    key: str | bytes | None = None,
    value: str | bytes | None = None,
    mapping: dict | None = None,
    items: list | None = None,
) -> int:
    """Set fields in hash asynchronously.

    Args:
        name (str): The hash key name.
        key (str | bytes | None): Single field name. Defaults to None.
        value (str | bytes | None): Single field value. Defaults to None.
        mapping (dict | None): Field-value pairs dict. Defaults to None.
        items (list | None): Field-value pairs list. Defaults to None.

    Returns:
        RedisIntegerResponseType: Number of fields set.
    """
    # Convert bytes to str for type compatibility with Redis client
    str_key: str | None = str(key) if key is not None and isinstance(key, bytes) else key
    str_value: str | None = str(value) if value is not None and isinstance(value, bytes) else value
    result = self.client.hset(name, str_key, str_value, mapping, items)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hmget async

hmget(
    name: str, keys: list, *args: str | bytes
) -> list[bytes | str | None]

Get multiple field values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required
keys list

List of field names.

required
*args str | bytes

Additional field names.

()

Returns:

Name Type Description
RedisListResponseType list[bytes | str | None]

List of field values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hmget(self, name: str, keys: list, *args: str | bytes) -> list[bytes | str | None]:
    """Get multiple field values from hash asynchronously.

    Args:
        name (str): The hash key name.
        keys (list): List of field names.
        *args (str | bytes): Additional field names.

    Returns:
        RedisListResponseType: List of field values.
    """
    # Convert keys list and args for type compatibility, combine into single list
    keys_list: list[str] = [str(k) for k in keys] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.read_only_client.hmget(name, keys_list)
    return await self._ensure_async_list(result)

archipy.adapters.redis.mocks.AsyncRedisMock.hvals async

hvals(name: str) -> list[bytes | str]

Get all values from hash asynchronously.

Parameters:

Name Type Description Default
name str

The hash key name.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/hashes.py
async def hvals(self, name: str) -> list[bytes | str]:
    """Get all values from hash asynchronously.

    Args:
        name (str): The hash key name.

    Returns:
        RedisListResponseType: List of values.
    """
    result = self.read_only_client.hvals(name)
    return await self._ensure_async_list(result)

archipy.adapters.redis.mocks.AsyncRedisMock.arset async

arset(
    name: bytes | str,
    index: int,
    *values: bytes | str | float,
) -> int

Set one or more contiguous values in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The starting index to set values at.

required
*values bytes | str | float

Values to store at consecutive indices.

()

Returns:

Name Type Description
RedisResponseType int

The number of previously empty slots that were set.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arset(self, name: bytes | str, index: int, *values: bytes | str | float) -> int:
    """Set one or more contiguous values in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        index (int): The starting index to set values at.
        *values (bytes | str | float): Values to store at consecutive indices.

    Returns:
        RedisResponseType: The number of previously empty slots that were set.
    """
    result = self.client.arset(name, index, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.arget async

arget(name: bytes | str, index: int) -> bytes | str | None

Get the value at an index in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
index int

The index to read.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value at the index, or None if unset.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arget(self, name: bytes | str, index: int) -> bytes | str | None:
    """Get the value at an index in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        index (int): The index to read.

    Returns:
        RedisResponseType: The value at the index, or None if unset.
    """
    result = self.read_only_client.arget(name, index)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.arlen async

arlen(name: bytes | str) -> int

Get the number of populated elements in an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required

Returns:

Name Type Description
RedisResponseType int

The number of populated elements.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arlen(self, name: bytes | str) -> int:
    """Get the number of populated elements in an array asynchronously.

    Args:
        name (bytes | str): The key of the array.

    Returns:
        RedisResponseType: The number of populated elements.
    """
    result = self.read_only_client.arlen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.ardel async

ardel(name: bytes | str, *indices: int) -> int

Delete one or more indices from an array asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
*indices int

Indices to delete.

()

Returns:

Name Type Description
RedisResponseType int

The number of elements deleted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def ardel(self, name: bytes | str, *indices: int) -> int:
    """Delete one or more indices from an array asynchronously.

    Args:
        name (bytes | str): The key of the array.
        *indices (int): Indices to delete.

    Returns:
        RedisResponseType: The number of elements deleted.
    """
    result = self.client.ardel(name, *indices)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.arring async

arring(
    name: bytes | str,
    size: int,
    *values: bytes | str | float,
) -> int

Insert values into an array as a fixed-size ring buffer asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key of the array.

required
size int

The fixed size of the ring buffer.

required
*values bytes | str | float

Values to insert.

()

Returns:

Name Type Description
RedisResponseType int

The last index where a value was inserted.

Source code in archipy/adapters/redis/adapter_mixins/arrays.py
async def arring(self, name: bytes | str, size: int, *values: bytes | str | float) -> int:
    """Insert values into an array as a fixed-size ring buffer asynchronously.

    Args:
        name (bytes | str): The key of the array.
        size (int): The fixed size of the ring buffer.
        *values (bytes | str | float): Values to insert.

    Returns:
        RedisResponseType: The last index where a value was inserted.
    """
    result = self.client.arring(name, size, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.zadd async

zadd(
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None

Add members to sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
mapping Mapping[bytes | str, bytes | str | float]

Member-score pairs.

required
nx bool

Only add new elements. Defaults to False.

False
xx bool

Only update existing. Defaults to False.

False
ch bool

Return changed count. Defaults to False.

False
incr bool

Increment scores. Defaults to False.

False
gt bool

Only if greater. Defaults to False.

False
lt bool

Only if less. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType int | float | None

Number of elements added or modified.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zadd(
    self,
    name: bytes | str,
    mapping: Mapping[bytes | str, bytes | str | float],
    nx: bool = False,
    xx: bool = False,
    ch: bool = False,
    incr: bool = False,
    gt: bool = False,
    lt: bool = False,
) -> int | float | None:
    """Add members to sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        mapping (Mapping[bytes | str, bytes | str | float]): Member-score pairs.
        nx (bool): Only add new elements. Defaults to False.
        xx (bool): Only update existing. Defaults to False.
        ch (bool): Return changed count. Defaults to False.
        incr (bool): Increment scores. Defaults to False.
        gt (bool): Only if greater. Defaults to False.
        lt (bool): Only if less. Defaults to False.

    Returns:
        RedisResponseType: Number of elements added or modified.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    if isinstance(mapping, dict):
        dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    else:
        dict_mapping = {str(k): v for k, v in mapping.items()}
    str_name = str(name)
    result = self.client.zadd(str_name, dict_mapping, nx, xx, ch, incr, gt, lt)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.zcard async

zcard(name: bytes | str) -> int

Get number of members in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required

Returns:

Name Type Description
RedisResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zcard(self, name: bytes | str) -> int:
    """Get number of members in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.

    Returns:
        RedisResponseType: Number of members.
    """
    return await self.client.zcard(name)

archipy.adapters.redis.mocks.AsyncRedisMock.zcount async

zcount(
    name: bytes | str, min_: float | str, max_: float | str
) -> int

Count members in score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required

Returns:

Name Type Description
RedisResponseType int

Number of members in range.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zcount(self, name: bytes | str, min_: float | str, max_: float | str) -> int:
    """Count members in score range asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.

    Returns:
        RedisResponseType: Number of members in range.
    """
    return await self.client.zcount(name, min_, max_)

archipy.adapters.redis.mocks.AsyncRedisMock.zpopmax async

zpopmax(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Pop highest scored members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zpopmax(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Pop highest scored members asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return await self.client.zpopmax(name, count)

archipy.adapters.redis.mocks.AsyncRedisMock.zpopmin async

zpopmin(
    name: bytes | str, count: int | None = None
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Pop lowest scored members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
count int | None

Number to pop. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of popped member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zpopmin(
    self,
    name: bytes | str,
    count: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Pop lowest scored members asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        count (int | None): Number to pop. Defaults to None.

    Returns:
        RedisResponseType: List of popped member-score pairs.
    """
    return await self.client.zpopmin(name, count)

archipy.adapters.redis.mocks.AsyncRedisMock.zrange async

zrange(
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get range from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index or score.

required
end int

End index or score.

required
desc bool

Descending order. Defaults to False.

False
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float
byscore bool

Range by score. Defaults to False.

False
bylex bool

Range by lex. Defaults to False.

False
offset int | None

Offset for byscore/bylex. Defaults to None.

None
num int | None

Count for byscore/bylex. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    desc: bool = False,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
    byscore: bool = False,
    bylex: bool = False,
    offset: int | None = None,
    num: int | None = None,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get range from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index or score.
        end (int): End index or score.
        desc (bool): Descending order. Defaults to False.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.
        byscore (bool): Range by score. Defaults to False.
        bylex (bool): Range by lex. Defaults to False.
        offset (int | None): Offset for byscore/bylex. Defaults to None.
        num (int | None): Count for byscore/bylex. Defaults to None.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrange(
        name,
        start,
        end,
        desc,
        withscores,
        score_cast_func,
        byscore,
        bylex,
        offset,
        num,
    )

archipy.adapters.redis.mocks.AsyncRedisMock.zrevrange async

zrevrange(
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get reverse range from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
start int

Start index.

required
end int

End index.

required
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrevrange(
    self,
    name: bytes | str,
    start: int,
    end: int,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get reverse range from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        start (int): Start index.
        end (int): End index.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrevrange(name, start, end, withscores, score_cast_func)

archipy.adapters.redis.mocks.AsyncRedisMock.zrangebyscore async

zrangebyscore(
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Get members by score range asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
min_ float | str

Minimum score.

required
max_ float | str

Maximum score.

required
start int | None

Offset. Defaults to None.

None
num int | None

Count. Defaults to None.

None
withscores bool

Include scores. Defaults to False.

False
score_cast_func RedisScoreCastType

Score cast function. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrangebyscore(
    self,
    name: bytes | str,
    min_: float | str,
    max_: float | str,
    start: int | None = None,
    num: int | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Get members by score range asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        min_ (float | str): Minimum score.
        max_ (float | str): Maximum score.
        start (int | None): Offset. Defaults to None.
        num (int | None): Count. Defaults to None.
        withscores (bool): Include scores. Defaults to False.
        score_cast_func (RedisScoreCastType): Score cast function. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zrangebyscore(name, min_, max_, start, num, withscores, score_cast_func)

archipy.adapters.redis.mocks.AsyncRedisMock.zrank async

zrank(
    name: bytes | str, value: bytes | str | float
) -> int | list[Any] | None

Get rank of member in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to find rank for.

required

Returns:

Name Type Description
RedisResponseType int | list[Any] | None

Rank or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrank(self, name: bytes | str, value: bytes | str | float) -> int | list[Any] | None:
    """Get rank of member in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to find rank for.

    Returns:
        RedisResponseType: Rank or None if not found.
    """
    return await self.client.zrank(name, value)

archipy.adapters.redis.mocks.AsyncRedisMock.zrem async

zrem(
    name: bytes | str, *values: bytes | str | float
) -> int

Remove members from sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zrem(self, name: bytes | str, *values: bytes | str | float) -> int:
    """Remove members from sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisResponseType: Number of members removed.
    """
    return await self.client.zrem(name, *values)

archipy.adapters.redis.mocks.AsyncRedisMock.zscore async

zscore(
    name: bytes | str, value: bytes | str | float
) -> float | None

Get score of member in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
value bytes | str | float

Member to get score for.

required

Returns:

Name Type Description
RedisResponseType float | None

Score or None if not found.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zscore(self, name: bytes | str, value: bytes | str | float) -> float | None:
    """Get score of member in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        value (bytes | str | float): Member to get score for.

    Returns:
        RedisResponseType: Score or None if not found.
    """
    return await self.client.zscore(name, value)

archipy.adapters.redis.mocks.AsyncRedisMock.zunion async

zunion(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the union of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False
score_cast_func RedisScoreCastType

Function to cast scores. Defaults to float.

float

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zunion(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
    score_cast_func: RedisScoreCastType = float,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the union of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.
        score_cast_func (RedisScoreCastType): Function to cast scores. Defaults to float.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zunion(_normalize_zset_keys(keys), aggregate, withscores, score_cast_func)

archipy.adapters.redis.mocks.AsyncRedisMock.zinter async

zinter(
    keys: Mapping[bytes | str, float]
    | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> (
    list[bytes | str]
    | list[tuple[bytes | str, Any]]
    | list[list[Any]]
)

Compute the intersection of multiple sorted sets asynchronously.

Parameters:

Name Type Description Default
keys Mapping[bytes | str, float] | Iterable[bytes | str]

Sorted set keys, optionally mapped to per-set weights.

required
aggregate str | None

"SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".

None
withscores bool

Include scores in result. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]

List of members or member-score pairs.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zinter(
    self,
    keys: Mapping[bytes | str, float] | Iterable[bytes | str],
    aggregate: str | None = None,
    withscores: bool = False,
) -> list[bytes | str] | list[tuple[bytes | str, Any]] | list[list[Any]]:
    """Compute the intersection of multiple sorted sets asynchronously.

    Args:
        keys (Mapping[bytes | str, float] | Iterable[bytes | str]): Sorted set keys, optionally
            mapped to per-set weights.
        aggregate (str | None): "SUM", "MIN", "MAX", or "COUNT". Defaults to "SUM".
        withscores (bool): Include scores in result. Defaults to False.

    Returns:
        RedisResponseType: List of members or member-score pairs.
    """
    return await self.client.zinter(_normalize_zset_keys(keys), aggregate, withscores)

archipy.adapters.redis.mocks.AsyncRedisMock.zincrby async

zincrby(
    name: bytes | str,
    amount: float,
    value: bytes | str | float,
) -> float | None

Increment member score in sorted set asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The sorted set key name.

required
amount float

Amount to increment by.

required
value bytes | str | float

Member to increment.

required

Returns:

Name Type Description
RedisResponseType float | None

New score of the member.

Source code in archipy/adapters/redis/adapter_mixins/sorted_sets.py
async def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) -> float | None:
    """Increment member score in sorted set asynchronously.

    Args:
        name (bytes | str): The sorted set key name.
        amount (float): Amount to increment by.
        value (bytes | str | float): Member to increment.

    Returns:
        RedisResponseType: New score of the member.
    """
    return await self.client.zincrby(name, amount, value)

archipy.adapters.redis.mocks.AsyncRedisMock.sscan async

sscan(
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]

Scan set members incrementally asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sscan(
    self,
    name: bytes | str,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
) -> tuple[int, list[bytes | str]]:
    """Scan set members incrementally asynchronously.

    Args:
        name (bytes | str): The set key name.
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        RedisResponseType: Tuple of cursor and list of members.
    """
    result = self.read_only_client.sscan(name, cursor, match, count)
    if isinstance(result, Awaitable):
        awaited_result: tuple[int, list[bytes | str]] = await result
        return awaited_result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.sscan_iter async

sscan_iter(
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]

Iterate over set members asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The set key name.

required
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of elements. Defaults to None.

None

Returns:

Type Description
AsyncIterator[bytes | str]

Iterator[Any]: Iterator over set members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sscan_iter(
    self,
    name: bytes | str,
    match: bytes | str | None = None,
    count: int | None = None,
) -> AsyncIterator[bytes | str]:
    """Iterate over set members asynchronously.

    Args:
        name (bytes | str): The set key name.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of elements. Defaults to None.

    Returns:
        Iterator[Any]: Iterator over set members.
    """
    return self.read_only_client.sscan_iter(name, match, count)

archipy.adapters.redis.mocks.AsyncRedisMock.sadd async

sadd(name: str, *values: bytes | str | float) -> int

Add members to a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to add.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements added.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sadd(self, name: str, *values: bytes | str | float) -> int:
    """Add members to a set asynchronously.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to add.

    Returns:
        RedisIntegerResponseType: Number of elements added.
    """
    result = self.client.sadd(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.scard async

scard(name: str) -> int

Get number of members in a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def scard(self, name: str) -> int:
    """Get number of members in a set asynchronously.

    Args:
        name (str): The set key name.

    Returns:
        RedisIntegerResponseType: Number of members.
    """
    result = self.client.scard(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.sismember async

sismember(name: str, value: str) -> bool

Check if value is in set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
value str

Value to check.

required

Returns:

Name Type Description
bool bool

True if value is member, False otherwise.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sismember(self, name: str, value: str) -> bool:
    """Check if value is in set asynchronously.

    Args:
        name (str): The set key name.
        value (str): Value to check.

    Returns:
        bool: True if value is member, False otherwise.
    """
    result = self.read_only_client.sismember(name, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.mocks.AsyncRedisMock.smembers async

smembers(name: str) -> _set[bytes | str]

Get all members of a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set of all members.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def smembers(self, name: str) -> _set[bytes | str]:
    """Get all members of a set asynchronously.

    Args:
        name (str): The set key name.

    Returns:
        RedisSetResponseType: Set of all members.
    """
    result = self.read_only_client.smembers(name)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return set()
    if isinstance(result, set):
        return result
    if isinstance(result, Iterable):
        return set(result)
    return set()

archipy.adapters.redis.mocks.AsyncRedisMock.spop async

spop(
    name: str, count: int | None = None
) -> bytes | float | int | str | list | None

Remove and return random set members asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
count int | None

Number of members to pop. Defaults to None.

None

Returns:

Type Description
bytes | float | int | str | list | None

bytes | float | int | str | list | None: Popped member(s) or None.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def spop(self, name: str, count: int | None = None) -> bytes | float | int | str | list | None:
    """Remove and return random set members asynchronously.

    Args:
        name (str): The set key name.
        count (int | None): Number of members to pop. Defaults to None.

    Returns:
        bytes | float | int | str | list | None: Popped member(s) or None.
    """
    result = self.client.spop(name, count)
    if isinstance(result, Awaitable):
        awaited_result = await result
        # Type narrowing: result can be any of the return types
        if awaited_result is None or isinstance(awaited_result, (bytes, float, int, str, list)):
            return awaited_result
        raise InvalidArgumentError(
            argument_name="spop_result",
            additional_data={"got": type(awaited_result).__name__},
        )
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.srem async

srem(name: str, *values: bytes | str | float) -> int

Remove members from a set asynchronously.

Parameters:

Name Type Description Default
name str

The set key name.

required
*values bytes | str | float

Members to remove.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Number of members removed.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def srem(self, name: str, *values: bytes | str | float) -> int:
    """Remove members from a set asynchronously.

    Args:
        name (str): The set key name.
        *values (bytes | str | float): Members to remove.

    Returns:
        RedisIntegerResponseType: Number of members removed.
    """
    result = self.client.srem(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.sunion async

sunion(
    keys: bytes | str, *args: bytes | str
) -> _set[bytes | str]

Get union of multiple sets asynchronously.

Parameters:

Name Type Description Default
keys bytes | str

First set key.

required
*args bytes | str

Additional set keys.

()

Returns:

Name Type Description
RedisSetResponseType _set[bytes | str]

Set containing union of all sets.

Source code in archipy/adapters/redis/adapter_mixins/sets.py
async def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]:
    """Get union of multiple sets asynchronously.

    Args:
        keys (bytes | str): First set key.
        *args (bytes | str): Additional set keys.

    Returns:
        RedisSetResponseType: Set containing union of all sets.
    """
    # Convert keys to str for type compatibility, combine into list
    keys_list: list[str] = [str(keys)] + [str(arg) if isinstance(arg, bytes) else arg for arg in args]
    result = self.client.sunion(keys_list)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return set()
    if isinstance(result, set):
        return result
    if isinstance(result, Iterable):
        return set(result)
    return set()

archipy.adapters.redis.mocks.AsyncRedisMock.llen async

llen(name: str) -> int

Get the length of a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def llen(self, name: str) -> int:
    """Get the length of a list asynchronously.

    Args:
        name (str): The key name of the list.

    Returns:
        RedisIntegerResponseType: Length of the list.
    """
    result = self.read_only_client.llen(name)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.lpop async

lpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from list left asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from list left asynchronously.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    result = self.client.lpop(name, count)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.lpush async

lpush(name: str, *values: bytes | str | float) -> int

Push elements to list left asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to list left asynchronously.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.lpush(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.lrange async

lrange(
    name: str, start: int, end: int
) -> list[bytes | str]

Get a range of elements from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
start int

Start index.

required
end int

End index.

required

Returns:

Name Type Description
RedisListResponseType list[bytes | str]

List of elements in range.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lrange(self, name: str, start: int, end: int) -> list[bytes | str]:
    """Get a range of elements from a list asynchronously.

    Args:
        name (str): The key name of the list.
        start (int): Start index.
        end (int): End index.

    Returns:
        RedisListResponseType: List of elements in range.
    """
    result = self.read_only_client.lrange(name, start, end)
    if isinstance(result, Awaitable):
        result = await result
    if result is None:
        return []
    if isinstance(result, list):
        return result
    if isinstance(result, Iterable):
        return list(result)
    return []

archipy.adapters.redis.mocks.AsyncRedisMock.lrem async

lrem(name: str, count: int, value: str) -> int

Remove elements from a list asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int

Number of occurrences to remove.

required
value str

Value to remove.

required

Returns:

Name Type Description
RedisIntegerResponseType int

Number of elements removed.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lrem(self, name: str, count: int, value: str) -> int:
    """Remove elements from a list asynchronously.

    Args:
        name (str): The key name of the list.
        count (int): Number of occurrences to remove.
        value (str): Value to remove.

    Returns:
        RedisIntegerResponseType: Number of elements removed.
    """
    result = self.client.lrem(name, count, value)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.lset async

lset(name: str, index: int, value: str) -> bool

Set list element by index asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
index int

Index of the element.

required
value str

New value.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def lset(self, name: str, index: int, value: str) -> bool:
    """Set list element by index asynchronously.

    Args:
        name (str): The key name of the list.
        index (int): Index of the element.
        value (str): New value.

    Returns:
        bool: True if successful.
    """
    result = self.client.lset(name, index, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.mocks.AsyncRedisMock.rpop async

rpop(
    name: str, count: int | None = None
) -> bytes | str | list[bytes | str] | None

Remove and return elements from list right asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
count int | None

Number of elements to pop. Defaults to None.

None

Returns:

Name Type Description
Any bytes | str | list[bytes | str] | None

Popped element(s) or None if list is empty.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def rpop(self, name: str, count: int | None = None) -> bytes | str | list[bytes | str] | None:
    """Remove and return elements from list right asynchronously.

    Args:
        name (str): The key name of the list.
        count (int | None): Number of elements to pop. Defaults to None.

    Returns:
        Any: Popped element(s) or None if list is empty.
    """
    result = self.client.rpop(name, count)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.rpush async

rpush(name: str, *values: bytes | str | float) -> int

Push elements to list right asynchronously.

Parameters:

Name Type Description Default
name str

The key name of the list.

required
*values bytes | str | float

Values to push.

()

Returns:

Name Type Description
RedisIntegerResponseType int

Length of the list after push.

Source code in archipy/adapters/redis/adapter_mixins/lists.py
async def rpush(self, name: str, *values: bytes | str | float) -> int:
    """Push elements to list right asynchronously.

    Args:
        name (str): The key name of the list.
        *values (bytes | str | float): Values to push.

    Returns:
        RedisIntegerResponseType: Length of the list after push.
    """
    result = self.client.rpush(name, *values)
    return await self._ensure_async_int(result)

archipy.adapters.redis.mocks.AsyncRedisMock.pttl async

pttl(name: bytes | str) -> int

Get the time to live in milliseconds for a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in milliseconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def pttl(self, name: bytes | str) -> int:
    """Get the time to live in milliseconds for a key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in milliseconds.
    """
    return await self.read_only_client.pttl(name)

archipy.adapters.redis.mocks.AsyncRedisMock.incrby async

incrby(name: bytes | str, amount: int = 1) -> int

Increment the integer value of a key by the given amount asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
amount int

Amount to increment by. Defaults to 1.

1

Returns:

Name Type Description
RedisResponseType int

The new value after increment.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def incrby(self, name: bytes | str, amount: int = 1) -> int:
    """Increment the integer value of a key by the given amount asynchronously.

    Args:
        name (bytes | str): The key name.
        amount (int): Amount to increment by. Defaults to 1.

    Returns:
        RedisResponseType: The new value after increment.
    """
    return await self.client.incrby(name, amount)

archipy.adapters.redis.mocks.AsyncRedisMock.increx async

increx(
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]

Increment a windowed counter with bounds and expiration control asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key to increment.

required
byfloat float

Increment amount as a float.

None
byint int

Increment amount as an int.

None
lbound float | int

Lower bound for the resulting value.

None
ubound float | int

Upper bound for the resulting value.

None
saturate bool

Clamp out-of-bounds results instead of rejecting. Defaults to False.

False
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None
persist bool

Remove any existing expiration. Defaults to False.

False
enx bool

Set expiration only if none already exists. Defaults to False.

False

Returns:

Name Type Description
RedisResponseType list[Any]

A two-element list of [new_value, actual_increment_applied].

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def increx(
    self,
    name: bytes | str,
    byfloat: float | None = None,
    byint: int | None = None,
    lbound: float | None = None,
    ubound: float | None = None,
    saturate: bool = False,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
    persist: bool = False,
    enx: bool = False,
) -> list[Any]:
    """Increment a windowed counter with bounds and expiration control asynchronously.

    Args:
        name (bytes | str): The key to increment.
        byfloat (float, optional): Increment amount as a float.
        byint (int, optional): Increment amount as an int.
        lbound (float | int, optional): Lower bound for the resulting value.
        ubound (float | int, optional): Upper bound for the resulting value.
        saturate (bool): Clamp out-of-bounds results instead of rejecting. Defaults to False.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.
        persist (bool): Remove any existing expiration. Defaults to False.
        enx (bool): Set expiration only if none already exists. Defaults to False.

    Returns:
        RedisResponseType: A two-element list of [new_value, actual_increment_applied].
    """
    result = self.client.increx(
        name,
        byfloat=byfloat,
        byint=byint,
        lbound=lbound,
        ubound=ubound,
        saturate=saturate,
        ex=ex,
        px=px,
        exat=exat,
        pxat=pxat,
        persist=persist,
        enx=enx,
    )
    if isinstance(result, Awaitable):
        result = await result
    return list(result)

archipy.adapters.redis.mocks.AsyncRedisMock.set async

set(
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None

Set the value of a key with optional expiration asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required
value int | bytes | str | float

The value to set.

required
ex int | timedelta | None

Expire time in seconds.

None
px int | timedelta | None

Expire time in milliseconds.

None
nx bool

Only set if key doesn't exist.

False
xx bool

Only set if key exists.

False
keepttl bool

Retain the TTL from the previous value.

False
get bool

Return the old value.

False
exat int | datetime | None

Absolute expiration time in seconds.

None
pxat int | datetime | None

Absolute expiration time in milliseconds.

None

Returns:

Name Type Description
RedisResponseType bool | str | bytes | None

Result of the operation.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def set(
    self,
    name: bytes | str,
    value: bytes | str | float,
    ex: int | timedelta | None = None,
    px: int | timedelta | None = None,
    nx: bool = False,
    xx: bool = False,
    keepttl: bool = False,
    get: bool = False,
    exat: int | datetime | None = None,
    pxat: int | datetime | None = None,
) -> bool | str | bytes | None:
    """Set the value of a key with optional expiration asynchronously.

    Args:
        name (bytes | str): The key name.
        value (int | bytes | str | float): The value to set.
        ex (int | timedelta | None): Expire time in seconds.
        px (int | timedelta | None): Expire time in milliseconds.
        nx (bool): Only set if key doesn't exist.
        xx (bool): Only set if key exists.
        keepttl (bool): Retain the TTL from the previous value.
        get (bool): Return the old value.
        exat (int | datetime | None): Absolute expiration time in seconds.
        pxat (int | datetime | None): Absolute expiration time in milliseconds.

    Returns:
        RedisResponseType: Result of the operation.
    """
    return await self.client.set(name, value, ex, px, nx, xx, keepttl, get, exat, pxat)

archipy.adapters.redis.mocks.AsyncRedisMock.get async

get(key: str) -> bytes | str | None

Get the value of a key asynchronously.

Parameters:

Name Type Description Default
key str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None if not exists.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def get(self, key: str) -> bytes | str | None:
    """Get the value of a key asynchronously.

    Args:
        key (str): The key name.

    Returns:
        RedisResponseType: The value of the key or None if not exists.
    """
    return await self.read_only_client.get(key)

archipy.adapters.redis.mocks.AsyncRedisMock.mget async

mget(
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]

Get the values of multiple keys asynchronously.

Parameters:

Name Type Description Default
keys bytes | str | Iterable[bytes | str]

Single key or iterable of keys.

required
*args bytes | str

Additional keys.

()

Returns:

Name Type Description
RedisResponseType list[bytes | str | None]

List of values.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def mget(
    self,
    keys: bytes | str | Iterable[bytes | str],
    *args: bytes | str,
) -> list[bytes | str | None]:
    """Get the values of multiple keys asynchronously.

    Args:
        keys (bytes | str | Iterable[bytes | str]): Single key or iterable of keys.
        *args (bytes | str): Additional keys.

    Returns:
        RedisResponseType: List of values.
    """
    return await self.read_only_client.mget(keys, *args)

archipy.adapters.redis.mocks.AsyncRedisMock.mset async

mset(
    mapping: Mapping[bytes | str, bytes | str | float],
) -> bool

Set multiple keys to their values asynchronously.

Parameters:

Name Type Description Default
mapping Mapping[bytes | str, bytes | str | float]

Dictionary of key-value pairs.

required

Returns:

Name Type Description
RedisResponseType bool

Always returns 'OK'.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def mset(self, mapping: Mapping[bytes | str, bytes | str | float]) -> bool:
    """Set multiple keys to their values asynchronously.

    Args:
        mapping (Mapping[bytes | str, bytes | str | float]): Dictionary of key-value pairs.

    Returns:
        RedisResponseType: Always returns 'OK'.
    """
    # Convert Mapping to dict for type compatibility with Redis client
    dict_mapping: dict[str, bytes | str | float] = {str(k): v for k, v in mapping.items()}
    return await self.client.mset(dict_mapping)

archipy.adapters.redis.mocks.AsyncRedisMock.keys async

keys(
    pattern: bytes | str = "*", **kwargs: Any
) -> list[bytes | str]

Find all keys matching the pattern asynchronously.

Parameters:

Name Type Description Default
pattern bytes | str

Pattern to match keys against. Defaults to "*".

'*'
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType list[bytes | str]

List of matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def keys(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]:
    """Find all keys matching the pattern asynchronously.

    Args:
        pattern (bytes | str): Pattern to match keys against. Defaults to "*".
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: List of matching keys.
    """
    return await self.read_only_client.keys(pattern, **kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.getset async

getset(
    key: bytes | str, value: bytes | str | float
) -> bytes | str | None

Set a key's value and return its old value asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The new value.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The previous value or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def getset(self, key: bytes | str, value: bytes | str | float) -> bytes | str | None:
    """Set a key's value and return its old value asynchronously.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The new value.

    Returns:
        RedisResponseType: The previous value or None.
    """
    return await self.client.getset(key, value)

archipy.adapters.redis.mocks.AsyncRedisMock.getdel async

getdel(key: bytes | str) -> bytes | str | None

Get a key's value and delete it asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str | None

The value of the key or None.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def getdel(self, key: bytes | str) -> bytes | str | None:
    """Get a key's value and delete it asynchronously.

    Args:
        key (bytes | str): The key name.

    Returns:
        RedisResponseType: The value of the key or None.
    """
    return await self.client.getdel(key)

archipy.adapters.redis.mocks.AsyncRedisMock.exists async

exists(*names: bytes | str) -> int

Check if keys exist asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys that exist.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def exists(self, *names: bytes | str) -> int:
    """Check if keys exist asynchronously.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys that exist.
    """
    return await self.read_only_client.exists(*names)

archipy.adapters.redis.mocks.AsyncRedisMock.delete async

delete(*names: bytes | str) -> int

Delete keys asynchronously.

Parameters:

Name Type Description Default
*names bytes | str

Variable number of key names.

()

Returns:

Name Type Description
RedisResponseType int

Number of keys deleted.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def delete(self, *names: bytes | str) -> int:
    """Delete keys asynchronously.

    Args:
        *names (bytes | str): Variable number of key names.

    Returns:
        RedisResponseType: Number of keys deleted.
    """
    return await self.client.delete(*names)

archipy.adapters.redis.mocks.AsyncRedisMock.append async

append(key: bytes | str, value: bytes | str | float) -> int

Append a value to a key asynchronously.

Parameters:

Name Type Description Default
key bytes | str

The key name.

required
value bytes | str | float

The value to append.

required

Returns:

Name Type Description
RedisResponseType int

Length of the string after append.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def append(self, key: bytes | str, value: bytes | str | float) -> int:
    """Append a value to a key asynchronously.

    Args:
        key (bytes | str): The key name.
        value (bytes | str | float): The value to append.

    Returns:
        RedisResponseType: Length of the string after append.
    """
    return await self.client.append(key, value)

archipy.adapters.redis.mocks.AsyncRedisMock.ttl async

ttl(name: bytes | str) -> int

Get the time to live in seconds for a key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType int

Time to live in seconds.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def ttl(self, name: bytes | str) -> int:
    """Get the time to live in seconds for a key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Time to live in seconds.
    """
    return await self.read_only_client.ttl(name)

archipy.adapters.redis.mocks.AsyncRedisMock.type async

type(name: bytes | str) -> bytes | str

Determine the type stored at key asynchronously.

Parameters:

Name Type Description Default
name bytes | str

The key name.

required

Returns:

Name Type Description
RedisResponseType bytes | str

Type of the key's value.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def type(self, name: bytes | str) -> bytes | str:
    """Determine the type stored at key asynchronously.

    Args:
        name (bytes | str): The key name.

    Returns:
        RedisResponseType: Type of the key's value.
    """
    return await self.read_only_client.type(name)

archipy.adapters.redis.mocks.AsyncRedisMock.scan async

scan(
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]

Scan keys in database incrementally asynchronously.

Parameters:

Name Type Description Default
cursor int

Cursor position. Defaults to 0.

0
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Name Type Description
RedisResponseType tuple[int, list[bytes | str]]

Tuple of cursor and list of keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def scan(
    self,
    cursor: int = 0,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> tuple[int, list[bytes | str]]:
    """Scan keys in database incrementally asynchronously.

    Args:
        cursor (int): Cursor position. Defaults to 0.
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        RedisResponseType: Tuple of cursor and list of keys.
    """
    return await self.read_only_client.scan(cursor, match, count, _type, **kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.scan_iter async

scan_iter(
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]

Iterate over keys in database asynchronously.

Parameters:

Name Type Description Default
match bytes | str | None

Pattern to match. Defaults to None.

None
count int | None

Hint for number of keys. Defaults to None.

None
_type str | None

Filter by type. Defaults to None.

None
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
AsyncIterator[bytes | str]

Iterator[Any]: Iterator over matching keys.

Source code in archipy/adapters/redis/adapter_mixins/keys.py
async def scan_iter(
    self,
    match: bytes | str | None = None,
    count: int | None = None,
    _type: str | None = None,
    **kwargs: Any,
) -> AsyncIterator[bytes | str]:
    """Iterate over keys in database asynchronously.

    Args:
        match (bytes | str | None): Pattern to match. Defaults to None.
        count (int | None): Hint for number of keys. Defaults to None.
        _type (str | None): Filter by type. Defaults to None.
        **kwargs (Any): Additional arguments.

    Returns:
        Iterator[Any]: Iterator over matching keys.
    """
    return self.read_only_client.scan_iter(match, count, _type, **kwargs)

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_info async

cluster_info() -> dict[str, str] | None

Get cluster information asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_info(self) -> dict[str, str] | None:
    """Get cluster information asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_info()
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_nodes async

cluster_nodes() -> (
    dict[
        str,
        dict[
            str,
            str
            | bool
            | list[list[str]]
            | list[dict[str, str]],
        ],
    ]
    | None
)

Get cluster nodes information asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_nodes(self) -> dict[str, dict[str, str | bool | list[list[str]] | list[dict[str, str]]]] | None:
    """Get cluster nodes information asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_nodes()
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_slots async

cluster_slots() -> list[Any] | None

Get cluster slots mapping asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_slots(self) -> list[Any] | None:
    """Get cluster slots mapping asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_slots()
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_key_slot async

cluster_key_slot(key: str) -> int | None

Get the hash slot for a key asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_key_slot(self, key: str) -> int | None:
    """Get the hash slot for a key asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_keyslot(key)
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_count_keys_in_slot async

cluster_count_keys_in_slot(slot: int) -> int | None

Count keys in a specific slot asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_count_keys_in_slot(self, slot: int) -> int | None:
    """Count keys in a specific slot asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_countkeysinslot(slot)
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.cluster_get_keys_in_slot async

cluster_get_keys_in_slot(
    slot: int, count: int
) -> list[bytes | str] | None

Get keys in a specific slot asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/cluster.py
async def cluster_get_keys_in_slot(self, slot: int, count: int) -> list[bytes | str] | None:
    """Get keys in a specific slot asynchronously."""
    if isinstance(self.client, AsyncRedisCluster):
        return await self.client.cluster_get_keys_in_slot(slot, count)
    return None

archipy.adapters.redis.mocks.AsyncRedisMock.ping async

ping() -> bool

Ping the Redis server asynchronously.

Returns:

Name Type Description
RedisResponseType bool

'PONG' if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def ping(self) -> bool:
    """Ping the Redis server asynchronously.

    Returns:
        RedisResponseType: 'PONG' if successful.
    """
    result = self.client.ping()
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.flushdb async

flushdb(asynchronous: bool = False) -> bool

Delete all keys in the current database asynchronously.

Parameters:

Name Type Description Default
asynchronous bool

Whether Redis should flush asynchronously. Defaults to False.

False

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def flushdb(self, asynchronous: bool = False) -> bool:
    """Delete all keys in the current database asynchronously.

    Args:
        asynchronous: Whether Redis should flush asynchronously. Defaults to False.

    Returns:
        bool: True if successful.
    """
    result = self.client.flushdb(asynchronous=asynchronous)
    if isinstance(result, Awaitable):
        return await result
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.get_pipeline async

get_pipeline(
    transaction: Any = True, shard_hint: Any = None
) -> AsyncPipeline | AsyncClusterPipeline

Get pipeline for multiple commands asynchronously.

Parameters:

Name Type Description Default
transaction Any

Use transactions. Defaults to True.

True
shard_hint Any

Sharding hint. Defaults to None.

None

Returns:

Type Description
Pipeline | ClusterPipeline

AsyncPipeline | AsyncClusterPipeline: Pipeline object.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def get_pipeline(
    self,
    transaction: Any = True,
    shard_hint: Any = None,
) -> AsyncPipeline | AsyncClusterPipeline:
    """Get pipeline for multiple commands asynchronously.

    Args:
        transaction (Any): Use transactions. Defaults to True.
        shard_hint (Any): Sharding hint. Defaults to None.

    Returns:
        AsyncPipeline | AsyncClusterPipeline: Pipeline object.
    """
    result = self.client.pipeline(transaction, shard_hint)
    if not isinstance(result, (AsyncPipeline, AsyncClusterPipeline)):
        raise InvalidArgumentError(
            argument_name="pipeline",
            additional_data={"expected": "AsyncPipeline", "got": type(result).__name__},
        )
    return result

archipy.adapters.redis.mocks.AsyncRedisMock.config_set async

config_set(name: str, value: str) -> bool

Set a Redis server configuration parameter asynchronously.

Parameters:

Name Type Description Default
name str

The configuration parameter name.

required
value str

The value to set.

required

Returns:

Name Type Description
bool bool

True if successful.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def config_set(self, name: str, value: str) -> bool:
    """Set a Redis server configuration parameter asynchronously.

    Args:
        name (str): The configuration parameter name.
        value (str): The value to set.

    Returns:
        bool: True if successful.
    """
    result = self.client.config_set(name, value)
    if isinstance(result, Awaitable):
        result = await result
    return bool(result)

archipy.adapters.redis.mocks.AsyncRedisMock.config_get async

config_get(pattern: str = '*') -> dict[str, str]

Get Redis server configuration parameters matching a pattern asynchronously.

Parameters:

Name Type Description Default
pattern str

Pattern to match configuration parameter names. Defaults to "*".

'*'

Returns:

Name Type Description
RedisResponseType dict[str, str]

Dictionary of configuration parameter names to values.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def config_get(self, pattern: str = "*") -> dict[str, str]:
    """Get Redis server configuration parameters matching a pattern asynchronously.

    Args:
        pattern (str): Pattern to match configuration parameter names. Defaults to "*".

    Returns:
        RedisResponseType: Dictionary of configuration parameter names to values.
    """
    result = self.read_only_client.config_get(pattern)
    if isinstance(result, Awaitable):
        result = await result
    return {str(k): str(v) for k, v in result.items()} if result else {}

archipy.adapters.redis.mocks.AsyncRedisMock.search_index

search_index(name: str) -> AsyncRedisSearchHandlePort

Return an index-bound async RediSearch handle.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
def search_index(self, name: str) -> AsyncRedisSearchHandlePort:
    """Return an index-bound async RediSearch handle."""
    return AsyncRedisSearchHandle(self._get_search_client(), name)

archipy.adapters.redis.mocks.AsyncRedisMock.list_search_indexes async

list_search_indexes() -> list[str]

List RediSearch indexes available on the server asynchronously.

Source code in archipy/adapters/redis/adapter_mixins/connection.py
async def list_search_indexes(self) -> list[str]:
    """List RediSearch indexes available on the server asynchronously."""
    return await list_redis_search_indexes_async(self._get_search_client())

options: show_root_toc_entry: false heading_level: 3