Clients

Redis

class Redis(host: str | None = 'localhost', port: int | None = 6379, db: int = 0, *, username: str | None = None, password: str | None = None, stream_timeout: float | None = None, connect_timeout: float | None = None, connection_pool: ConnectionPool | None = None, connection_pool_cls: Type[ConnectionPool] = ConnectionPool, unix_socket_path: str | None = None, encoding: str = 'utf-8', decode_responses: bool = False, ssl: bool = False, ssl_context: SSLContext | None = None, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = None, ssl_check_hostname: bool | None = None, ssl_ca_certs: str | None = None, max_connections: int | None = None, max_idle_time: float = 0, idle_check_interval: float = 1, client_name: str | None = None, protocol_version: Literal[2, 3] = 3, verify_version: bool = True, cache: AbstractCache | None = None, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = ConstantRetryPolicy((ConnectionError, TimeoutError), 2, 0.01), **kwargs: Any)[source]
Changes
Parameters:
  • host – The hostname of the redis server

  • port – The port at which th redis server is listening on

  • db – database number to switch to upon connection

  • username – Username for authenticating with the redis server

  • password – Password for authenticating with the redis server

  • stream_timeout – Timeout (seconds) when reading responses from the server

  • connect_timeout – Timeout (seconds) for establishing a connection to the server

  • connection_pool – The connection pool instance to use. If not provided a new pool will be assigned to this client.

  • connection_pool_cls – The connection pool class to use when constructing a connection pool for this instance.

  • unix_socket_path – Path to the UDS which the redis server is listening at

  • encoding – The codec to use to encode strings transmitted to redis and decode responses with. (See Encoding/Decoding)

  • decode_responses – If True string responses from the server will be decoded using encoding before being returned. (See Encoding/Decoding)

  • ssl – Whether to use an SSL connection

  • ssl_context – If provided the ssl.SSLContext will be used when establishing the connection. Otherwise either the default context (if no other ssl related parameters are provided) or a custom context based on the other ssl_* parameters will be used.

  • ssl_keyfile – Path of the private key to use

  • ssl_certfile – Path to the certificate corresponding to ssl_keyfile

  • ssl_cert_reqs – Whether to try to verify the server’s certificates and how to behave if verification fails (See ssl.SSLContext.verify_mode).

  • ssl_check_hostname – Whether to enable hostname checking when establishing an ssl connection.

  • ssl_ca_certs – Path to a concatenated certificate authority file or a directory containing several CA certifcates to use for validating the server’s certificates when ssl_cert_reqs is not "none" (See ssl.SSLContext.load_verify_locations()).

  • max_connections – Maximum capacity of the connection pool (Ignored if connection_pool is not None.

  • max_idle_time – Maximum number of a seconds an unused connection is cached before it is disconnected.

  • idle_check_interval – Periodicity of idle checks (seconds) to release idle connections.

  • client_name – The client name to identifiy with the redis server

  • protocol_version – Whether to use the RESP (2) or RESP3 (3) protocol for parsing responses from the server (Default 3). (See Redis Response)

  • verify_version – Validate redis server version against the documented version introduced before executing a command and raises a CommandNotSupportedError error if the required version is higher than the reported server version

  • cache – If provided the cache will be used to avoid requests for read only commands if the client has already requested the data and it hasn’t been invalidated. The cache is responsible for any mutations to the keys that happen outside of this client

  • noreply – If True the client will not request a response for any commands sent to the server.

  • noevict – Ensures that connections from the client will be excluded from the client eviction process even if we’re above the configured client eviction threshold.

  • notouch – Ensures that commands sent by the client will not alter the LRU/LFU of the keys they access.

  • retry_policy – The retry policy to use when interacting with the redis server

classmethod from_url(url: str, db: int | None = None, *, decode_responses: ~typing.Literal[False] = False, protocol_version: ~typing.Literal[2, 3] = 3, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: ~coredis.retry.RetryPolicy = ConstantRetryPolicy<retries=2, retryable_exceptions=ConnectionError, TimeoutError>, **kwargs: ~typing.Any) RedisBytesT[source]
classmethod from_url(url: str, db: int | None = None, *, decode_responses: ~typing.Literal[True], protocol_version: ~typing.Literal[2, 3] = 3, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: ~coredis.retry.RetryPolicy = ConstantRetryPolicy<retries=2, retryable_exceptions=ConnectionError,TimeoutError>, **kwargs: ~typing.Any) RedisStringT

Return a Redis client object configured from the given URL, which must use either the redis:// scheme for RESP connections or the unix:// scheme for Unix domain sockets.

For example:

  • redis://[:password]@localhost:6379/0

  • rediss://[:password]@localhost:6379/0

  • unix://[:password]@/path/to/socket.sock?db=0

url and kwargs are passed as is to the coredis.ConnectionPool.from_url().

bitfield(key: KeyT) BitFieldOperation
Returns:

a BitFieldOperation instance to conveniently construct one or more bitfield operations on key.

bitfield_ro(key: KeyT) BitFieldOperation
Returns:

a BitFieldOperation instance to conveniently construct bitfield operations on a read only replica against key.

Raises ReadOnlyError if a write operation is attempted

decoding(mode: Literal[False], encoding: str | None = None) ContextManager[Redis[bytes]][source]
decoding(mode: Literal[True], encoding: str | None = None) ContextManager[Redis[str]]

Context manager to temporarily change the decoding behavior of the client

Parameters:
  • mode – Whether to decode or not

  • encoding – Optional encoding to use if decoding. If not provided the encoding parameter provided to the client will be used.

Example:

client = coredis.Redis(decode_responses=True)
await client.set("fubar", "baz")
assert await client.get("fubar") == "baz"
with client.decoding(False):
    assert await client.get("fubar") == b"baz"
    with client.decoding(True):
        assert await client.get("fubar") == "baz"

Added in version 4.8.0.

ensure_persistence(local: Literal[0, 1] = 0, replicas: int = 0, timeout_ms: int = 100) Iterator[ClientT]

Context manager to ensure that commands executed within the context are synced to the AOF of a local host and/or replicas within timeout_ms milliseconds.

Internally this uses WAITAOF after each command executed within the context

Raises:

coredis.exceptions.PersistenceError

Example for standalone client:

client = coredis.Redis()
with client.ensure_persistence(1, 0, 20):
    await client.set("fubar", 1)

Example for cluster:

client = coredis.RedisCluster("localhost", 7000)
with client.ensure_persistence(1, 1, 20):
    await client.set("fubar", 1)

Added in version 4.12.0.

ensure_replication(replicas: int = 1, timeout_ms: int = 100) Iterator[ClientT]

Context manager to ensure that commands executed within the context are replicated to atleast replicas within timeout_ms milliseconds.

Internally this uses WAIT after each command executed within the context

Raises:

coredis.exceptions.ReplicationError

Example:

client = coredis.RedisCluster("localhost", 7000)
with client.ensure_replication(1, 20):
    await client.set("fubar", 1)
async execute_command(command: bytes, *args: ValueT, callback: Callable[[...], R] = NoopCallback(), **options: ValueT | None) R[source]

Executes a command with configured retries and returns the parsed response

async get_library(name: StringT) Library

Fetch a pre registered library

Parameters:

name – name of the library

Added in version 3.1.0.

async hscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncGenerator[tuple[AnyStr, AnyStr], None]

Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.

ignore_replies() Iterator[ClientT]

Context manager to run commands without waiting for a reply.

Example:

client = coredis.Redis()
with client.ignore_replies():
    assert None == await client.set("fubar", 1), "noreply"
assert True == await client.set("fubar", 1), "reply"
monitor() Monitor[source]

Return an instance of a Monitor

The monitor can be used as an async iterator or individual commands can be fetched via get_command().

async pipeline(transaction: bool | None = True, watches: Parameters[KeyT] | None = None, timeout: float | None = None) coredis.pipeline.Pipeline[AnyStr][source]

Returns a new pipeline object that can queue multiple commands for batch execution.

Parameters:
  • transaction – indicates whether all commands should be executed atomically.

  • watches – If transaction is True these keys are watched for external changes during the transaction.

  • timeout – If specified this value will take precedence over Redis.stream_timeout

pubsub(ignore_subscribe_messages: bool = False, retry_policy: RetryPolicy | None = None, **kwargs: Any) PubSub[source]

Return a Pub/Sub instance that can be used to subscribe to channels and patterns and receive messages that get published to them.

Parameters:
  • ignore_subscribe_messages – Whether to skip subscription acknowledgement messages

  • retry_policy – An explicit retry policy to use in the subscriber.

async register_library(name: StringT, code: StringT, replace: bool = False) Library

Register a new library

Parameters:
  • name – name of the library

  • code – raw code for the library

  • replace – Whether to replace the library when intializing. If False an exception will be raised if the library was already loaded in the target redis instance.

Added in version 3.1.0.

register_script(script: ValueT) Script

Registers a Lua script

Returns:

A coredis.commands.script.Script instance that is callable and hides the complexity of dealing with scripts, keys, and shas.

async scan_iter(match: StringT | None = None, count: int | None = None, type_: StringT | None = None) AsyncIterator

Make an iterator using the SCAN command so that the client doesn’t need to remember the cursor position.

async sscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncIterator

Make an iterator using the SSCAN command so that the client doesn’t need to remember the cursor position.

async transaction(func: Callable[['coredis.pipeline.Pipeline[AnyStr]'], Coroutine[Any, Any, Any]], *watches: KeyT, value_from_callable: bool = False, watch_delay: float | None = None, **kwargs: Any) Any | None[source]

Convenience method for executing the callable func as a transaction while watching all keys specified in watches.

Parameters:
  • func – callable should expect a single argument which is a coredis.pipeline.Pipeline object retrieved by calling pipeline().

  • watches – The keys to watch during the transaction

  • value_from_callable – Whether to return the result of transaction or the value returned from func

async zscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncIterator[ScoredMember]

Make an iterator using the ZSCAN command so that the client doesn’t need to remember the cursor position.

async append(key: KeyT, value: ValueT) int

Append a value to a key

Returns:

the length of the string after the append operation.

Redis command documentation: APPEND

async decr(key: KeyT) int

Decrement the integer value of a key by one

Returns:

the value of key after the decrement

Redis command documentation: DECR

async decrby(key: KeyT, decrement: int) int

Decrement the integer value of a key by the given number

Returns:

the value of key after the decrement

Redis command documentation: DECRBY

async get(key: KeyT) AnyStr | None

Get the value of a key

Returns:

the value of key, or None when key does not exist.

Redis command documentation: GET

Hint

Supports client side caching

async getdel(key: KeyT) AnyStr | None

Get the value of a key and delete the key

Returns:

the value of key, None when key does not exist, or an error if the key’s value type isn’t a string.

Redis command documentation: GETDEL

Compatibility:

async getex(key: KeyT, ex: int | timedelta | None = None, px: int | timedelta | None = None, exat: int | datetime | None = None, pxat: int | datetime | None = None, persist: bool | None = None) AnyStr | None

Get the value of a key and optionally set its expiration

GETEX is similar to GET, but is a write command with additional options. All time parameters can be given as datetime.timedelta or integers.

Parameters:
  • key – name of the key

  • ex – sets an expire flag on key key for ex seconds.

  • px – sets an expire flag on key key for px milliseconds.

  • exat – sets an expire flag on key key for ex seconds, specified in unix time.

  • pxat – sets an expire flag on key key for ex milliseconds, specified in unix time.

  • persist – remove the time to live associated with key.

Returns:

the value of key, or None when key does not exist.

Redis command documentation: GETEX

Compatibility:

async getrange(key: KeyT, start: int, end: int) AnyStr

Get a substring of the string stored at a key

Returns:

The substring of the string value stored at key, determined by the offsets start and end (both are inclusive)

Redis command documentation: GETRANGE

Hint

Supports client side caching

async getset(key: KeyT, value: ValueT) AnyStr | None

Set the string value of a key and return its old value

Returns:

the old value stored at key, or None when key did not exist.

Redis command documentation: GETSET

async incr(key: KeyT) int

Increment the integer value of a key by one

Returns:

the value of key after the increment. If no key exists, the value will be initialized as 1.

Redis command documentation: INCR

async incrby(key: KeyT, increment: int) int

Increment the integer value of a key by the given amount

Returns:

the value of key after the increment If no key exists, the value will be initialized as increment

Redis command documentation: INCRBY

async incrbyfloat(key: KeyT, increment: int | float) float

Increment the float value of a key by the given amount

Returns:

the value of key after the increment. If no key exists, the value will be initialized as increment

Redis command documentation: INCRBYFLOAT

async lcs(key1: KeyT, key2: KeyT, *, len_: bool | None = None, idx: bool | None = None, minmatchlen: int | None = None, withmatchlen: bool | None = None) AnyStr | int | LCSResult

Find the longest common substring

Returns:

The matched string if no other arguments are given. The returned values vary depending on different arguments.

  • If len_ is provided the length of the longest match

  • If idx is True all the matches with the start/end positions of both keys. Optionally, if withmatchlen is True each match will contain the length of the match.

Redis command documentation: LCS

Compatibility:

Added in version 3.0.0.

async mget(keys: Parameters[KeyT]) Tuple[AnyStr | None, ...]

Returns values ordered identically to keys

Redis command documentation: MGET

async mset(key_values: Mapping[KeyT, ValueT]) bool

Sets multiple keys to multiple values

Redis command documentation: MSET

async msetnx(key_values: Mapping[KeyT, ValueT]) bool

Set multiple keys to multiple values, only if none of the keys exist

Returns:

Whether all the keys were set

Redis command documentation: MSETNX

async psetex(key: KeyT, milliseconds: int | timedelta, value: ValueT) bool

Set the value and expiration in milliseconds of a key

Redis command documentation: PSETEX

async set(key: KeyT, value: ValueT, *, condition: Literal[PureToken.NX, PureToken.XX] | None = None, get: bool | None = None, ex: int | timedelta | None = None, px: int | timedelta | None = None, exat: int | datetime | None = None, pxat: int | datetime | None = None, keepttl: bool | None = None) AnyStr | bool | None

Set the string value of a key

Parameters:
  • condition – Condition to use when setting the key

  • get – Return the old string stored at key, or nil if key did not exist. An error is returned and the command is aborted if the value stored at key is not a string.

  • ex – Number of seconds to expire in

  • px – Number of milliseconds to expire in

  • exat – Expiry time with seconds granularity

  • pxat – Expiry time with milliseconds granularity

  • keepttl – Retain the time to live associated with the key

Returns:

Whether the operation was performed successfully.

Warning

If the command is issued with the get argument, the old string value stored at key is return regardless of success or failure - except if the key was not found.

Redis command documentation: SET

Compatibility:

async setex(key: KeyT, value: ValueT, seconds: int | timedelta) bool

Set the value of key key to value that expires in seconds

Redis command documentation: SETEX

async setnx(key: KeyT, value: ValueT) bool

Sets the value of key key to value if key doesn’t exist

Redis command documentation: SETNX

async setrange(key: KeyT, offset: int, value: ValueT) int

Overwrite bytes in the value of key starting at offset with value. If offset plus the length of value exceeds the length of the original value, the new value will be larger than before.

If offset exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what’s being injected.

Returns:

the length of the string after it was modified by the command.

Redis command documentation: SETRANGE

async strlen(key: KeyT) int

Get the length of the value stored in a key

Returns:

the length of the string at key, or 0 when key does not

Redis command documentation: STRLEN

Hint

Supports client side caching

async substr(key: KeyT, start: int, end: int) AnyStr

Get a substring of the string stored at a key

Returns:

the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). Negative offsets can be used in order to provide an offset starting from the end of the string.

Redis command documentation: SUBSTR

Hint

Supports client side caching

async bitcount(key: KeyT, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) int

Returns the count of set bits in the value of key. Optional start and end parameters indicate which bytes to consider

Redis command documentation: BITCOUNT

Compatibility:

async bitop(keys: Parameters[KeyT], operation: StringT, destkey: KeyT) int

Perform a bitwise operation using operation between keys and store the result in destkey.

Redis command documentation: BITOP

async bitpos(key: KeyT, bit: int, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) int

Return the position of the first bit set to 1 or 0 in a string. start and end defines the search range. The range is interpreted as a range of bytes and not a range of bits, so start=0 and end=2 means to look at the first three bytes.

Returns:

The position of the first bit set to 1 or 0 according to the request. If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned.

If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns the first bit not part of the string on the right.

So if the string is three bytes set to the value 0xff the command BITPOS key 0 will return 24, since up to bit 23 all the bits are 1.

Basically, the function considers the right of the string as padded with zeros if you look for clear bits and specify no range or the start argument only.

However, this behavior changes if you are looking for clear bits and specify a range with both start and end.

If no clear bit is found in the specified range, the function returns -1 as the user specified a clear range and there are no 0 bits in that range.

Redis command documentation: BITPOS

Compatibility:

async getbit(key: KeyT, offset: int) int

Returns the bit value at offset in the string value stored at key

Returns:

the bit value stored at offset.

Redis command documentation: GETBIT

async setbit(key: KeyT, offset: int, value: int) int

Flag the offset in key as value.

Redis command documentation: SETBIT

async copy(source: KeyT, destination: KeyT, db: int | None = None, replace: bool | None = None) bool

Copy a key

Redis command documentation: COPY

Compatibility:

Added in version 3.0.0.

async delete(keys: Parameters[KeyT]) int

Delete one or more keys specified by keys

Returns:

The number of keys that were removed.

Redis command documentation: DEL

async dump(key: KeyT) bytes

Return a serialized version of the value stored at the specified key.

Returns:

the serialized value

Redis command documentation: DUMP

async exists(keys: Parameters[KeyT]) int

Determine if a key exists

Returns:

the number of keys that exist from those specified as arguments.

Redis command documentation: EXISTS

async expire(key: KeyT, seconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set a key’s time to live in seconds

Returns:

if the timeout was set or not set. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: EXPIRE

Compatibility:

async expireat(key: KeyT, unix_time_seconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set the expiration for a key to a specific time

Returns:

if the timeout was set or no. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: EXPIREAT

Compatibility:

async expiretime(key: KeyT) datetime

Get the expiration Unix timestamp for a key

Returns:

Expiration Unix timestamp in seconds, or a negative value in order to signal an error.

  • The command returns -1 if the key exists but has no associated expiration time.

  • The command returns -2 if the key does not exist.

Redis command documentation: EXPIRETIME

Compatibility:

Added in version 3.0.0.

async keys(pattern: StringT = '*') set[AnyStr]

Find all keys matching the given pattern

Returns:

keys matching pattern.

Redis command documentation: KEYS

async migrate(host: StringT, port: int, destination_db: int, timeout: int, *keys: KeyT, copy: bool | None = None, replace: bool | None = None, auth: StringT | None = None, username: StringT | None = None, password: StringT | None = None) bool

Atomically transfer key(s) from a Redis instance to another one.

Returns:

If all keys were found in the source instance.

Redis command documentation: MIGRATE

Added in version 3.0.0.

async move(key: KeyT, db: int) bool

Move a key to another database

Redis command documentation: MOVE

async object_encoding(key: KeyT) AnyStr | None

Return the internal encoding for the object stored at key

Returns:

the encoding of the object, or None if the key doesn’t exist

Redis command documentation: OBJECT ENCODING

async object_freq(key: KeyT) int

Return the logarithmic access frequency counter for the object stored at key

Returns:

The counter’s value.

Redis command documentation: OBJECT FREQ

async object_idletime(key: KeyT) int

Return the time in seconds since the last access to the object stored at key

Returns:

The idle time in seconds.

Redis command documentation: OBJECT IDLETIME

async object_refcount(key: KeyT) int

Return the reference count of the object stored at key

Returns:

The number of references.

Redis command documentation: OBJECT REFCOUNT

async persist(key: KeyT) bool

Removes an expiration on key

Redis command documentation: PERSIST

async pexpire(key: KeyT, milliseconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set a key’s time to live in milliseconds

Returns:

if the timeout was set or not. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: PEXPIRE

Compatibility:

async pexpireat(key: KeyT, unix_time_milliseconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set the expiration for a key as a UNIX timestamp specified in milliseconds

Returns:

if the timeout was set or not. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: PEXPIREAT

Compatibility:

async pexpiretime(key: KeyT) datetime

Get the expiration Unix timestamp for a key in milliseconds

Returns:

Expiration Unix timestamp in milliseconds, or a negative value in order to signal an error

  • The command returns -1 if the key exists but has no associated expiration time.

  • The command returns -2 if the key does not exist.

Redis command documentation: PEXPIRETIME

Compatibility:

Added in version 3.0.0.

async pttl(key: KeyT) int

Returns the number of milliseconds until the key key will expire

Returns:

TTL in milliseconds, or a negative value in order to signal an error

Redis command documentation: PTTL

async randomkey() AnyStr | None

Returns the name of a random key

Returns:

the random key, or None when the database is empty.

Redis command documentation: RANDOMKEY

async rename(key: KeyT, newkey: KeyT) bool

Rekeys key key to newkey

Redis command documentation: RENAME

async renamenx(key: KeyT, newkey: KeyT) bool

Rekeys key key to newkey if newkey doesn’t already exist

Returns:

False when newkey already exists.

Redis command documentation: RENAMENX

async restore(key: KeyT, ttl: int | timedelta | datetime, serialized_value: bytes, replace: bool | None = None, absttl: bool | None = None, idletime: int | timedelta | None = None, freq: int | None = None) bool

Create a key using the provided serialized value, previously obtained using DUMP.

Redis command documentation: RESTORE

async scan(cursor: int | None = 0, match: StringT | None = None, count: int | None = None, type_: StringT | None = None) tuple[int, tuple[AnyStr, ...]]

Incrementally iterate the keys space

Redis command documentation: SCAN

async sort(key: KeyT, gets: Parameters[KeyT] | None = None, by: StringT | None = None, offset: int | None = None, count: int | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, alpha: bool | None = None, store: KeyT | None = None) Tuple[AnyStr, ...] | int

Sort the elements in a list, set or sorted set

Returns:

sorted elements.

When the store option is specified the command returns the number of sorted elements in the destination list.

Redis command documentation: SORT

async sort_ro(key: KeyT, gets: Parameters[KeyT] | None = None, by: StringT | None = None, offset: int | None = None, count: int | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, alpha: bool | None = None) Tuple[AnyStr, ...]

Sort the elements in a list, set or sorted set. Read-only variant of SORT.

Returns:

sorted elements.

Redis command documentation: SORT_RO

Compatibility:

Added in version 3.0.0.

async touch(keys: Parameters[KeyT]) int

Alters the last access time of a key(s). Returns the number of existing keys specified.

Returns:

The number of keys that were touched.

Redis command documentation: TOUCH

async ttl(key: KeyT) int

Get the time to live for a key in seconds

Returns:

TTL in seconds, or a negative value in order to signal an error

Redis command documentation: TTL

async type(key: KeyT) AnyStr | None

Determine the type stored at key

Returns:

type of key, or None when key does not exist.

Redis command documentation: TYPE

Hint

Supports client side caching

Delete a key asynchronously in another thread. Otherwise it is just as delete(), but non blocking.

Returns:

The number of keys that were unlinked.

Redis command documentation: UNLINK

async wait(numreplicas: int, timeout: int) int

Wait for the synchronous replication of all the write commands sent in the context of the current connection

Returns:

the number of replicas the write was replicated to

Redis command documentation: WAIT

Warning

Using wait directly is not recommended. Use the Redis.ensure_replication() or RedisCluster.ensure_replication() context managers to ensure a command is replicated to the number of replicas

async waitaof(numlocal: int, numreplicas: int, timeout: int) tuple[int, ...]

Wait for all write commands sent in the context of the current connection to be synced to AOF of local host and/or replicas

Returns:

a tuple of (numlocal, numreplicas) that the write commands were synced to

Redis command documentation: WAITAOF

Compatibility:

Warning

Using waitaof directly is not recommended. Use the Redis.ensure_persistence() or RedisCluster.ensure_persistence() context managers to ensure a command is synced to the AOF of the number of local hosts or replicas

Added in version 4.12.0.

async hdel(key: KeyT, fields: Parameters[StringT]) int

Deletes fields from hash key

Redis command documentation: HDEL

async hexists(key: KeyT, field: StringT) bool

Returns a boolean indicating if field exists within hash key

Redis command documentation: HEXISTS

Hint

Supports client side caching

async hget(key: KeyT, field: StringT) AnyStr | None

Returns the value of field within the hash key

Redis command documentation: HGET

Hint

Supports client side caching

async hgetall(key: KeyT) dict[AnyStr, AnyStr]

Returns a Python dict of the hash’s name/value pairs

Redis command documentation: HGETALL

Hint

Supports client side caching

async hincrby(key: KeyT, field: StringT, increment: int) int

Increments the value of field in hash key by increment

Redis command documentation: HINCRBY

async hincrbyfloat(key: KeyT, field: StringT, increment: int | float) float

Increments the value of field in hash key by floating increment

Redis command documentation: HINCRBYFLOAT

async hkeys(key: KeyT) tuple[AnyStr, ...]

Returns the list of keys within hash key

Redis command documentation: HKEYS

Hint

Supports client side caching

async hlen(key: KeyT) int

Returns the number of elements in hash key

Redis command documentation: HLEN

Hint

Supports client side caching

async hmget(key: KeyT, fields: Parameters[StringT]) Tuple[AnyStr | None, ...]

Returns values ordered identically to fields

Redis command documentation: HMGET

Hint

Supports client side caching

async hmset(key: KeyT, field_values: Mapping[StringT, ValueT]) bool

Sets key to value within hash key for each corresponding key and value from the field_items dict.

Redis command documentation: HMSET

async hrandfield(key: KeyT, *, count: int | None = None, withvalues: bool | None = None) AnyStr | tuple[AnyStr, ...] | dict[AnyStr, AnyStr] | None

Return a random field from the hash value stored at key.

Returns:

Without the additional count argument, the command returns a randomly selected field, or None when key does not exist. When the additional count argument is passed, the command returns fields, or an empty tuple when key does not exist.

If withvalues is True, the reply is a mapping of fields and their values from the hash.

Redis command documentation: HRANDFIELD

Compatibility:

async hscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, dict[AnyStr, AnyStr]]

Incrementallys return key/value slices in a hash. Also returns a cursor pointing to the scan position.

Parameters:
  • match – allows for filtering the keys by pattern

  • count – allows for hint the minimum number of returns

Redis command documentation: HSCAN

async hset(key: KeyT, field_values: Mapping[StringT, ValueT]) int

Sets field to value within hash key

Returns:

number of fields that were added

Redis command documentation: HSET

async hsetnx(key: KeyT, field: StringT, value: ValueT) bool

Sets field to value within hash key if field does not exist.

Returns:

whether the field was created

Redis command documentation: HSETNX

async hstrlen(key: KeyT, field: StringT) int

Get the length of the value of a hash field

Returns:

the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.

Redis command documentation: HSTRLEN

Hint

Supports client side caching

async hvals(key: KeyT) tuple[AnyStr, ...]

Get all the values in a hash

Returns:

list of values in the hash, or an empty list when key does not exist.

Redis command documentation: HVALS

Hint

Supports client side caching

async pfadd(key: KeyT, *elements: ValueT) bool

Adds the specified elements to the specified HyperLogLog.

Returns:

Whether atleast 1 HyperLogLog internal register was altered

Redis command documentation: PFADD

async pfcount(keys: Parameters[KeyT]) int

Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).

Returns:

The approximated number of unique elements observed via pfadd().

Redis command documentation: PFCOUNT

async pfmerge(destkey: KeyT, sourcekeys: Parameters[KeyT]) bool

Merge N different HyperLogLogs into a single one

Redis command documentation: PFMERGE

async blmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT], timeout: int | float) AnyStr | None

Pop an element from a list, push it to another list and return it; or block until one is available

Returns:

the element being popped from source and pushed to destination

Redis command documentation: BLMOVE

Compatibility:

async blmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) List[AnyStr | List[AnyStr]] | None

Pop elements from the first non empty list, or block until one is available

Returns:

  • A None when no element could be popped, and timeout is reached.

  • A two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of elements.

Redis command documentation: BLMPOP

Compatibility:

Added in version 3.0.0.

async blpop(keys: Parameters[KeyT], timeout: int | float) List[AnyStr] | None

Remove and get the first element in a list, or block until one is available

Returns:

  • None when no element could be popped and the timeout expired.

  • A list with the first element being the name of the key where an element was popped and the second element being the value of the popped element.

Redis command documentation: BLPOP

async brpop(keys: Parameters[KeyT], timeout: int | float) List[AnyStr] | None

Remove and get the last element in a list, or block until one is available

Returns:

  • None when no element could be popped and the timeout expired.

  • A list with the first element being the name of the key where an element was popped and the second element being the value of the popped element.

Redis command documentation: BRPOP

async brpoplpush(source: KeyT, destination: KeyT, timeout: int | float) AnyStr | None

Pop an element from a list, push it to another list and return it; or block until one is available

Returns:

the element being popped from source and pushed to destination.

Redis command documentation: BRPOPLPUSH

async lindex(key: KeyT, index: int) AnyStr | None

Get an element from a list by its index

Returns:

the requested element, or None when index is out of range.

Redis command documentation: LINDEX

Hint

Supports client side caching

async linsert(key: KeyT, where: Literal[PureToken.AFTER, PureToken.BEFORE], pivot: ValueT, element: ValueT) int

Inserts element in the list stored at key either before or after the reference value pivot.

Returns:

the length of the list after the insert operation, or -1 when the value pivot was not found.

Redis command documentation: LINSERT

async llen(key: KeyT) int
Returns:

the length of the list at key.

Redis command documentation: LLEN

Hint

Supports client side caching

async lmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT]) AnyStr

Pop an element from a list, push it to another list and return it

Returns:

the element being popped and pushed.

Redis command documentation: LMOVE

Compatibility:

async lmpop(keys: Parameters[KeyT], where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) List[AnyStr | List[AnyStr]] | None

Pop elements from the first non empty list

Returns:

  • A `None` when no element could be popped.

  • A two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of elements.

Redis command documentation: LMPOP

Compatibility:

Added in version 3.0.0.

async lpop(key: KeyT, count: int | None = None) AnyStr | list[AnyStr] | None

Remove and get the first count elements in a list

Returns:

the value of the first element, or None when key does not exist. If count is provided the return is a list of popped elements, or None when key does not exist.

Redis command documentation: LPOP

Compatibility:

async lpos(key: KeyT, element: ValueT, rank: int | None = None, count: int | None = None, maxlen: int | None = None) int | list[int] | None

Return the index of matching elements on a list

Returns:

The command returns the integer representing the matching element, or None if there is no match.

If the count argument is given a list of integers representing the matching elements.

Redis command documentation: LPOS

Compatibility:

Hint

Supports client side caching

async lpush(key: KeyT, elements: Parameters[ValueT]) int

Prepend one or multiple elements to a list

Returns:

the length of the list after the push operations.

Redis command documentation: LPUSH

async lpushx(key: KeyT, elements: Parameters[ValueT]) int

Prepend an element to a list, only if the list exists

Returns:

the length of the list after the push operation.

Redis command documentation: LPUSHX

async lrange(key: KeyT, start: int, stop: int) list[AnyStr]

Get a range of elements from a list

Returns:

list of elements in the specified range.

Redis command documentation: LRANGE

Hint

Supports client side caching

async lrem(key: KeyT, count: int, element: ValueT) int

Removes the first count occurrences of elements equal to element from the list stored at key.

The count argument influences the operation in the following ways:

count > 0: Remove elements equal to value moving from head to tail. count < 0: Remove elements equal to value moving from tail to head. count = 0: Remove all elements equal to value.

Returns:

the number of removed elements.

Redis command documentation: LREM

async lset(key: KeyT, index: int, element: ValueT) bool

Sets index of list key to element

Redis command documentation: LSET

async ltrim(key: KeyT, start: int, stop: int) bool

Trims the list key, removing all values not within the slice between start and stop

start and stop can be negative numbers just like Python slicing notation

Redis command documentation: LTRIM

async rpop(key: KeyT, count: int | None = None) AnyStr | list[AnyStr] | None

Remove and get the last elements in a list

Returns:

When called without the count argument the value of the last element, or None when key does not exist.

When called with the count argument list of popped elements, or None when key does not exist.

Redis command documentation: RPOP

Compatibility:

async rpoplpush(source: KeyT, destination: KeyT) AnyStr | None

Remove the last element in a list, prepend it to another list and return it

Returns:

the element being popped and pushed.

Redis command documentation: RPOPLPUSH

async rpush(key: KeyT, elements: Parameters[ValueT]) int

Append an element(s) to a list

Returns:

the length of the list after the push operation.

Redis command documentation: RPUSH

async rpushx(key: KeyT, elements: Parameters[ValueT]) int

Append a element(s) to a list, only if the list exists

Returns:

the length of the list after the push operation.

Redis command documentation: RPUSHX

async sadd(key: KeyT, members: Parameters[ValueT]) int

Add one or more members to a set

Returns:

the number of elements that were added to the set, not including all the elements already present in the set.

Redis command documentation: SADD

async scard(key: KeyT) int

Returns the number of members in the set

:return the cardinality (number of elements) of the set, or 0 if key

does not exist.

Redis command documentation: SCARD

Hint

Supports client side caching

async sdiff(keys: Parameters[KeyT]) Set[AnyStr]

Subtract multiple sets

Returns:

members of the resulting set.

Redis command documentation: SDIFF

async sdiffstore(keys: Parameters[KeyT], destination: KeyT) int

Subtract multiple sets and store the resulting set in a key

Redis command documentation: SDIFFSTORE

async sinter(keys: Parameters[KeyT]) Set[AnyStr]

Intersect multiple sets

Returns:

members of the resulting set

Redis command documentation: SINTER

async sintercard(keys: Parameters[KeyT], limit: int | None = None) int

Intersect multiple sets and return the cardinality of the result

Returns:

The number of elements in the resulting intersection.

Redis command documentation: SINTERCARD

Compatibility:

Added in version 3.0.0.

async sinterstore(keys: Parameters[KeyT], destination: KeyT) int

Intersect multiple sets and store the resulting set in a key

Returns:

the number of elements in the resulting set.

Redis command documentation: SINTERSTORE

async sismember(key: KeyT, member: ValueT) bool

Determine if a given value is a member of a set

Returns:

If the element is a member of the set. False if key does not exist.

Redis command documentation: SISMEMBER

Hint

Supports client side caching

async smembers(key: KeyT) set[AnyStr]

Returns all members of the set

Redis command documentation: SMEMBERS

Hint

Supports client side caching

async smismember(key: KeyT, members: Parameters[ValueT]) Tuple[bool, ...]

Returns the membership associated with the given elements for a set

Returns:

tuple representing the membership of the given elements, in the same order as they are requested.

Redis command documentation: SMISMEMBER

Compatibility:

Hint

Supports client side caching

async smove(source: KeyT, destination: KeyT, member: ValueT) bool

Move a member from one set to another

Redis command documentation: SMOVE

async spop(key: KeyT, count: int | None = None) AnyStr | set[AnyStr] | None

Remove and return one or multiple random members from a set

Returns:

When called without the count argument the removed member, or None when key does not exist.

When called with the count argument the removed members, or an empty array when key does not exist.

Redis command documentation: SPOP

async srandmember(key: KeyT, count: int | None = None) AnyStr | set[AnyStr] | None

Get one or multiple random members from a set

Returns:

without the additional count argument, the command returns a randomly selected element, or None when key does not exist.

When the additional count argument is passed, the command returns elements, or an empty set when key does not exist.

Redis command documentation: SRANDMEMBER

async srem(key: KeyT, members: Parameters[ValueT]) int

Remove one or more members from a set

Returns:

the number of members that were removed from the set, not including non existing members.

Redis command documentation: SREM

async sscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, set[AnyStr]]

Incrementally returns subsets of elements in a set. Also returns a cursor pointing to the scan position.

Parameters:
  • match – is for filtering the keys by pattern

  • count – is for hint the minimum number of returns

Redis command documentation: SSCAN

async sunion(keys: Parameters[KeyT]) Set[AnyStr]

Add multiple sets

Returns:

members of the resulting set.

Redis command documentation: SUNION

async sunionstore(keys: Parameters[KeyT], destination: KeyT) int

Add multiple sets and store the resulting set in a key

Returns:

the number of elements in the resulting set.

Redis command documentation: SUNIONSTORE

async bzmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) Tuple[AnyStr, Tuple[ScoredMember, ...]] | None

Remove and return members with scores in a sorted set or block until one is available

Returns:

  • A `None` when no element could be popped.

  • A tuple of (name of key, popped (member, score) pairs)

Redis command documentation: BZMPOP

Compatibility:

Added in version 3.0.0.

async bzpopmax(keys: Parameters[KeyT], timeout: int | float) Tuple[AnyStr, AnyStr, float] | None

Remove and return the member with the highest score from one or more sorted sets, or block until one is available.

Returns:

A triplet with the first element being the name of the key where a member was popped, the second element is the popped member itself, and the third element is the score of the popped element.

Redis command documentation: BZPOPMAX

async bzpopmin(keys: Parameters[KeyT], timeout: int | float) Tuple[AnyStr, AnyStr, float] | None

Remove and return the member with the lowest score from one or more sorted sets, or block until one is available

Returns:

A triplet with the first element being the name of the key where a member was popped, the second element is the popped member itself, and the third element is the score of the popped element.

Redis command documentation: BZPOPMIN

async zadd(key: KeyT, member_scores: Mapping[StringT, int | float], condition: Literal[PureToken.NX, PureToken.XX] | None = None, comparison: Literal[PureToken.GT, PureToken.LT] | None = None, change: bool | None = None, increment: bool | None = None) int | float | None

Add one or more members to a sorted set, or update its score if it already exists

Returns:

  • When used without optional arguments, the number of elements added to the sorted set (excluding score updates).

  • If the change option is specified, the number of elements that were changed (added or updated).

  • If condition is specified, the new score of member (a double precision floating point number) represented as string

  • None if the operation is aborted

Redis command documentation: ZADD

Compatibility:

async zcard(key: KeyT) int

Get the number of members in a sorted set

Returns:

the cardinality (number of elements) of the sorted set, or 0 if the key does not exist

Redis command documentation: ZCARD

async zcount(key: KeyT, min_: ValueT, max_: ValueT) int

Count the members in a sorted set with scores within the given values

Returns:

the number of elements in the specified score range.

Redis command documentation: ZCOUNT

async zdiff(keys: Parameters[KeyT], withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Subtract multiple sorted sets

Returns:

the result of the difference (optionally with their scores, in case the withscores option is given).

Redis command documentation: ZDIFF

Compatibility:

async zdiffstore(keys: Parameters[KeyT], destination: KeyT) int

Subtract multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZDIFFSTORE

Compatibility:

async zincrby(key: KeyT, member: ValueT, increment: int) float

Increment the score of a member in a sorted set

Returns:

the new score of member

Redis command documentation: ZINCRBY

async zinter(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None, withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Intersect multiple sorted sets

Returns:

the result of intersection (optionally with their scores, in case the withscores option is given).

Redis command documentation: ZINTER

Compatibility:

async zintercard(keys: Parameters[KeyT], limit: int | None = None) int

Intersect multiple sorted sets and return the cardinality of the result

Returns:

The number of elements in the resulting intersection.

Redis command documentation: ZINTERCARD

Compatibility:

Added in version 3.0.0.

async zinterstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None) int

Intersect multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZINTERSTORE

async zlexcount(key: KeyT, min_: ValueT, max_: ValueT) int

Count the number of members in a sorted set between a given lexicographical range

Returns:

the number of elements in the specified score range.

Redis command documentation: ZLEXCOUNT

Hint

Supports client side caching

async zmpop(keys: Parameters[KeyT], where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) Tuple[AnyStr, Tuple[ScoredMember, ...]] | None

Remove and return members with scores in a sorted set

Returns:

A tuple of (name of key, popped (member, score) pairs)

Redis command documentation: ZMPOP

Compatibility:

Added in version 3.0.0.

async zmscore(key: KeyT, members: Parameters[ValueT]) Tuple[float | None, ...]

Get the score associated with the given members in a sorted set

Returns:

scores or None associated with the specified members values (a double precision floating point number), represented as strings

Redis command documentation: ZMSCORE

Compatibility:

Hint

Supports client side caching

async zpopmax(key: KeyT, count: int | None = None) ScoredMember | tuple[ScoredMember, ...] | None

Remove and return members with the highest scores in a sorted set

Returns:

popped elements and scores.

Redis command documentation: ZPOPMAX

async zpopmin(key: KeyT, count: int | None = None) ScoredMember | tuple[ScoredMember, ...] | None

Remove and return members with the lowest scores in a sorted set

Returns:

popped elements and scores.

Redis command documentation: ZPOPMIN

async zrandmember(key: KeyT, count: int | None = None, withscores: bool | None = None) AnyStr | list[AnyStr] | tuple[ScoredMember, ...] | None

Get one or multiple random elements from a sorted set

Returns:

without count, the command returns a randomly selected element, or None when key does not exist.

If count is passed the command returns the elements, or an empty tuple when key does not exist.

If withscores argument is used, the return is a list elements and their scores from the sorted set.

Redis command documentation: ZRANDMEMBER

Compatibility:

async zrange(key: KeyT, min_: int | ValueT, max_: int | ValueT, sortby: Literal[PureToken.BYSCORE, PureToken.BYLEX] | None = None, rev: bool | None = None, offset: int | None = None, count: int | None = None, withscores: bool | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set

Returns:

elements in the specified range (optionally with their scores, in case withscores is given).

Redis command documentation: ZRANGE

Compatibility:

Hint

Supports client side caching

async zrangebylex(key: KeyT, min_: ValueT, max_: ValueT, offset: int | None = None, count: int | None = None) tuple[AnyStr, ...]

Return a range of members in a sorted set, by lexicographical range

Returns:

elements in the specified score range.

Redis command documentation: ZRANGEBYLEX

Hint

Supports client side caching

async zrangebyscore(key: KeyT, min_: int | float, max_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by score

Returns:

elements in the specified score range (optionally with their scores).

Redis command documentation: ZRANGEBYSCORE

Hint

Supports client side caching

async zrangestore(dst: KeyT, src: KeyT, min_: int | ValueT, max_: int | ValueT, sortby: Literal[PureToken.BYSCORE, PureToken.BYLEX] | None = None, rev: bool | None = None, offset: int | None = None, count: int | None = None) int

Store a range of members from sorted set into another key

Returns:

the number of elements in the resulting sorted set

Redis command documentation: ZRANGESTORE

Compatibility:

async zrank(key: KeyT, member: ValueT, withscore: bool | None = None) int | tuple[int, float] | None

Determine the index of a member in a sorted set

Returns:

the rank of member. If withscore is True the return is a tuple of (rank, score).

Redis command documentation: ZRANK

Compatibility:

Hint

Supports client side caching

async zrem(key: KeyT, members: Parameters[ValueT]) int

Remove one or more members from a sorted set

Returns:

The number of members removed from the sorted set, not including non existing members.

Redis command documentation: ZREM

async zremrangebylex(key: KeyT, min_: ValueT, max_: ValueT) int

Remove all members in a sorted set between the given lexicographical range

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYLEX

async zremrangebyrank(key: KeyT, start: int, stop: int) int

Remove all members in a sorted set within the given indexes

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYRANK

async zremrangebyscore(key: KeyT, min_: int | float, max_: int | float) int

Remove all members in a sorted set within the given scores

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYSCORE

async zrevrange(key: KeyT, start: int, stop: int, withscores: bool | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by index, with scores ordered from high to low

Returns:

elements in the specified range (optionally with their scores).

Redis command documentation: ZREVRANGE

Hint

Supports client side caching

async zrevrangebylex(key: KeyT, max_: ValueT, min_: ValueT, offset: int | None = None, count: int | None = None) tuple[AnyStr, ...]

Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.

Returns:

elements in the specified score range

Redis command documentation: ZREVRANGEBYLEX

Hint

Supports client side caching

async zrevrangebyscore(key: KeyT, max_: int | float, min_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by score, with scores ordered from high to low

Returns:

elements in the specified score range (optionally with their scores)

Redis command documentation: ZREVRANGEBYSCORE

Hint

Supports client side caching

async zrevrank(key: KeyT, member: ValueT, withscore: bool | None = None) int | tuple[int, float] | None

Determine the index of a member in a sorted set, with scores ordered from high to low

Returns:

the rank of member. If withscore is True the return is a tuple of (rank, score).

Redis command documentation: ZREVRANK

Compatibility:

Hint

Supports client side caching

async zscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, tuple[ScoredMember, ...]]

Incrementally iterate sorted sets elements and associated scores

Redis command documentation: ZSCAN

async zscore(key: KeyT, member: ValueT) float | None

Get the score associated with the given member in a sorted set

Returns:

the score of member (a double precision floating point number), represented as string or None if the member doesn’t exist.

Redis command documentation: ZSCORE

Hint

Supports client side caching

async zunion(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None, withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Add multiple sorted sets

Returns:

the result of union (optionally with their scores, in case withscores is given).

Redis command documentation: ZUNION

Compatibility:

async zunionstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None) int

Add multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZUNIONSTORE

async geoadd(key: KeyT, longitude_latitude_members: Parameters[Tuple[int | float, int | float, ValueT]], condition: Literal[PureToken.NX, PureToken.XX] | None = None, change: bool | None = None) int

Add one or more geospatial items in the geospatial index represented using a sorted set

Returns:

Number of elements added. If change is True the return is the number of elements that were changed.

Redis command documentation: GEOADD

Compatibility:

async geodist(key: KeyT, member1: StringT, member2: StringT, unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None) float | None

Returns the distance between two members of a geospatial index

Returns:

Distance in the unit specified by unit

Redis command documentation: GEODIST

async geohash(key: KeyT, members: Parameters[ValueT]) Tuple[AnyStr, ...]

Returns members of a geospatial index as standard geohash strings

Redis command documentation: GEOHASH

async geopos(key: KeyT, members: Parameters[ValueT]) Tuple[GeoCoordinates | None, ...]

Returns longitude and latitude of members of a geospatial index

Returns:

pairs of longitude/latitudes. Missing members are represented by None entries.

Redis command documentation: GEOPOS

async georadius(key: KeyT, longitude: int | float, latitude: int | float, radius: int | float, unit: Literal[PureToken.FT, PureToken.KM, PureToken.M, PureToken.MI], *, withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None, count: int | None = None, any_: bool | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, store: KeyT | None = None, storedist: KeyT | None = None) int | tuple[AnyStr | GeoSearchResult, ...]

Query a geospatial index to fetch members within the borders of the area specified with center location at longitude and latitude and the maximum distance from the center (radius).

Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

  • If a key for store or storedist is provided, the return is the count of places stored.

Redis command documentation: GEORADIUS

Compatibility:

async georadiusbymember(key: KeyT, member: ValueT, radius: int | float, unit: Literal[PureToken.FT, PureToken.KM, PureToken.M, PureToken.MI], withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None, count: int | None = None, any_: bool | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, store: KeyT | None = None, storedist: KeyT | None = None) int | tuple[AnyStr | GeoSearchResult, ...]

This command is exactly like georadius() with the sole difference that instead of searching from a coordinate, it searches from a member already existing in the index.

Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

  • If a key for store or storedist is provided, the return is the count of places stored.

Redis command documentation: GEORADIUSBYMEMBER

async geosearch(key: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, width: int | float | None = None, height: int | float | None = None, box_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, count: int | None = None, any_: bool | None = None, withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None) int | tuple[AnyStr | GeoSearchResult, ...]
Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

Redis command documentation: GEOSEARCH

Compatibility:

async geosearchstore(destination: KeyT, source: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, width: int | float | None = None, height: int | float | None = None, box_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, count: int | None = None, any_: bool | None = None, storedist: bool | None = None) int
Returns:

The number of elements stored in the resulting set

Redis command documentation: GEOSEARCHSTORE

Compatibility:

async eval(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Execute the Lua script with the key names and argument values in keys and args.

Returns:

The result of the script as redis returns it

Redis command documentation: EVAL

async eval_ro(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of eval() that cannot execute commands that modify data.

Returns:

The result of the script as redis returns it

Redis command documentation: EVAL_RO

Compatibility:

Added in version 3.0.0.

async evalsha(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Execute the Lua script cached by it’s sha ref with the key names and argument values in keys and args. Evaluate a script from the server’s cache by its sha1 digest.

Returns:

The result of the script as redis returns it

Redis command documentation: EVALSHA

async evalsha_ro(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of evalsha() that cannot execute commands that modify data.

Returns:

The result of the script as redis returns it

Redis command documentation: EVALSHA_RO

Compatibility:

Added in version 3.0.0.

async fcall(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Invoke a function

Redis command documentation: FCALL

Compatibility:

Added in version 3.1.0.

async fcall_ro(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of fcall()

Redis command documentation: FCALL_RO

Compatibility:

Added in version 3.1.0.

async function_delete(library_name: StringT) bool

Delete a library and all its functions.

Redis command documentation: FUNCTION DELETE

Compatibility:

Added in version 3.1.0.

async function_dump() bytes

Dump all functions into a serialized binary payload

Redis command documentation: FUNCTION DUMP

Compatibility:

Added in version 3.1.0.

async function_flush(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Delete all functions

Redis command documentation: FUNCTION FLUSH

Compatibility:

Added in version 3.1.0.

async function_kill() bool

Kill the function currently in execution.

Redis command documentation: FUNCTION KILL

Compatibility:

Added in version 3.1.0.

async function_list(libraryname: StringT | None = None, withcode: bool | None = None) Mapping[AnyStr, LibraryDefinition]

List information about the functions registered under libraryname

Redis command documentation: FUNCTION LIST

Compatibility:

Added in version 3.1.0.

async function_load(function_code: StringT, replace: bool | None = None) AnyStr

Load a library of functions.

Redis command documentation: FUNCTION LOAD

Compatibility:

Added in version 3.1.0.

async function_restore(serialized_value: bytes, policy: Literal[PureToken.FLUSH, PureToken.APPEND, PureToken.REPLACE] | None = None) bool

Restore all the functions on the given payload

Redis command documentation: FUNCTION RESTORE

Compatibility:

Added in version 3.1.0.

async function_stats() dict[AnyStr, AnyStr | dict[AnyStr, dict[AnyStr, ResponsePrimitive]]]

Return information about the function currently running

Redis command documentation: FUNCTION STATS

Compatibility:

Added in version 3.1.0.

async script_debug(mode: Literal[PureToken.NO, PureToken.SYNC, PureToken.YES]) bool

Set the debug mode for executed scripts

Raises:

NotImplementedError

Redis command documentation: SCRIPT DEBUG

Added in version 3.0.0.

async script_exists(sha1s: Parameters[StringT]) Tuple[bool, ...]

Check if a script exists in the script cache by specifying the SHAs of each script as sha1s.

Returns:

tuple of boolean values indicating if each script exists in the cache.

Redis command documentation: SCRIPT EXISTS

async script_flush(sync_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Flushes all scripts from the script cache

Redis command documentation: SCRIPT FLUSH

Compatibility:

async script_kill() bool

Kills the currently executing Lua script

Redis command documentation: SCRIPT KILL

async script_load(script: StringT) AnyStr

Loads a Lua script into the script cache.

Returns:

The SHA1 digest of the script added into the script cache

Redis command documentation: SCRIPT LOAD

async publish(channel: StringT, message: ValueT) int

Publish message on channel.

Returns:

the number of subscribers the message was delivered to.

Redis command documentation: PUBLISH

async pubsub_channels(pattern: StringT | None = None) set[AnyStr]

Return channels that have at least one subscriber

Redis command documentation: PUBSUB CHANNELS

async pubsub_numpat() int

Get the count of unique patterns pattern subscriptions

Returns:

the number of patterns all the clients are subscribed to.

Redis command documentation: PUBSUB NUMPAT

async pubsub_numsub(*channels: StringT) dict[AnyStr, int]

Get the count of subscribers for channels

Returns:

Mapping of channels to number of subscribers per channel

Redis command documentation: PUBSUB NUMSUB

async pubsub_shardchannels(pattern: StringT | None = None) set[AnyStr]

Return shard channels that have at least one subscriber

Redis command documentation: PUBSUB SHARDCHANNELS

Compatibility:

Added in version 3.6.0.

async pubsub_shardnumsub(*channels: StringT) dict[AnyStr, int]

Get the count of subscribers for shard channels

Returns:

Ordered mapping of shard channels to number of subscribers per channel

Redis command documentation: PUBSUB SHARDNUMSUB

async spublish(channel: StringT, message: ValueT) int

Publish message on shard channel.

Returns:

the number of shard subscribers the message was delivered to.

Note

The number only represents subscribers listening to the exact node the message was published to, which means that if a subscriber is listening on a replica node, it will not be included in the count.

Redis command documentation: SPUBLISH

Compatibility:

Added in version 3.6.0.

async xack(key: KeyT, group: StringT, identifiers: Parameters[ValueT]) int

Marks a pending message as correctly processed, effectively removing it from the pending entries list of the consumer group.

Returns:

number of messages successfully acknowledged, that is, the IDs we were actually able to resolve in the PEL.

Redis command documentation: XACK

async xadd(key: KeyT, field_values: Mapping[StringT, ValueT], identifier: ValueT | None = None, nomkstream: bool | None = None, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID] | None = None, threshold: int | None = None, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None) AnyStr | None

Appends a new entry to a stream

Returns:

The identifier of the added entry. The identifier is the one auto-generated if * is passed as identifier, otherwise the it justs returns the same identifier specified

Returns None when used with nomkstream and the key doesn’t exist.

Redis command documentation: XADD

Compatibility:

async xautoclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | timedelta, start: ValueT, count: int | None = None, justid: bool | None = None) tuple[AnyStr, tuple[AnyStr, ...]] | tuple[AnyStr, tuple[StreamEntry, ...], tuple[AnyStr, ...]]

Changes (or acquires) ownership of messages in a consumer group, as if the messages were delivered to the specified consumer.

Returns:

A dictionary with keys as stream identifiers and values containing all the successfully claimed messages in the same format as xrange()

Redis command documentation: XAUTOCLAIM

Compatibility:

Added in version 3.0.0.

async xclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | datetime.timedelta, identifiers: Parameters[ValueT], idle: int | datetime.timedelta | None = None, time: int | datetime.datetime | None = None, retrycount: int | None = None, force: bool | None = None, justid: bool | None = None, lastid: ValueT | None = None) Tuple[AnyStr, ...] | Tuple[StreamEntry, ...]

Changes (or acquires) ownership of a message in a consumer group, as if the message was delivered to the specified consumer.

Redis command documentation: XCLAIM

async xdel(key: KeyT, identifiers: Parameters[ValueT]) int

Redis command documentation: XDEL

async xgroup_create(key: KeyT, groupname: StringT, identifier: ValueT | None = None, mkstream: bool | None = None, entriesread: int | None = None) bool

Create a consumer group.

Redis command documentation: XGROUP CREATE

Compatibility:

async xgroup_createconsumer(key: KeyT, groupname: StringT, consumername: StringT) bool

Create a consumer in a consumer group.

Returns:

whether the consumer was created

Redis command documentation: XGROUP CREATECONSUMER

Compatibility:

Added in version 3.0.0.

async xgroup_delconsumer(key: KeyT, groupname: StringT, consumername: StringT) int

Delete a consumer from a consumer group.

Returns:

The number of pending messages that the consumer had before it was deleted

Redis command documentation: XGROUP DELCONSUMER

Added in version 3.0.0.

async xgroup_destroy(key: KeyT, groupname: StringT) int

Destroy a consumer group.

Returns:

The number of destroyed consumer groups

Redis command documentation: XGROUP DESTROY

async xgroup_setid(key: KeyT, groupname: StringT, identifier: ValueT | None = None, entriesread: int | None = None) bool

Set a consumer group to an arbitrary last delivered ID value.

Redis command documentation: XGROUP SETID

Compatibility:

Added in version 3.0.0.

async xinfo_consumers(key: KeyT, groupname: StringT) tuple[dict[AnyStr, AnyStr], ...]

Get list of all consumers that belong to groupname of the stream stored at key

Redis command documentation: XINFO CONSUMERS

async xinfo_groups(key: KeyT) tuple[dict[AnyStr, AnyStr], ...]

Get list of all consumers groups of the stream stored at key

Redis command documentation: XINFO GROUPS

async xinfo_stream(key: KeyT, full: bool | None = None, count: int | None = None) StreamInfo

Get information about the stream stored at key

Parameters:

Redis command documentation: XINFO STREAM

async xlen(key: KeyT) int

Redis command documentation: XLEN

async xpending(key: KeyT, group: StringT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None, idle: int | None = None, consumer: StringT | None = None) tuple[StreamPendingExt, ...] | StreamPending

Return information and entries from a stream consumer group pending entries list, that are messages fetched but never acknowledged.

Redis command documentation: XPENDING

Compatibility:

async xrange(key: KeyT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None) tuple[StreamEntry, ...]

Return a range of elements in a stream, with IDs matching the specified IDs interval

Redis command documentation: XRANGE

async xread(streams: Mapping[ValueT, ValueT], count: int | None = None, block: int | timedelta | None = None) dict[AnyStr, tuple[StreamEntry, ...]] | None

Return never seen elements in multiple streams, with IDs greater than the ones reported by the caller for each stream. Can block.

Returns:

Mapping of streams to stream entries. Field and values are guaranteed to be reported in the same order they were added by xadd().

When block is used, on timeout None is returned.

Redis command documentation: XREAD

async xreadgroup(group: StringT, consumer: StringT, streams: Mapping[ValueT, ValueT], count: int | None = None, block: int | timedelta | None = None, noack: bool | None = None) dict[AnyStr, tuple[StreamEntry, ...]] | None

Redis command documentation: XREADGROUP

async xrevrange(key: KeyT, end: ValueT | None = None, start: ValueT | None = None, count: int | None = None) tuple[StreamEntry, ...]

Return a range of elements in a stream, with IDs matching the specified IDs interval, in reverse order (from greater to smaller IDs) compared to XRANGE

Redis command documentation: XREVRANGE

async xtrim(key: KeyT, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID], threshold: int, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None) int

Redis command documentation: XTRIM

Compatibility:

async acl_cat(categoryname: StringT | None = None) tuple[AnyStr, ...]

List the ACL categories or the commands inside a category

Returns:

a list of ACL categories or a list of commands inside a given category. The command may return an error if an invalid category name is given as argument.

Redis command documentation: ACL CAT

Compatibility:

Added in version 3.0.0.

async acl_deluser(usernames: Parameters[StringT]) int

Remove the specified ACL users and the associated rules

Returns:

The number of users that were deleted. This number will not always match the number of arguments since certain users may not exist.

Redis command documentation: ACL DELUSER

Compatibility:

Added in version 3.0.0.

async acl_dryrun(username: StringT, command: StringT, *args: ValueT) bool

Returns whether the user can execute the given command without executing the command.

Redis command documentation: ACL DRYRUN

Compatibility:

Added in version 3.0.0.

async acl_genpass(bits: int | None = None) AnyStr

Generate a pseudorandom secure password to use for ACL users

Returns:

by default 64 bytes string representing 256 bits of pseudorandom data. Otherwise if an argument if needed, the output string length is the number of specified bits (rounded to the next multiple of 4) divided by 4.

Redis command documentation: ACL GENPASS

Compatibility:

Added in version 3.0.0.

async acl_getuser(username: StringT) dict[AnyStr, list[AnyStr] | set[AnyStr]]

Get the rules for a specific ACL user

Redis command documentation: ACL GETUSER

Compatibility:

Added in version 3.0.0.

async acl_list() tuple[AnyStr, ...]

List the current ACL rules in ACL config file format

Redis command documentation: ACL LIST

Compatibility:

Added in version 3.0.0.

async acl_load() bool

Reload the ACLs from the configured ACL file

Returns:

True if successful. The command may fail with an error for several reasons:

  • if the file is not readable

  • if there is an error inside the file, and in such case the error will be reported to the user in the error.

  • Finally the command will fail if the server is not configured to use an external ACL file.

Redis command documentation: ACL LOAD

Compatibility:

Added in version 3.0.0.

async acl_log(count: int | None = None, reset: bool | None = None) bool | tuple[dict[AnyStr, ResponsePrimitive] | None, ...]

List latest events denied because of ACLs in place

Returns:

When called to show security events a list of ACL security events. When called with RESET True if the security log was cleared.

Redis command documentation: ACL LOG

Compatibility:

Added in version 3.0.0.

async acl_save() bool

Save the current ACL rules in the configured ACL file

Returns:

True if successful. The command may fail with an error for several reasons: - if the file cannot be written, or - if the server is not configured to use an external ACL file.

Redis command documentation: ACL SAVE

Compatibility:

Added in version 3.0.0.

async acl_setuser(username: StringT, *rules: StringT) bool

Modify or create the rules for a specific ACL user

Returns:

True if successful. If the rules contain errors, the error is returned.

Redis command documentation: ACL SETUSER

Compatibility:

Added in version 3.0.0.

async acl_users() tuple[AnyStr, ...]

List the username of all the configured ACL rules

Redis command documentation: ACL USERS

Compatibility:

Added in version 3.0.0.

async acl_whoami() AnyStr

Return the name of the user associated to the current connection

Returns:

the username of the current connection.

Redis command documentation: ACL WHOAMI

Compatibility:

Added in version 3.0.0.

async command() dict[str, Command]

Get Redis command details

Returns:

Mapping of command details. Commands are returned in random order.

Redis command documentation: COMMAND

Added in version 3.0.0.

async command_count() int

Get total number of Redis commands

Returns:

number of commands returned by COMMAND

Redis command documentation: COMMAND COUNT

Added in version 3.0.0.

async command_docs(*command_names: StringT) dict[AnyStr, dict[AnyStr, ResponseType]]

Mapping of commands to a dictionary containing it’s documentation

Redis command documentation: COMMAND DOCS

Compatibility:

Added in version 3.1.0.

async command_getkeys(command: StringT, arguments: Parameters[ValueT]) Tuple[AnyStr, ...]

Extract keys given a full Redis command

Returns:

Keys from your command.

Redis command documentation: COMMAND GETKEYS

Added in version 3.0.0.

async command_getkeysandflags(command: StringT, arguments: Parameters[ValueT]) Dict[AnyStr, Set[AnyStr]]

Extract keys from a full Redis command and their usage flags.

Returns:

Mapping of keys from your command to flags

Redis command documentation: COMMAND GETKEYSANDFLAGS

Compatibility:

Added in version 3.1.0.

async command_info(*command_names: StringT) dict[str, Command]

Get specific Redis command details, or all when no argument is given.

Returns:

mapping of command details.

Redis command documentation: COMMAND INFO

Added in version 3.0.0.

async command_list(module: StringT | None = None, aclcat: StringT | None = None, pattern: StringT | None = None) set[AnyStr]

Get an array of Redis command names

Redis command documentation: COMMAND LIST

Compatibility:

Added in version 3.1.0.

async config_get(parameters: Parameters[StringT]) Dict[AnyStr, AnyStr]

Get the values of configuration parameters

Redis command documentation: CONFIG GET

async config_resetstat() bool

Resets runtime statistics

Redis command documentation: CONFIG RESETSTAT

async config_rewrite() bool

Rewrites config file with the minimal change to reflect running config

Redis command documentation: CONFIG REWRITE

async config_set(parameter_values: Mapping[StringT, ValueT]) bool

Sets configuration parameters to the given values

Redis command documentation: CONFIG SET

async dbsize() int

Returns the number of keys in the current database

Redis command documentation: DBSIZE

async debug_object(key: KeyT) dict[str, str | int]

Returns version specific meta information about a given key

Redis command documentation: DEBUG OBJECT

async failover(host: StringT | None = None, port: int | None = None, force: bool | None = None, abort: bool | None = None, timeout: int | timedelta | None = None) bool

Start a coordinated failover between this server and one of its replicas.

Returns:

True if the command was accepted and a coordinated failover is in progress.

Redis command documentation: FAILOVER

Compatibility:

Added in version 3.0.0.

async flushall(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Deletes all keys in all databases on the current host

Redis command documentation: FLUSHALL

async flushdb(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Deletes all keys in the current database

Redis command documentation: FLUSHDB

async info(*sections: StringT) dict[str, ResponseType]

Get information and statistics about the server

The sections option can be used to select a specific section(s) of information.

Redis command documentation: INFO

async lastsave() datetime

Get the time of the last successful save to disk

Redis command documentation: LASTSAVE

async latency_doctor() AnyStr

Return a human readable latency analysis report.

Redis command documentation: LATENCY DOCTOR

Added in version 3.0.0.

async latency_graph(event: StringT) AnyStr

Return a latency graph for the event.

Redis command documentation: LATENCY GRAPH

Added in version 3.0.0.

async latency_histogram(*commands: StringT) dict[AnyStr, dict[AnyStr, ValueT]]

Return the cumulative distribution of latencies of a subset of commands or all.

Redis command documentation: LATENCY HISTOGRAM

Compatibility:

Added in version 3.2.0.

async latency_history(event: StringT) tuple[list[int], ...]

Return timestamp-latency samples for the event.

Returns:

The command returns a tuple where each element is a tuple representing the timestamp and the latency of the event.

Redis command documentation: LATENCY HISTORY

Added in version 3.0.0.

async latency_latest() dict[AnyStr, tuple[int, int, int]]

Return the latest latency samples for all events.

Returns:

Mapping of event name to (timestamp, latest, all-time) triplet

Redis command documentation: LATENCY LATEST

Added in version 3.0.0.

async latency_reset(*events: StringT) int

Reset latency data for one or more events.

Returns:

the number of event time series that were reset.

Redis command documentation: LATENCY RESET

Added in version 3.0.0.

async lolwut(version: int | None = None) AnyStr

Get the Redis version and a piece of generative computer art

Redis command documentation: LOLWUT

async memory_doctor() AnyStr

Outputs memory problems report

Redis command documentation: MEMORY DOCTOR

Added in version 3.0.0.

async memory_malloc_stats() AnyStr

Show allocator internal stats :return: the memory allocator’s internal statistics report

Redis command documentation: MEMORY MALLOC-STATS

Added in version 3.0.0.

async memory_purge() bool

Ask the allocator to release memory

Redis command documentation: MEMORY PURGE

Added in version 3.0.0.

async memory_stats() dict[AnyStr, ValueT]

Show memory usage details :return: mapping of memory usage metrics and their values

Redis command documentation: MEMORY STATS

Added in version 3.0.0.

async memory_usage(key: KeyT, *, samples: int | None = None) int | None

Estimate the memory usage of a key

Returns:

the memory usage in bytes, or None when the key does not exist.

Redis command documentation: MEMORY USAGE

Added in version 3.0.0.

async module_list() tuple[dict[AnyStr, ResponsePrimitive], ...]

List all modules loaded by the server

Returns:

The loaded modules with each element represents a module containing a mapping with name and ver

Redis command documentation: MODULE LIST

Added in version 3.2.0.

async module_load(path: StringT, *args: str | bytes | int | float) bool

Load a module

Redis command documentation: MODULE LOAD

Added in version 3.2.0.

async module_loadex(path: StringT, configs: Dict[StringT, ValueT] | None = None, args: Parameters[ValueT] | None = None) bool

Loads a module from a dynamic library at runtime with configuration directives.

Redis command documentation: MODULE LOADEX

Compatibility:

Added in version 3.4.0.

async module_unload(name: StringT) bool

Unload a module

Redis command documentation: MODULE UNLOAD

Added in version 3.2.0.

async replicaof(host: StringT | None = None, port: int | None = None) bool

Make the server a replica of another instance, or promote it as master.

Redis command documentation: REPLICAOF

Added in version 3.0.0.

async role() RoleInfo

Provides information on the role of a Redis instance in the context of replication, by returning if the instance is currently a master, slave, or sentinel. The command also returns additional information about the state of the replication (if the role is master or slave) or the list of monitored master names (if the role is sentinel).

Redis command documentation: ROLE

async save() bool

Tells the Redis server to save its data to disk, blocking until the save is complete

Redis command documentation: SAVE

async shutdown(nosave_save: Literal[PureToken.NOSAVE, PureToken.SAVE] | None = None, *, now: bool | None = None, force: bool | None = None, abort: bool | None = None) bool

Stops Redis server

Redis command documentation: SHUTDOWN

Compatibility:

async slaveof(host: StringT | None = None, port: int | None = None) bool

Sets the server to be a replicated slave of the instance identified by the host and port. If called without arguments, the instance is promoted to a master instead.

Redis command documentation: SLAVEOF

async slowlog_get(count: int | None = None) tuple[SlowLogInfo, ...]

Gets the entries from the slowlog. If count is specified, get the most recent count items.

Redis command documentation: SLOWLOG GET

async slowlog_len() int

Gets the number of items in the slowlog

Redis command documentation: SLOWLOG LEN

async slowlog_reset() bool

Removes all items in the slowlog

Redis command documentation: SLOWLOG RESET

async swapdb(index1: int, index2: int) bool

Swaps two Redis databases

Redis command documentation: SWAPDB

Added in version 3.0.0.

async time() datetime

Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).

Redis command documentation: TIME

async asking() bool

Sent by cluster clients after an -ASK redirect

Redis command documentation: ASKING

Added in version 3.0.0.

async cluster_addslots(slots: Parameters[int]) bool

Assign new hash slots to receiving node

Redis command documentation: CLUSTER ADDSLOTS

async cluster_addslotsrange(slots: Parameters[Tuple[int, int]]) bool

Assign new hash slots to receiving node

Redis command documentation: CLUSTER ADDSLOTSRANGE

Compatibility:

Added in version 3.1.1.

async cluster_bumpepoch() AnyStr

Advance the cluster config epoch

Returns:

BUMPED if the epoch was incremented, or STILL if the node already has the greatest config epoch in the cluster.

Redis command documentation: CLUSTER BUMPEPOCH

Added in version 3.0.0.

async cluster_count_failure_reports(node_id: StringT) int

Return the number of failure reports active for a given node

Redis command documentation: CLUSTER COUNT-FAILURE-REPORTS

async cluster_countkeysinslot(slot: int) int

Return the number of local keys in the specified hash slot

Redis command documentation: CLUSTER COUNTKEYSINSLOT

async cluster_delslots(slots: Parameters[int]) bool

Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there

Redis command documentation: CLUSTER DELSLOTS

async cluster_delslotsrange(slots: Parameters[Tuple[int, int]]) bool

Set hash slots as unbound in receiving node

Redis command documentation: CLUSTER DELSLOTSRANGE

Compatibility:

Added in version 3.1.1.

async cluster_failover(options: Literal[PureToken.FORCE, PureToken.TAKEOVER] | None = None) bool

Forces a replica to perform a manual failover of its master.

Redis command documentation: CLUSTER FAILOVER

async cluster_flushslots() bool

Delete a node’s own slots information

Redis command documentation: CLUSTER FLUSHSLOTS

Added in version 3.0.0.

async cluster_forget(node_id: StringT) bool

remove a node via its node ID from the set of known nodes of the Redis Cluster node receiving the command

Redis command documentation: CLUSTER FORGET

async cluster_getkeysinslot(slot: int, count: int) tuple[AnyStr, ...]

Return local key names in the specified hash slot

Returns:

count key names

Redis command documentation: CLUSTER GETKEYSINSLOT

Added in version 3.0.0.

async cluster_info() dict[str, str]

Provides info about Redis Cluster node state

Redis command documentation: CLUSTER INFO

async cluster_keyslot(key: KeyT) int

Returns the hash slot of the specified key

Redis command documentation: CLUSTER KEYSLOT

Returns a list of all TCP links to and from peer nodes in cluster

Returns:

A map of maps where each map contains various attributes and their values of a cluster link.

Redis command documentation: CLUSTER LINKS

Compatibility:

Added in version 3.1.1.

async cluster_meet(ip: StringT, port: int, cluster_bus_port: int | None = None) bool

Force a node cluster to handshake with another node.

Redis command documentation: CLUSTER MEET

async cluster_myid() AnyStr

Return the node id

Redis command documentation: CLUSTER MYID

Added in version 3.1.1.

async cluster_nodes() list[ClusterNodeDetail]

Get Cluster config for the node

Redis command documentation: CLUSTER NODES

async cluster_replicas(node_id: StringT) list[ClusterNodeDetail]

List replica nodes of the specified master node

Redis command documentation: CLUSTER REPLICAS

async cluster_replicate(node_id: StringT) bool

Reconfigure a node as a replica of the specified master node

Redis command documentation: CLUSTER REPLICATE

async cluster_reset(hard_soft: Literal[PureToken.HARD, PureToken.SOFT] | None = None) bool

Reset a Redis Cluster node

Redis command documentation: CLUSTER RESET

async cluster_saveconfig() bool

Forces the node to save cluster state on disk

Redis command documentation: CLUSTER SAVECONFIG

async cluster_set_config_epoch(config_epoch: int) bool

Set the configuration epoch in a new node

Redis command documentation: CLUSTER SET-CONFIG-EPOCH

async cluster_setslot(slot: int, *, importing: StringT | None = None, migrating: StringT | None = None, node: StringT | None = None, stable: bool | None = None) bool

Bind a hash slot to a specific node

Redis command documentation: CLUSTER SETSLOT

async cluster_shards() list[dict[AnyStr, list[ValueT] | Mapping[AnyStr, ValueT]]]

Get mapping of cluster slots to nodes

Redis command documentation: CLUSTER SHARDS

Compatibility:

Added in version 3.2.0.

async cluster_slaves(node_id: StringT) list[ClusterNodeDetail]

List replica nodes of the specified master node

Redis command documentation: CLUSTER SLAVES

async cluster_slots() dict[tuple[int, int], tuple[ClusterNode, ...]]

Get mapping of Cluster slot to nodes

Redis command documentation: CLUSTER SLOTS

async readonly() bool

Enables read queries for a connection to a cluster replica node

Redis command documentation: READONLY

Added in version 3.2.0.

async readwrite() bool

Disables read queries for a connection to a cluster replica node

Redis command documentation: READWRITE

Added in version 3.2.0.

async auth(password: StringT, username: StringT | None = None) bool

Authenticate to the server

Redis command documentation: AUTH

Compatibility:

Warning

Using auth directly is not recommended. Use the Redis.username and Redis.password arguments when initializing the client to ensure that all connections originating from this client are authenticated before being made available.

Added in version 3.0.0.

async bgrewriteaof() bool

Tell the Redis server to rewrite the AOF file from data in memory

Redis command documentation: BGREWRITEAOF

async bgsave(schedule: bool | None = None) bool

Tells the Redis server to save its data to disk. Unlike save(), this method is asynchronous and returns immediately.

Redis command documentation: BGSAVE

async client_caching(mode: Literal[PureToken.NO, PureToken.YES]) bool

Instruct the server about tracking or not keys in the next request

Redis command documentation: CLIENT CACHING

Compatibility:

Added in version 3.0.0.

async client_getname() AnyStr | None

Returns the current connection name

Returns:

The connection name, or None if no name is set.

Redis command documentation: CLIENT GETNAME

async client_getredir() int

Get tracking notifications redirection client ID if any

Returns:

the ID of the client we are redirecting the notifications to. The command returns -1 if client tracking is not enabled, or 0 if client tracking is enabled but we are not redirecting the notifications to any client.

Redis command documentation: CLIENT GETREDIR

Compatibility:

Added in version 3.0.0.

async client_id() int

Returns the client ID for the current connection

Returns:

The id of the client.

Redis command documentation: CLIENT ID

Added in version 3.0.0.

async client_info() ClientInfo

Returns information about the current client connection.

Redis command documentation: CLIENT INFO

Compatibility:

Added in version 3.0.0.

async client_kill(ip_port: StringT | None = None, identifier: int | None = None, type_: Literal[PureToken.NORMAL, PureToken.MASTER, PureToken.SLAVE, PureToken.REPLICA, PureToken.PUBSUB] | None = None, user: StringT | None = None, addr: StringT | None = None, laddr: StringT | None = None, skipme: bool | None = None) int | bool

Disconnects the client at ip_port

Returns:

True if the connection exists and has been closed or the number of clients killed.

Redis command documentation: CLIENT KILL

Compatibility:

async client_list(type_: Literal[PureToken.MASTER, PureToken.NORMAL, PureToken.PUBSUB, PureToken.REPLICA] | None = None, identifiers: Parameters[int] | None = None) Tuple[ClientInfo, ...]

Get client connections

Returns:

a tuple of dictionaries containing client fields

Redis command documentation: CLIENT LIST

Compatibility:

async client_no_evict(enabled: Literal[PureToken.ON, PureToken.OFF]) bool

Set client eviction mode for the current connection

Redis command documentation: CLIENT NO-EVICT

Compatibility:

Warning

Using client_no_evict directly is not recommended. Use Redis.noevict argument when initializing the client to ensure that all connections originating from this client use the desired mode

Added in version 3.2.0.

async client_no_touch(enabled: Literal[PureToken.OFF, PureToken.ON]) bool

Controls whether commands sent by the client will alter the LRU/LFU of the keys they access.

Redis command documentation: CLIENT NO-TOUCH

Compatibility:

Warning

Using client_no_touch directly is not recommended. Use Redis.notouch argument when initializing the client to ensure that all connections originating from this client use the desired mode

Added in version 4.12.0.

async client_pause(timeout: int, mode: Literal[PureToken.WRITE, PureToken.ALL] | None = None) bool

Stop processing commands from clients for some time

Returns:

The command returns True or raises an error if the timeout is invalid.

Redis command documentation: CLIENT PAUSE

Compatibility:

async client_reply(mode: Literal[PureToken.OFF, PureToken.ON, PureToken.SKIP]) bool

Instruct the server whether to reply to commands

Redis command documentation: CLIENT REPLY

Danger

Using client_reply directly is not supported. Use the Redis.noreply argument when initializing the client to ensure that all connections originating from this client disable or enable replies. You can also use the Redis.ignore_replies() context manager to selectively execute certain commands without waiting for a reply

Added in version 3.0.0.

async client_setinfo(lib_name: StringT | None = None, lib_ver: StringT | None = None) bool

Set client or connection specific info

Parameters:
  • lib_name – name of the library

  • lib_ver – version of the library

Redis command documentation: CLIENT SETINFO

Compatibility:

Warning

Using client_setinfo directly is not recommended. Coredis sets the library name and version by default during the handshake phase.Explicitly calling this command will only apply to the connection from the pool that was used to send it and not for subsequent commands

Added in version 4.12.0.

async client_setname(connection_name: StringT) bool

Set the current connection name :return: If the connection name was successfully set.

Redis command documentation: CLIENT SETNAME

Warning

Using client_setname directly is not recommended. Use the Redis.client_name argument when initializing the client to ensure the client name is consistent across all connections originating from the client

async client_tracking(status: Literal[PureToken.OFF, PureToken.ON], *prefixes: StringT, redirect: int | None = None, bcast: bool | None = None, optin: bool | None = None, optout: bool | None = None, noloop: bool | None = None) bool

Enable or disable server assisted client side caching support

Returns:

If the connection was successfully put in tracking mode or if the tracking mode was successfully disabled.

Redis command documentation: CLIENT TRACKING

Compatibility:

Added in version 3.0.0.

async client_trackinginfo() dict[AnyStr, AnyStr | set[AnyStr] | list[AnyStr]]

Return information about server assisted client side caching for the current connection

Returns:

a mapping of tracking information sections and their respective values

Redis command documentation: CLIENT TRACKINGINFO

Compatibility:

Added in version 3.0.0.

async client_unblock(client_id: int, timeout_error: Literal[PureToken.TIMEOUT, PureToken.ERROR] | None = None) bool

Unblock a client blocked in a blocking command from a different connection

Returns:

Whether the client was unblocked

Redis command documentation: CLIENT UNBLOCK

Added in version 3.0.0.

async client_unpause() bool

Resume processing of clients that were paused

Returns:

The command returns `True`

Redis command documentation: CLIENT UNPAUSE

Compatibility:

Added in version 3.0.0.

async echo(message: StringT) AnyStr

Echo the string back from the server

Redis command documentation: ECHO

async hello(protover: int | None = None, username: StringT | None = None, password: StringT | None = None, setname: StringT | None = None) dict[AnyStr, AnyStr]

Handshake with Redis

Returns:

a mapping of server properties.

Redis command documentation: HELLO

Compatibility:

Added in version 3.0.0.

async ping(message: StringT | None = None) AnyStr

Ping the server

Returns:

PONG, when no argument is provided else the message provided

Redis command documentation: PING

async quit() bool

Close the connection

Redis command documentation: QUIT

async reset() None

Reset the connection

Redis command documentation: RESET

Compatibility:

Added in version 3.0.0.

async select(index: int) bool

Change the selected database for the current connection

Redis command documentation: SELECT

Warning

Using select directly is not recommended. Use the db argument when initializing the client to ensure that all connections originating from this client use the desired database number

Added in version 3.0.0.

async sentinel_config_get(name: ValueT) dict[AnyStr, AnyStr]

Get the current value of a global Sentinel configuration parameter. The specified name may be a wildcard, similar to config_get()

Compatibility:

async sentinel_config_set(name: ValueT, value: ValueT) bool

Set the value of a global Sentinel configuration parameter

Compatibility:

async sentinel_failover(service_name: StringT) bool

Force a failover as if the master was not reachable, and without asking for agreement to other Sentinels

async sentinel_flushconfig() bool

Force Sentinel to rewrite its configuration on disk, including the current Sentinel state.

async sentinel_get_master_addr_by_name(service_name: StringT) tuple[str, int] | None

Returns a (host, port) pair for the given service_name

async sentinel_infocache(*nodenames: StringT) dict[AnyStr, dict[int, dict[str, ResponseType]]]

Return cached INFO output from masters and replicas.

async sentinel_master(service_name: StringT) dict[str, int | bool | str]

Returns a dictionary containing the specified masters state.

async sentinel_masters() dict[str, dict[str, int | bool | str]]

Returns a list of dictionaries containing each master’s state.

async sentinel_monitor(name: ValueT, ip: ValueT, port: int, quorum: int) bool

Adds a new master to Sentinel to be monitored

async sentinel_myid() AnyStr

Return the ID of the Sentinel instance Compatibility:

async sentinel_remove(name: ValueT) bool

Removes a master from Sentinel’s monitoring

async sentinel_replicas(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of replicas for service_name

async sentinel_reset(pattern: StringT) int

Reset all the masters with matching name. The pattern argument is a glob-style pattern. The reset process clears any previous state in a master (including a failover in progress), and removes every replica and sentinel already discovered and associated with the master.

async sentinel_sentinels(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of sentinels for service_name

async sentinel_set(name: ValueT, option: ValueT, value: ValueT) bool

Sets Sentinel monitoring parameters for a given master

async sentinel_slaves(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of slaves for paramref:service_name

property autocomplete: Autocomplete

Property to access Autocomplete commands.

Added in version 4.12.0.

property bf: BloomFilter

Property to access BloomFilter commands.

Added in version 4.12.0.

property cf: CuckooFilter

Property to access CuckooFilter commands.

Added in version 4.12.0.

property cms: CountMinSketch

Property to access CountMinSketch commands.

Added in version 4.12.0.

property graph: Graph

Property to access Graph commands.

Added in version 4.12.0.

property json: Json

Property to access Json commands.

Added in version 4.12.0.

property search: Search

Property to access Search commands.

Added in version 4.12.0.

property tdigest: TDigest

Property to access TDigest commands.

Added in version 4.12.0.

property timeseries: TimeSeries

Property to access TimeSeries commands.

Added in version 4.12.0.

property topk: TopK

Property to access TopK commands.

Added in version 4.12.0.

Cluster

class RedisCluster(host: str | None = None, port: int | None = None, *, startup_nodes: Iterable[Node] | None = None, stream_timeout: float | None = None, connect_timeout: float | None = None, ssl: bool = False, ssl_context: SSLContext | None = None, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = None, ssl_check_hostname: bool | None = None, ssl_ca_certs: str | None = None, max_connections: int = 32, max_connections_per_node: bool = False, readonly: bool = False, read_from_replicas: bool = False, reinitialize_steps: int | None = None, skip_full_coverage_check: bool = False, nodemanager_follow_cluster: bool = True, decode_responses: bool = False, connection_pool: ClusterConnectionPool | None = None, connection_pool_cls: Type[ClusterConnectionPool] = ClusterConnectionPool, protocol_version: Literal[2, 3] = 3, verify_version: bool = True, non_atomic_cross_slot: bool = True, cache: AbstractCache | None = None, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = CompositeRetryPolicy(ConstantRetryPolicy((ClusterDownError,), 2, 0.1), ConstantRetryPolicy((ConnectionError, TimeoutError), 2, 0.1)), **kwargs: Any)[source]
Changes
Parameters:
  • host – Can be used to point to a startup node

  • port – Can be used to point to a startup node

  • startup_nodes – List of nodes that initial bootstrapping can be done from

  • stream_timeout – Timeout (seconds) when reading responses from the server

  • connect_timeout – Timeout (seconds) for establishing a connection to the server

  • ssl – Whether to use an SSL connection

  • ssl_context – If provided the ssl.SSLContext will be used when establishing the connection. Otherwise either the default context (if no other ssl related parameters are provided) or a custom context based on the other ssl_* parameters will be used.

  • ssl_keyfile – Path of the private key to use

  • ssl_certfile – Path to the certificate corresponding to ssl_keyfile

  • ssl_cert_reqs – Whether to try to verify the server’s certificates and how to behave if verification fails (See ssl.SSLContext.verify_mode).

  • ssl_check_hostname – Whether to enable hostname checking when establishing an ssl connection.

  • ssl_ca_certs – Path to a concatenated certificate authority file or a directory containing several CA certifcates to use for validating the server’s certificates when ssl_cert_reqs is not "none" (See ssl.SSLContext.load_verify_locations()).

  • max_connections – Maximum number of connections that should be kept open at one time

  • max_connections_per_node

  • read_from_replicas – If True the client will route readonly commands to replicas

  • reinitialize_steps – Number of moved errors that result in a cluster topology refresh using the startup nodes provided

  • skip_full_coverage_check – Skips the check of cluster-require-full-coverage config, useful for clusters without the CONFIG command (like aws)

  • nodemanager_follow_cluster – The node manager will during initialization try the last set of nodes that it was operating on. This will allow the client to drift along side the cluster if the cluster nodes move around alot.

  • decode_responses – If True string responses from the server will be decoded using encoding before being returned. (See Encoding/Decoding)

  • connection_pool – The connection pool instance to use. If not provided a new pool will be assigned to this client.

  • connection_pool_cls – The connection pool class to use when constructing a connection pool for this instance.

  • protocol_version – Whether to use the RESP (2) or RESP3 (3) protocol for parsing responses from the server (Default 3). (See Redis Response)

  • verify_version – Validate redis server version against the documented version introduced before executing a command and raises a CommandNotSupportedError error if the required version is higher than the reported server version

  • non_atomic_cross_slot – If True certain commands that can operate on multiple keys (cross slot) will be split across the relevant nodes by mapping the keys to the appropriate slot and the result merged before being returned.

  • cache – If provided the cache will be used to avoid requests for read only commands if the client has already requested the data and it hasn’t been invalidated. The cache is responsible for any mutations to the keys that happen outside of this client

  • noreply – If True the client will not request a response for any commands sent to the server.

  • noevict – Ensures that connections from the client will be excluded from the client eviction process even if we’re above the configured client eviction threshold.

  • notouch – Ensures that commands sent by the client will not alter the LRU/LFU of the keys they access.

  • retry_policy – The retry policy to use when interacting with the cluster

classmethod from_url(url: str, *, db: int | None = None, skip_full_coverage_check: bool = False, decode_responses: ~typing.Literal[False] = False, protocol_version: ~typing.Literal[2, 3] = 3, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: ~coredis.retry.RetryPolicy = CompositeRetryPolicy<ConstantRetryPolicy<retries=2, retryable_exceptions=ClusterDownError>, ConstantRetryPolicy<retries=2, retryable_exceptions=ConnectionError, TimeoutError>>, **kwargs: ~typing.Any) RedisClusterBytesT[source]
classmethod from_url(url: str, *, db: int | None = None, skip_full_coverage_check: bool = False, decode_responses: ~typing.Literal[True], protocol_version: ~typing.Literal[2, 3] = 3, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: ~coredis.retry.RetryPolicy = CompositeRetryPolicy<ConstantRetryPolicy<retries=2, retryable_exceptions=ClusterDownError>,ConstantRetryPolicy<retries=2, retryable_exceptions=ConnectionError,TimeoutError>>, **kwargs: ~typing.Any) RedisClusterStringT

Return a Cluster client object configured from the startup node in URL, which must use either the redis:// scheme http://www.iana.org/assignments/uri-schemes/prov/redis

For example:

  • redis://[:password]@localhost:6379

  • rediss://[:password]@localhost:6379

url and kwargs are passed as is to the coredis.ConnectionPool.from_url().

bitfield(key: KeyT) BitFieldOperation
Returns:

a BitFieldOperation instance to conveniently construct one or more bitfield operations on key.

bitfield_ro(key: KeyT) BitFieldOperation
Returns:

a BitFieldOperation instance to conveniently construct bitfield operations on a read only replica against key.

Raises ReadOnlyError if a write operation is attempted

decoding(mode: Literal[False], encoding: str | None = None) ContextManager[RedisCluster[bytes]][source]
decoding(mode: Literal[True], encoding: str | None = None) ContextManager[RedisCluster[str]]

Context manager to temporarily change the decoding behavior of the client

Parameters:
  • mode – Whether to decode or not

  • encoding – Optional encoding to use if decoding. If not provided the encoding parameter provided to the client will be used.

Example:

client = coredis.RedisCluster(decode_responses=True)
await client.set("fubar", "baz")
assert await client.get("fubar") == "baz"
with client.decoding(False):
    assert await client.get("fubar") == b"baz"
    with client.decoding(True):
        assert await client.get("fubar") == "baz"

Added in version 4.8.0.

ensure_persistence(local: Literal[0, 1] = 0, replicas: int = 0, timeout_ms: int = 100) Iterator[ClientT]

Context manager to ensure that commands executed within the context are synced to the AOF of a local host and/or replicas within timeout_ms milliseconds.

Internally this uses WAITAOF after each command executed within the context

Raises:

coredis.exceptions.PersistenceError

Example for standalone client:

client = coredis.Redis()
with client.ensure_persistence(1, 0, 20):
    await client.set("fubar", 1)

Example for cluster:

client = coredis.RedisCluster("localhost", 7000)
with client.ensure_persistence(1, 1, 20):
    await client.set("fubar", 1)

Added in version 4.12.0.

ensure_replication(replicas: int = 1, timeout_ms: int = 100) Iterator[ClientT]

Context manager to ensure that commands executed within the context are replicated to atleast replicas within timeout_ms milliseconds.

Internally this uses WAIT after each command executed within the context

Raises:

coredis.exceptions.ReplicationError

Example:

client = coredis.RedisCluster("localhost", 7000)
with client.ensure_replication(1, 20):
    await client.set("fubar", 1)
async execute_command(command: bytes, *args: ValueT, callback: Callable[[...], R] = NoopCallback(), **kwargs: ValueT | None) R[source]

Sends a command to one or many nodes in the cluster with retries based on RedisCluster.retry_policy

async get_library(name: StringT) Library

Fetch a pre registered library

Parameters:

name – name of the library

Added in version 3.1.0.

async hscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncGenerator[tuple[AnyStr, AnyStr], None]

Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.

ignore_replies() Iterator[ClientT]

Context manager to run commands without waiting for a reply.

Example:

client = coredis.Redis()
with client.ignore_replies():
    assert None == await client.set("fubar", 1), "noreply"
assert True == await client.set("fubar", 1), "reply"
async pipeline(transaction: bool | None = None, watches: Parameters[StringT] | None = None, timeout: float | None = None) coredis.pipeline.ClusterPipeline[AnyStr][source]

Returns a new pipeline object that can queue multiple commands for batch execution. Pipelines in cluster mode only provide a subset of the functionality of pipelines in standalone mode.

Specifically:

  • Each command in the pipeline should only access keys on the same node

  • Transactions are disabled by default and are only supported if all watched keys route to the same node as where the commands in the multi/exec part of the pipeline.

Parameters:
  • transaction – indicates whether all commands should be executed atomically.

  • watches – If transaction is True these keys are watched for external changes during the transaction.

  • timeout – If specified this value will take precedence over RedisCluster.stream_timeout

pubsub(ignore_subscribe_messages: bool = False, retry_policy: RetryPolicy | None = None, **kwargs: Any) ClusterPubSub[source]

Return a Pub/Sub instance that can be used to subscribe to channels or patterns in a redis cluster and receive messages that get published to them.

Parameters:
  • ignore_subscribe_messages – Whether to skip subscription acknowledgement messages

  • retry_policy – An explicit retry policy to use in the subscriber.

async register_library(name: StringT, code: StringT, replace: bool = False) Library

Register a new library

Parameters:
  • name – name of the library

  • code – raw code for the library

  • replace – Whether to replace the library when intializing. If False an exception will be raised if the library was already loaded in the target redis instance.

Added in version 3.1.0.

register_script(script: ValueT) Script

Registers a Lua script

Returns:

A coredis.commands.script.Script instance that is callable and hides the complexity of dealing with scripts, keys, and shas.

async scan_iter(match: StringT | None = None, count: int | None = None, type_: StringT | None = None) AsyncIterator[source]

Make an iterator using the SCAN command so that the client doesn’t need to remember the cursor position.

sharded_pubsub(ignore_subscribe_messages: bool = False, read_from_replicas: bool = False, retry_policy: RetryPolicy | None = None, **kwargs: Any) ShardedPubSub[source]

Return a Pub/Sub instance that can be used to subscribe to channels in a redis cluster and receive messages that get published to them. The implementation returned differs from that returned by pubsub() as it uses the Sharded Pub/Sub implementation which routes messages to cluster nodes using the same algorithm used to assign keys to slots. This effectively restricts the propagation of messages to be within the shard of a cluster hence affording horizontally scaling the use of Pub/Sub with the cluster itself.

Parameters:
  • ignore_subscribe_messages – Whether to skip subscription acknowledgement messages

  • read_from_replicas – Whether to read messages from replica nodes

  • retry_policy – An explicit retry policy to use in the subscriber.

New in Redis version: 7.0.0

Added in version 3.6.0.

async sscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncIterator

Make an iterator using the SSCAN command so that the client doesn’t need to remember the cursor position.

async transaction(func: Callable[['coredis.pipeline.ClusterPipeline[AnyStr]'], Coroutine[Any, Any, Any]], *watches: StringT, value_from_callable: bool = False, watch_delay: float | None = None, **kwargs: Any) Any[source]

Convenience method for executing the callable func as a transaction while watching all keys specified in watches.

Parameters:
  • func – callable should expect a single argument which is a coredis.pipeline.ClusterPipeline object retrieved by calling pipeline().

  • watches – The keys to watch during the transaction. The keys should route to the same node as the keys touched by the commands in func

  • value_from_callable – Whether to return the result of transaction or the value returned from func

Warning

Cluster transactions can only be run with commands that route to the same slot.

Changed in version 4.9.0: When the transaction is started with watches the ClusterPipeline instance passed to func will not start queuing commands until a call to multi() is made. This makes the cluster implementation consistent with coredis.Redis.transaction()

async zscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None) AsyncIterator[ScoredMember]

Make an iterator using the ZSCAN command so that the client doesn’t need to remember the cursor position.

async append(key: KeyT, value: ValueT) int

Append a value to a key

Returns:

the length of the string after the append operation.

Redis command documentation: APPEND

async decr(key: KeyT) int

Decrement the integer value of a key by one

Returns:

the value of key after the decrement

Redis command documentation: DECR

async decrby(key: KeyT, decrement: int) int

Decrement the integer value of a key by the given number

Returns:

the value of key after the decrement

Redis command documentation: DECRBY

async get(key: KeyT) AnyStr | None

Get the value of a key

Returns:

the value of key, or None when key does not exist.

Redis command documentation: GET

Hint

Supports client side caching

async getdel(key: KeyT) AnyStr | None

Get the value of a key and delete the key

Returns:

the value of key, None when key does not exist, or an error if the key’s value type isn’t a string.

Redis command documentation: GETDEL

Compatibility:

async getex(key: KeyT, ex: int | timedelta | None = None, px: int | timedelta | None = None, exat: int | datetime | None = None, pxat: int | datetime | None = None, persist: bool | None = None) AnyStr | None

Get the value of a key and optionally set its expiration

GETEX is similar to GET, but is a write command with additional options. All time parameters can be given as datetime.timedelta or integers.

Parameters:
  • key – name of the key

  • ex – sets an expire flag on key key for ex seconds.

  • px – sets an expire flag on key key for px milliseconds.

  • exat – sets an expire flag on key key for ex seconds, specified in unix time.

  • pxat – sets an expire flag on key key for ex milliseconds, specified in unix time.

  • persist – remove the time to live associated with key.

Returns:

the value of key, or None when key does not exist.

Redis command documentation: GETEX

Compatibility:

async getrange(key: KeyT, start: int, end: int) AnyStr

Get a substring of the string stored at a key

Returns:

The substring of the string value stored at key, determined by the offsets start and end (both are inclusive)

Redis command documentation: GETRANGE

Hint

Supports client side caching

async getset(key: KeyT, value: ValueT) AnyStr | None

Set the string value of a key and return its old value

Returns:

the old value stored at key, or None when key did not exist.

Redis command documentation: GETSET

async incr(key: KeyT) int

Increment the integer value of a key by one

Returns:

the value of key after the increment. If no key exists, the value will be initialized as 1.

Redis command documentation: INCR

async incrby(key: KeyT, increment: int) int

Increment the integer value of a key by the given amount

Returns:

the value of key after the increment If no key exists, the value will be initialized as increment

Redis command documentation: INCRBY

async incrbyfloat(key: KeyT, increment: int | float) float

Increment the float value of a key by the given amount

Returns:

the value of key after the increment. If no key exists, the value will be initialized as increment

Redis command documentation: INCRBYFLOAT

async lcs(key1: KeyT, key2: KeyT, *, len_: bool | None = None, idx: bool | None = None, minmatchlen: int | None = None, withmatchlen: bool | None = None) AnyStr | int | LCSResult

Find the longest common substring

Returns:

The matched string if no other arguments are given. The returned values vary depending on different arguments.

  • If len_ is provided the length of the longest match

  • If idx is True all the matches with the start/end positions of both keys. Optionally, if withmatchlen is True each match will contain the length of the match.

Redis command documentation: LCS

Compatibility:

Added in version 3.0.0.

async mget(keys: Parameters[KeyT]) Tuple[AnyStr | None, ...]

Returns values ordered identically to keys

Redis command documentation: MGET

async mset(key_values: Mapping[KeyT, ValueT]) bool

Sets multiple keys to multiple values

Redis command documentation: MSET

async msetnx(key_values: Mapping[KeyT, ValueT]) bool

Set multiple keys to multiple values, only if none of the keys exist

Returns:

Whether all the keys were set

Redis command documentation: MSETNX

async psetex(key: KeyT, milliseconds: int | timedelta, value: ValueT) bool

Set the value and expiration in milliseconds of a key

Redis command documentation: PSETEX

async set(key: KeyT, value: ValueT, *, condition: Literal[PureToken.NX, PureToken.XX] | None = None, get: bool | None = None, ex: int | timedelta | None = None, px: int | timedelta | None = None, exat: int | datetime | None = None, pxat: int | datetime | None = None, keepttl: bool | None = None) AnyStr | bool | None

Set the string value of a key

Parameters:
  • condition – Condition to use when setting the key

  • get – Return the old string stored at key, or nil if key did not exist. An error is returned and the command is aborted if the value stored at key is not a string.

  • ex – Number of seconds to expire in

  • px – Number of milliseconds to expire in

  • exat – Expiry time with seconds granularity

  • pxat – Expiry time with milliseconds granularity

  • keepttl – Retain the time to live associated with the key

Returns:

Whether the operation was performed successfully.

Warning

If the command is issued with the get argument, the old string value stored at key is return regardless of success or failure - except if the key was not found.

Redis command documentation: SET

Compatibility:

async setex(key: KeyT, value: ValueT, seconds: int | timedelta) bool

Set the value of key key to value that expires in seconds

Redis command documentation: SETEX

async setnx(key: KeyT, value: ValueT) bool

Sets the value of key key to value if key doesn’t exist

Redis command documentation: SETNX

async setrange(key: KeyT, offset: int, value: ValueT) int

Overwrite bytes in the value of key starting at offset with value. If offset plus the length of value exceeds the length of the original value, the new value will be larger than before.

If offset exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what’s being injected.

Returns:

the length of the string after it was modified by the command.

Redis command documentation: SETRANGE

async strlen(key: KeyT) int

Get the length of the value stored in a key

Returns:

the length of the string at key, or 0 when key does not

Redis command documentation: STRLEN

Hint

Supports client side caching

async substr(key: KeyT, start: int, end: int) AnyStr

Get a substring of the string stored at a key

Returns:

the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). Negative offsets can be used in order to provide an offset starting from the end of the string.

Redis command documentation: SUBSTR

Hint

Supports client side caching

async bitcount(key: KeyT, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) int

Returns the count of set bits in the value of key. Optional start and end parameters indicate which bytes to consider

Redis command documentation: BITCOUNT

Compatibility:

async bitop(keys: Parameters[KeyT], operation: StringT, destkey: KeyT) int

Perform a bitwise operation using operation between keys and store the result in destkey.

Redis command documentation: BITOP

async bitpos(key: KeyT, bit: int, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) int

Return the position of the first bit set to 1 or 0 in a string. start and end defines the search range. The range is interpreted as a range of bytes and not a range of bits, so start=0 and end=2 means to look at the first three bytes.

Returns:

The position of the first bit set to 1 or 0 according to the request. If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned.

If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns the first bit not part of the string on the right.

So if the string is three bytes set to the value 0xff the command BITPOS key 0 will return 24, since up to bit 23 all the bits are 1.

Basically, the function considers the right of the string as padded with zeros if you look for clear bits and specify no range or the start argument only.

However, this behavior changes if you are looking for clear bits and specify a range with both start and end.

If no clear bit is found in the specified range, the function returns -1 as the user specified a clear range and there are no 0 bits in that range.

Redis command documentation: BITPOS

Compatibility:

async getbit(key: KeyT, offset: int) int

Returns the bit value at offset in the string value stored at key

Returns:

the bit value stored at offset.

Redis command documentation: GETBIT

async setbit(key: KeyT, offset: int, value: int) int

Flag the offset in key as value.

Redis command documentation: SETBIT

async copy(source: KeyT, destination: KeyT, db: int | None = None, replace: bool | None = None) bool

Copy a key

Redis command documentation: COPY

Compatibility:

Added in version 3.0.0.

async delete(keys: Parameters[KeyT]) int

Delete one or more keys specified by keys

Returns:

The number of keys that were removed.

Redis command documentation: DEL

Cluster note

The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.

To disable this behavior set RedisCluster.non_atomic_cross_slot to False

async dump(key: KeyT) bytes

Return a serialized version of the value stored at the specified key.

Returns:

the serialized value

Redis command documentation: DUMP

async exists(keys: Parameters[KeyT]) int

Determine if a key exists

Returns:

the number of keys that exist from those specified as arguments.

Redis command documentation: EXISTS

Cluster note

The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.

To disable this behavior set RedisCluster.non_atomic_cross_slot to False

async expire(key: KeyT, seconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set a key’s time to live in seconds

Returns:

if the timeout was set or not set. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: EXPIRE

Compatibility:

async expireat(key: KeyT, unix_time_seconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set the expiration for a key to a specific time

Returns:

if the timeout was set or no. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: EXPIREAT

Compatibility:

async expiretime(key: KeyT) datetime

Get the expiration Unix timestamp for a key

Returns:

Expiration Unix timestamp in seconds, or a negative value in order to signal an error.

  • The command returns -1 if the key exists but has no associated expiration time.

  • The command returns -2 if the key does not exist.

Redis command documentation: EXPIRETIME

Compatibility:

Added in version 3.0.0.

async keys(pattern: StringT = '*') set[AnyStr]

Find all keys matching the given pattern

Returns:

keys matching pattern.

Redis command documentation: KEYS

Cluster note

The command will be run on all primaries and return the union of the results

async migrate(host: StringT, port: int, destination_db: int, timeout: int, *keys: KeyT, copy: bool | None = None, replace: bool | None = None, auth: StringT | None = None, username: StringT | None = None, password: StringT | None = None) bool

Atomically transfer key(s) from a Redis instance to another one.

Returns:

If all keys were found in the source instance.

Redis command documentation: MIGRATE

Added in version 3.0.0.

async move(key: KeyT, db: int) bool

Move a key to another database

Redis command documentation: MOVE

async object_encoding(key: KeyT) AnyStr | None

Return the internal encoding for the object stored at key

Returns:

the encoding of the object, or None if the key doesn’t exist

Redis command documentation: OBJECT ENCODING

async object_freq(key: KeyT) int

Return the logarithmic access frequency counter for the object stored at key

Returns:

The counter’s value.

Redis command documentation: OBJECT FREQ

async object_idletime(key: KeyT) int

Return the time in seconds since the last access to the object stored at key

Returns:

The idle time in seconds.

Redis command documentation: OBJECT IDLETIME

async object_refcount(key: KeyT) int

Return the reference count of the object stored at key

Returns:

The number of references.

Redis command documentation: OBJECT REFCOUNT

async persist(key: KeyT) bool

Removes an expiration on key

Redis command documentation: PERSIST

async pexpire(key: KeyT, milliseconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set a key’s time to live in milliseconds

Returns:

if the timeout was set or not. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: PEXPIRE

Compatibility:

async pexpireat(key: KeyT, unix_time_milliseconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) bool

Set the expiration for a key as a UNIX timestamp specified in milliseconds

Returns:

if the timeout was set or not. e.g. key doesn’t exist, or operation skipped due to the provided arguments.

Redis command documentation: PEXPIREAT

Compatibility:

async pexpiretime(key: KeyT) datetime

Get the expiration Unix timestamp for a key in milliseconds

Returns:

Expiration Unix timestamp in milliseconds, or a negative value in order to signal an error

  • The command returns -1 if the key exists but has no associated expiration time.

  • The command returns -2 if the key does not exist.

Redis command documentation: PEXPIRETIME

Compatibility:

Added in version 3.0.0.

async pttl(key: KeyT) int

Returns the number of milliseconds until the key key will expire

Returns:

TTL in milliseconds, or a negative value in order to signal an error

Redis command documentation: PTTL

async randomkey() AnyStr | None

Returns the name of a random key

Returns:

the random key, or None when the database is empty.

Redis command documentation: RANDOMKEY

Cluster note

The command will be run on a random node

async rename(key: KeyT, newkey: KeyT) bool

Rekeys key key to newkey

Redis command documentation: RENAME

async renamenx(key: KeyT, newkey: KeyT) bool

Rekeys key key to newkey if newkey doesn’t already exist

Returns:

False when newkey already exists.

Redis command documentation: RENAMENX

async restore(key: KeyT, ttl: int | timedelta | datetime, serialized_value: bytes, replace: bool | None = None, absttl: bool | None = None, idletime: int | timedelta | None = None, freq: int | None = None) bool

Create a key using the provided serialized value, previously obtained using DUMP.

Redis command documentation: RESTORE

async scan(cursor: int | None = 0, match: StringT | None = None, count: int | None = None, type_: StringT | None = None) tuple[int, tuple[AnyStr, ...]]

Incrementally iterate the keys space

Redis command documentation: SCAN

Cluster note

The command will be run on all primaries and a mapping of nodes to results will be returned

async sort(key: KeyT, gets: Parameters[KeyT] | None = None, by: StringT | None = None, offset: int | None = None, count: int | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, alpha: bool | None = None, store: KeyT | None = None) Tuple[AnyStr, ...] | int

Sort the elements in a list, set or sorted set

Returns:

sorted elements.

When the store option is specified the command returns the number of sorted elements in the destination list.

Redis command documentation: SORT

async sort_ro(key: KeyT, gets: Parameters[KeyT] | None = None, by: StringT | None = None, offset: int | None = None, count: int | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, alpha: bool | None = None) Tuple[AnyStr, ...]

Sort the elements in a list, set or sorted set. Read-only variant of SORT.

Returns:

sorted elements.

Redis command documentation: SORT_RO

Compatibility:

Added in version 3.0.0.

async touch(keys: Parameters[KeyT]) int

Alters the last access time of a key(s). Returns the number of existing keys specified.

Returns:

The number of keys that were touched.

Redis command documentation: TOUCH

Cluster note

The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.

To disable this behavior set RedisCluster.non_atomic_cross_slot to False

async ttl(key: KeyT) int

Get the time to live for a key in seconds

Returns:

TTL in seconds, or a negative value in order to signal an error

Redis command documentation: TTL

async type(key: KeyT) AnyStr | None

Determine the type stored at key

Returns:

type of key, or None when key does not exist.

Redis command documentation: TYPE

Hint

Supports client side caching

Delete a key asynchronously in another thread. Otherwise it is just as delete(), but non blocking.

Returns:

The number of keys that were unlinked.

Redis command documentation: UNLINK

Cluster note

The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.

To disable this behavior set RedisCluster.non_atomic_cross_slot to False

async wait(numreplicas: int, timeout: int) int

Wait for the synchronous replication of all the write commands sent in the context of the current connection

Returns:

the number of replicas the write was replicated to

Redis command documentation: WAIT

Warning

Using wait directly is not recommended. Use the Redis.ensure_replication() or RedisCluster.ensure_replication() context managers to ensure a command is replicated to the number of replicas

async waitaof(numlocal: int, numreplicas: int, timeout: int) tuple[int, ...]

Wait for all write commands sent in the context of the current connection to be synced to AOF of local host and/or replicas

Returns:

a tuple of (numlocal, numreplicas) that the write commands were synced to

Redis command documentation: WAITAOF

Compatibility:

Warning

Using waitaof directly is not recommended. Use the Redis.ensure_persistence() or RedisCluster.ensure_persistence() context managers to ensure a command is synced to the AOF of the number of local hosts or replicas

Added in version 4.12.0.

async hdel(key: KeyT, fields: Parameters[StringT]) int

Deletes fields from hash key

Redis command documentation: HDEL

async hexists(key: KeyT, field: StringT) bool

Returns a boolean indicating if field exists within hash key

Redis command documentation: HEXISTS

Hint

Supports client side caching

async hget(key: KeyT, field: StringT) AnyStr | None

Returns the value of field within the hash key

Redis command documentation: HGET

Hint

Supports client side caching

async hgetall(key: KeyT) dict[AnyStr, AnyStr]

Returns a Python dict of the hash’s name/value pairs

Redis command documentation: HGETALL

Hint

Supports client side caching

async hincrby(key: KeyT, field: StringT, increment: int) int

Increments the value of field in hash key by increment

Redis command documentation: HINCRBY

async hincrbyfloat(key: KeyT, field: StringT, increment: int | float) float

Increments the value of field in hash key by floating increment

Redis command documentation: HINCRBYFLOAT

async hkeys(key: KeyT) tuple[AnyStr, ...]

Returns the list of keys within hash key

Redis command documentation: HKEYS

Hint

Supports client side caching

async hlen(key: KeyT) int

Returns the number of elements in hash key

Redis command documentation: HLEN

Hint

Supports client side caching

async hmget(key: KeyT, fields: Parameters[StringT]) Tuple[AnyStr | None, ...]

Returns values ordered identically to fields

Redis command documentation: HMGET

Hint

Supports client side caching

async hmset(key: KeyT, field_values: Mapping[StringT, ValueT]) bool

Sets key to value within hash key for each corresponding key and value from the field_items dict.

Redis command documentation: HMSET

async hrandfield(key: KeyT, *, count: int | None = None, withvalues: bool | None = None) AnyStr | tuple[AnyStr, ...] | dict[AnyStr, AnyStr] | None

Return a random field from the hash value stored at key.

Returns:

Without the additional count argument, the command returns a randomly selected field, or None when key does not exist. When the additional count argument is passed, the command returns fields, or an empty tuple when key does not exist.

If withvalues is True, the reply is a mapping of fields and their values from the hash.

Redis command documentation: HRANDFIELD

Compatibility:

async hscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, dict[AnyStr, AnyStr]]

Incrementallys return key/value slices in a hash. Also returns a cursor pointing to the scan position.

Parameters:
  • match – allows for filtering the keys by pattern

  • count – allows for hint the minimum number of returns

Redis command documentation: HSCAN

async hset(key: KeyT, field_values: Mapping[StringT, ValueT]) int

Sets field to value within hash key

Returns:

number of fields that were added

Redis command documentation: HSET

async hsetnx(key: KeyT, field: StringT, value: ValueT) bool

Sets field to value within hash key if field does not exist.

Returns:

whether the field was created

Redis command documentation: HSETNX

async hstrlen(key: KeyT, field: StringT) int

Get the length of the value of a hash field

Returns:

the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.

Redis command documentation: HSTRLEN

Hint

Supports client side caching

async hvals(key: KeyT) tuple[AnyStr, ...]

Get all the values in a hash

Returns:

list of values in the hash, or an empty list when key does not exist.

Redis command documentation: HVALS

Hint

Supports client side caching

async pfadd(key: KeyT, *elements: ValueT) bool

Adds the specified elements to the specified HyperLogLog.

Returns:

Whether atleast 1 HyperLogLog internal register was altered

Redis command documentation: PFADD

async pfcount(keys: Parameters[KeyT]) int

Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).

Returns:

The approximated number of unique elements observed via pfadd().

Redis command documentation: PFCOUNT

async pfmerge(destkey: KeyT, sourcekeys: Parameters[KeyT]) bool

Merge N different HyperLogLogs into a single one

Redis command documentation: PFMERGE

async blmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT], timeout: int | float) AnyStr | None

Pop an element from a list, push it to another list and return it; or block until one is available

Returns:

the element being popped from source and pushed to destination

Redis command documentation: BLMOVE

Compatibility:

async blmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) List[AnyStr | List[AnyStr]] | None

Pop elements from the first non empty list, or block until one is available

Returns:

  • A None when no element could be popped, and timeout is reached.

  • A two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of elements.

Redis command documentation: BLMPOP

Compatibility:

Added in version 3.0.0.

async blpop(keys: Parameters[KeyT], timeout: int | float) List[AnyStr] | None

Remove and get the first element in a list, or block until one is available

Returns:

  • None when no element could be popped and the timeout expired.

  • A list with the first element being the name of the key where an element was popped and the second element being the value of the popped element.

Redis command documentation: BLPOP

async brpop(keys: Parameters[KeyT], timeout: int | float) List[AnyStr] | None

Remove and get the last element in a list, or block until one is available

Returns:

  • None when no element could be popped and the timeout expired.

  • A list with the first element being the name of the key where an element was popped and the second element being the value of the popped element.

Redis command documentation: BRPOP

async brpoplpush(source: KeyT, destination: KeyT, timeout: int | float) AnyStr | None

Pop an element from a list, push it to another list and return it; or block until one is available

Returns:

the element being popped from source and pushed to destination.

Redis command documentation: BRPOPLPUSH

async lindex(key: KeyT, index: int) AnyStr | None

Get an element from a list by its index

Returns:

the requested element, or None when index is out of range.

Redis command documentation: LINDEX

Hint

Supports client side caching

async linsert(key: KeyT, where: Literal[PureToken.AFTER, PureToken.BEFORE], pivot: ValueT, element: ValueT) int

Inserts element in the list stored at key either before or after the reference value pivot.

Returns:

the length of the list after the insert operation, or -1 when the value pivot was not found.

Redis command documentation: LINSERT

async llen(key: KeyT) int
Returns:

the length of the list at key.

Redis command documentation: LLEN

Hint

Supports client side caching

async lmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT]) AnyStr

Pop an element from a list, push it to another list and return it

Returns:

the element being popped and pushed.

Redis command documentation: LMOVE

Compatibility:

async lmpop(keys: Parameters[KeyT], where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) List[AnyStr | List[AnyStr]] | None

Pop elements from the first non empty list

Returns:

  • A `None` when no element could be popped.

  • A two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of elements.

Redis command documentation: LMPOP

Compatibility:

Added in version 3.0.0.

async lpop(key: KeyT, count: int | None = None) AnyStr | list[AnyStr] | None

Remove and get the first count elements in a list

Returns:

the value of the first element, or None when key does not exist. If count is provided the return is a list of popped elements, or None when key does not exist.

Redis command documentation: LPOP

Compatibility:

async lpos(key: KeyT, element: ValueT, rank: int | None = None, count: int | None = None, maxlen: int | None = None) int | list[int] | None

Return the index of matching elements on a list

Returns:

The command returns the integer representing the matching element, or None if there is no match.

If the count argument is given a list of integers representing the matching elements.

Redis command documentation: LPOS

Compatibility:

Hint

Supports client side caching

async lpush(key: KeyT, elements: Parameters[ValueT]) int

Prepend one or multiple elements to a list

Returns:

the length of the list after the push operations.

Redis command documentation: LPUSH

async lpushx(key: KeyT, elements: Parameters[ValueT]) int

Prepend an element to a list, only if the list exists

Returns:

the length of the list after the push operation.

Redis command documentation: LPUSHX

async lrange(key: KeyT, start: int, stop: int) list[AnyStr]

Get a range of elements from a list

Returns:

list of elements in the specified range.

Redis command documentation: LRANGE

Hint

Supports client side caching

async lrem(key: KeyT, count: int, element: ValueT) int

Removes the first count occurrences of elements equal to element from the list stored at key.

The count argument influences the operation in the following ways:

count > 0: Remove elements equal to value moving from head to tail. count < 0: Remove elements equal to value moving from tail to head. count = 0: Remove all elements equal to value.

Returns:

the number of removed elements.

Redis command documentation: LREM

async lset(key: KeyT, index: int, element: ValueT) bool

Sets index of list key to element

Redis command documentation: LSET

async ltrim(key: KeyT, start: int, stop: int) bool

Trims the list key, removing all values not within the slice between start and stop

start and stop can be negative numbers just like Python slicing notation

Redis command documentation: LTRIM

async rpop(key: KeyT, count: int | None = None) AnyStr | list[AnyStr] | None

Remove and get the last elements in a list

Returns:

When called without the count argument the value of the last element, or None when key does not exist.

When called with the count argument list of popped elements, or None when key does not exist.

Redis command documentation: RPOP

Compatibility:

async rpoplpush(source: KeyT, destination: KeyT) AnyStr | None

Remove the last element in a list, prepend it to another list and return it

Returns:

the element being popped and pushed.

Redis command documentation: RPOPLPUSH

async rpush(key: KeyT, elements: Parameters[ValueT]) int

Append an element(s) to a list

Returns:

the length of the list after the push operation.

Redis command documentation: RPUSH

async rpushx(key: KeyT, elements: Parameters[ValueT]) int

Append a element(s) to a list, only if the list exists

Returns:

the length of the list after the push operation.

Redis command documentation: RPUSHX

async sadd(key: KeyT, members: Parameters[ValueT]) int

Add one or more members to a set

Returns:

the number of elements that were added to the set, not including all the elements already present in the set.

Redis command documentation: SADD

async scard(key: KeyT) int

Returns the number of members in the set

:return the cardinality (number of elements) of the set, or 0 if key

does not exist.

Redis command documentation: SCARD

Hint

Supports client side caching

async sdiff(keys: Parameters[KeyT]) Set[AnyStr]

Subtract multiple sets

Returns:

members of the resulting set.

Redis command documentation: SDIFF

async sdiffstore(keys: Parameters[KeyT], destination: KeyT) int

Subtract multiple sets and store the resulting set in a key

Redis command documentation: SDIFFSTORE

async sinter(keys: Parameters[KeyT]) Set[AnyStr]

Intersect multiple sets

Returns:

members of the resulting set

Redis command documentation: SINTER

async sintercard(keys: Parameters[KeyT], limit: int | None = None) int

Intersect multiple sets and return the cardinality of the result

Returns:

The number of elements in the resulting intersection.

Redis command documentation: SINTERCARD

Compatibility:

Added in version 3.0.0.

async sinterstore(keys: Parameters[KeyT], destination: KeyT) int

Intersect multiple sets and store the resulting set in a key

Returns:

the number of elements in the resulting set.

Redis command documentation: SINTERSTORE

async sismember(key: KeyT, member: ValueT) bool

Determine if a given value is a member of a set

Returns:

If the element is a member of the set. False if key does not exist.

Redis command documentation: SISMEMBER

Hint

Supports client side caching

async smembers(key: KeyT) set[AnyStr]

Returns all members of the set

Redis command documentation: SMEMBERS

Hint

Supports client side caching

async smismember(key: KeyT, members: Parameters[ValueT]) Tuple[bool, ...]

Returns the membership associated with the given elements for a set

Returns:

tuple representing the membership of the given elements, in the same order as they are requested.

Redis command documentation: SMISMEMBER

Compatibility:

Hint

Supports client side caching

async smove(source: KeyT, destination: KeyT, member: ValueT) bool

Move a member from one set to another

Redis command documentation: SMOVE

async spop(key: KeyT, count: int | None = None) AnyStr | set[AnyStr] | None

Remove and return one or multiple random members from a set

Returns:

When called without the count argument the removed member, or None when key does not exist.

When called with the count argument the removed members, or an empty array when key does not exist.

Redis command documentation: SPOP

async srandmember(key: KeyT, count: int | None = None) AnyStr | set[AnyStr] | None

Get one or multiple random members from a set

Returns:

without the additional count argument, the command returns a randomly selected element, or None when key does not exist.

When the additional count argument is passed, the command returns elements, or an empty set when key does not exist.

Redis command documentation: SRANDMEMBER

async srem(key: KeyT, members: Parameters[ValueT]) int

Remove one or more members from a set

Returns:

the number of members that were removed from the set, not including non existing members.

Redis command documentation: SREM

async sscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, set[AnyStr]]

Incrementally returns subsets of elements in a set. Also returns a cursor pointing to the scan position.

Parameters:
  • match – is for filtering the keys by pattern

  • count – is for hint the minimum number of returns

Redis command documentation: SSCAN

async sunion(keys: Parameters[KeyT]) Set[AnyStr]

Add multiple sets

Returns:

members of the resulting set.

Redis command documentation: SUNION

async sunionstore(keys: Parameters[KeyT], destination: KeyT) int

Add multiple sets and store the resulting set in a key

Returns:

the number of elements in the resulting set.

Redis command documentation: SUNIONSTORE

async bzmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) Tuple[AnyStr, Tuple[ScoredMember, ...]] | None

Remove and return members with scores in a sorted set or block until one is available

Returns:

  • A `None` when no element could be popped.

  • A tuple of (name of key, popped (member, score) pairs)

Redis command documentation: BZMPOP

Compatibility:

Added in version 3.0.0.

async bzpopmax(keys: Parameters[KeyT], timeout: int | float) Tuple[AnyStr, AnyStr, float] | None

Remove and return the member with the highest score from one or more sorted sets, or block until one is available.

Returns:

A triplet with the first element being the name of the key where a member was popped, the second element is the popped member itself, and the third element is the score of the popped element.

Redis command documentation: BZPOPMAX

async bzpopmin(keys: Parameters[KeyT], timeout: int | float) Tuple[AnyStr, AnyStr, float] | None

Remove and return the member with the lowest score from one or more sorted sets, or block until one is available

Returns:

A triplet with the first element being the name of the key where a member was popped, the second element is the popped member itself, and the third element is the score of the popped element.

Redis command documentation: BZPOPMIN

async zadd(key: KeyT, member_scores: Mapping[StringT, int | float], condition: Literal[PureToken.NX, PureToken.XX] | None = None, comparison: Literal[PureToken.GT, PureToken.LT] | None = None, change: bool | None = None, increment: bool | None = None) int | float | None

Add one or more members to a sorted set, or update its score if it already exists

Returns:

  • When used without optional arguments, the number of elements added to the sorted set (excluding score updates).

  • If the change option is specified, the number of elements that were changed (added or updated).

  • If condition is specified, the new score of member (a double precision floating point number) represented as string

  • None if the operation is aborted

Redis command documentation: ZADD

Compatibility:

async zcard(key: KeyT) int

Get the number of members in a sorted set

Returns:

the cardinality (number of elements) of the sorted set, or 0 if the key does not exist

Redis command documentation: ZCARD

async zcount(key: KeyT, min_: ValueT, max_: ValueT) int

Count the members in a sorted set with scores within the given values

Returns:

the number of elements in the specified score range.

Redis command documentation: ZCOUNT

async zdiff(keys: Parameters[KeyT], withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Subtract multiple sorted sets

Returns:

the result of the difference (optionally with their scores, in case the withscores option is given).

Redis command documentation: ZDIFF

Compatibility:

async zdiffstore(keys: Parameters[KeyT], destination: KeyT) int

Subtract multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZDIFFSTORE

Compatibility:

async zincrby(key: KeyT, member: ValueT, increment: int) float

Increment the score of a member in a sorted set

Returns:

the new score of member

Redis command documentation: ZINCRBY

async zinter(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None, withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Intersect multiple sorted sets

Returns:

the result of intersection (optionally with their scores, in case the withscores option is given).

Redis command documentation: ZINTER

Compatibility:

async zintercard(keys: Parameters[KeyT], limit: int | None = None) int

Intersect multiple sorted sets and return the cardinality of the result

Returns:

The number of elements in the resulting intersection.

Redis command documentation: ZINTERCARD

Compatibility:

Added in version 3.0.0.

async zinterstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None) int

Intersect multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZINTERSTORE

async zlexcount(key: KeyT, min_: ValueT, max_: ValueT) int

Count the number of members in a sorted set between a given lexicographical range

Returns:

the number of elements in the specified score range.

Redis command documentation: ZLEXCOUNT

Hint

Supports client side caching

async zmpop(keys: Parameters[KeyT], where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) Tuple[AnyStr, Tuple[ScoredMember, ...]] | None

Remove and return members with scores in a sorted set

Returns:

A tuple of (name of key, popped (member, score) pairs)

Redis command documentation: ZMPOP

Compatibility:

Added in version 3.0.0.

async zmscore(key: KeyT, members: Parameters[ValueT]) Tuple[float | None, ...]

Get the score associated with the given members in a sorted set

Returns:

scores or None associated with the specified members values (a double precision floating point number), represented as strings

Redis command documentation: ZMSCORE

Compatibility:

Hint

Supports client side caching

async zpopmax(key: KeyT, count: int | None = None) ScoredMember | tuple[ScoredMember, ...] | None

Remove and return members with the highest scores in a sorted set

Returns:

popped elements and scores.

Redis command documentation: ZPOPMAX

async zpopmin(key: KeyT, count: int | None = None) ScoredMember | tuple[ScoredMember, ...] | None

Remove and return members with the lowest scores in a sorted set

Returns:

popped elements and scores.

Redis command documentation: ZPOPMIN

async zrandmember(key: KeyT, count: int | None = None, withscores: bool | None = None) AnyStr | list[AnyStr] | tuple[ScoredMember, ...] | None

Get one or multiple random elements from a sorted set

Returns:

without count, the command returns a randomly selected element, or None when key does not exist.

If count is passed the command returns the elements, or an empty tuple when key does not exist.

If withscores argument is used, the return is a list elements and their scores from the sorted set.

Redis command documentation: ZRANDMEMBER

Compatibility:

async zrange(key: KeyT, min_: int | ValueT, max_: int | ValueT, sortby: Literal[PureToken.BYSCORE, PureToken.BYLEX] | None = None, rev: bool | None = None, offset: int | None = None, count: int | None = None, withscores: bool | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set

Returns:

elements in the specified range (optionally with their scores, in case withscores is given).

Redis command documentation: ZRANGE

Compatibility:

Hint

Supports client side caching

async zrangebylex(key: KeyT, min_: ValueT, max_: ValueT, offset: int | None = None, count: int | None = None) tuple[AnyStr, ...]

Return a range of members in a sorted set, by lexicographical range

Returns:

elements in the specified score range.

Redis command documentation: ZRANGEBYLEX

Hint

Supports client side caching

async zrangebyscore(key: KeyT, min_: int | float, max_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by score

Returns:

elements in the specified score range (optionally with their scores).

Redis command documentation: ZRANGEBYSCORE

Hint

Supports client side caching

async zrangestore(dst: KeyT, src: KeyT, min_: int | ValueT, max_: int | ValueT, sortby: Literal[PureToken.BYSCORE, PureToken.BYLEX] | None = None, rev: bool | None = None, offset: int | None = None, count: int | None = None) int

Store a range of members from sorted set into another key

Returns:

the number of elements in the resulting sorted set

Redis command documentation: ZRANGESTORE

Compatibility:

async zrank(key: KeyT, member: ValueT, withscore: bool | None = None) int | tuple[int, float] | None

Determine the index of a member in a sorted set

Returns:

the rank of member. If withscore is True the return is a tuple of (rank, score).

Redis command documentation: ZRANK

Compatibility:

Hint

Supports client side caching

async zrem(key: KeyT, members: Parameters[ValueT]) int

Remove one or more members from a sorted set

Returns:

The number of members removed from the sorted set, not including non existing members.

Redis command documentation: ZREM

async zremrangebylex(key: KeyT, min_: ValueT, max_: ValueT) int

Remove all members in a sorted set between the given lexicographical range

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYLEX

async zremrangebyrank(key: KeyT, start: int, stop: int) int

Remove all members in a sorted set within the given indexes

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYRANK

async zremrangebyscore(key: KeyT, min_: int | float, max_: int | float) int

Remove all members in a sorted set within the given scores

Returns:

the number of elements removed.

Redis command documentation: ZREMRANGEBYSCORE

async zrevrange(key: KeyT, start: int, stop: int, withscores: bool | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by index, with scores ordered from high to low

Returns:

elements in the specified range (optionally with their scores).

Redis command documentation: ZREVRANGE

Hint

Supports client side caching

async zrevrangebylex(key: KeyT, max_: ValueT, min_: ValueT, offset: int | None = None, count: int | None = None) tuple[AnyStr, ...]

Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.

Returns:

elements in the specified score range

Redis command documentation: ZREVRANGEBYLEX

Hint

Supports client side caching

async zrevrangebyscore(key: KeyT, max_: int | float, min_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) tuple[AnyStr | ScoredMember, ...]

Return a range of members in a sorted set, by score, with scores ordered from high to low

Returns:

elements in the specified score range (optionally with their scores)

Redis command documentation: ZREVRANGEBYSCORE

Hint

Supports client side caching

async zrevrank(key: KeyT, member: ValueT, withscore: bool | None = None) int | tuple[int, float] | None

Determine the index of a member in a sorted set, with scores ordered from high to low

Returns:

the rank of member. If withscore is True the return is a tuple of (rank, score).

Redis command documentation: ZREVRANK

Compatibility:

Hint

Supports client side caching

async zscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) tuple[int, tuple[ScoredMember, ...]]

Incrementally iterate sorted sets elements and associated scores

Redis command documentation: ZSCAN

async zscore(key: KeyT, member: ValueT) float | None

Get the score associated with the given member in a sorted set

Returns:

the score of member (a double precision floating point number), represented as string or None if the member doesn’t exist.

Redis command documentation: ZSCORE

Hint

Supports client side caching

async zunion(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None, withscores: bool | None = None) Tuple[AnyStr | ScoredMember, ...]

Add multiple sorted sets

Returns:

the result of union (optionally with their scores, in case withscores is given).

Redis command documentation: ZUNION

Compatibility:

async zunionstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None) int

Add multiple sorted sets and store the resulting sorted set in a new key

Returns:

the number of elements in the resulting sorted set at destination.

Redis command documentation: ZUNIONSTORE

async geoadd(key: KeyT, longitude_latitude_members: Parameters[Tuple[int | float, int | float, ValueT]], condition: Literal[PureToken.NX, PureToken.XX] | None = None, change: bool | None = None) int

Add one or more geospatial items in the geospatial index represented using a sorted set

Returns:

Number of elements added. If change is True the return is the number of elements that were changed.

Redis command documentation: GEOADD

Compatibility:

async geodist(key: KeyT, member1: StringT, member2: StringT, unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None) float | None

Returns the distance between two members of a geospatial index

Returns:

Distance in the unit specified by unit

Redis command documentation: GEODIST

async geohash(key: KeyT, members: Parameters[ValueT]) Tuple[AnyStr, ...]

Returns members of a geospatial index as standard geohash strings

Redis command documentation: GEOHASH

async geopos(key: KeyT, members: Parameters[ValueT]) Tuple[GeoCoordinates | None, ...]

Returns longitude and latitude of members of a geospatial index

Returns:

pairs of longitude/latitudes. Missing members are represented by None entries.

Redis command documentation: GEOPOS

async georadius(key: KeyT, longitude: int | float, latitude: int | float, radius: int | float, unit: Literal[PureToken.FT, PureToken.KM, PureToken.M, PureToken.MI], *, withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None, count: int | None = None, any_: bool | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, store: KeyT | None = None, storedist: KeyT | None = None) int | tuple[AnyStr | GeoSearchResult, ...]

Query a geospatial index to fetch members within the borders of the area specified with center location at longitude and latitude and the maximum distance from the center (radius).

Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

  • If a key for store or storedist is provided, the return is the count of places stored.

Redis command documentation: GEORADIUS

Compatibility:

async georadiusbymember(key: KeyT, member: ValueT, radius: int | float, unit: Literal[PureToken.FT, PureToken.KM, PureToken.M, PureToken.MI], withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None, count: int | None = None, any_: bool | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, store: KeyT | None = None, storedist: KeyT | None = None) int | tuple[AnyStr | GeoSearchResult, ...]

This command is exactly like georadius() with the sole difference that instead of searching from a coordinate, it searches from a member already existing in the index.

Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

  • If a key for store or storedist is provided, the return is the count of places stored.

Redis command documentation: GEORADIUSBYMEMBER

async geosearch(key: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, width: int | float | None = None, height: int | float | None = None, box_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, count: int | None = None, any_: bool | None = None, withcoord: bool | None = None, withdist: bool | None = None, withhash: bool | None = None) int | tuple[AnyStr | GeoSearchResult, ...]
Returns:

  • If no with{coord,dist,hash} options are provided the return is simply the names of places matched (optionally ordered if order is provided).

  • If any of the with{coord,dist,hash} options are set each result entry contains (name, distance, geohash, coordinate pair)`

Redis command documentation: GEOSEARCH

Compatibility:

async geosearchstore(destination: KeyT, source: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, width: int | float | None = None, height: int | float | None = None, box_unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None, order: Literal[PureToken.ASC, PureToken.DESC] | None = None, count: int | None = None, any_: bool | None = None, storedist: bool | None = None) int
Returns:

The number of elements stored in the resulting set

Redis command documentation: GEOSEARCHSTORE

Compatibility:

async eval(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Execute the Lua script with the key names and argument values in keys and args.

Returns:

The result of the script as redis returns it

Redis command documentation: EVAL

async eval_ro(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of eval() that cannot execute commands that modify data.

Returns:

The result of the script as redis returns it

Redis command documentation: EVAL_RO

Compatibility:

Added in version 3.0.0.

async evalsha(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Execute the Lua script cached by it’s sha ref with the key names and argument values in keys and args. Evaluate a script from the server’s cache by its sha1 digest.

Returns:

The result of the script as redis returns it

Redis command documentation: EVALSHA

async evalsha_ro(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of evalsha() that cannot execute commands that modify data.

Returns:

The result of the script as redis returns it

Redis command documentation: EVALSHA_RO

Compatibility:

Added in version 3.0.0.

async fcall(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Invoke a function

Redis command documentation: FCALL

Compatibility:

Added in version 3.1.0.

async fcall_ro(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) ResponseType

Read-only variant of fcall()

Redis command documentation: FCALL_RO

Compatibility:

Added in version 3.1.0.

async function_delete(library_name: StringT) bool

Delete a library and all its functions.

Redis command documentation: FUNCTION DELETE

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async function_dump() bytes

Dump all functions into a serialized binary payload

Redis command documentation: FUNCTION DUMP

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async function_flush(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Delete all functions

Redis command documentation: FUNCTION FLUSH

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async function_kill() bool

Kill the function currently in execution.

Redis command documentation: FUNCTION KILL

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on all primaries and return the first response that is not an error

async function_list(libraryname: StringT | None = None, withcode: bool | None = None) Mapping[AnyStr, LibraryDefinition]

List information about the functions registered under libraryname

Redis command documentation: FUNCTION LIST

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async function_load(function_code: StringT, replace: bool | None = None) AnyStr

Load a library of functions.

Redis command documentation: FUNCTION LOAD

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async function_restore(serialized_value: bytes, policy: Literal[PureToken.FLUSH, PureToken.APPEND, PureToken.REPLACE] | None = None) bool

Restore all the functions on the given payload

Redis command documentation: FUNCTION RESTORE

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async function_stats() dict[AnyStr, AnyStr | dict[AnyStr, dict[AnyStr, ResponsePrimitive]]]

Return information about the function currently running

Redis command documentation: FUNCTION STATS

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async script_debug(mode: Literal[PureToken.NO, PureToken.SYNC, PureToken.YES]) bool

Set the debug mode for executed scripts

Raises:

NotImplementedError

Redis command documentation: SCRIPT DEBUG

Added in version 3.0.0.

async script_exists(sha1s: Parameters[StringT]) Tuple[bool, ...]

Check if a script exists in the script cache by specifying the SHAs of each script as sha1s.

Returns:

tuple of boolean values indicating if each script exists in the cache.

Redis command documentation: SCRIPT EXISTS

Cluster note

The command will be run on all primaries and return the logical AND of all responses

async script_flush(sync_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Flushes all scripts from the script cache

Redis command documentation: SCRIPT FLUSH

Compatibility:

Cluster note

The command will be run on all nodes and return success if all shards responded True

async script_kill() bool

Kills the currently executing Lua script

Redis command documentation: SCRIPT KILL

Cluster note

The command will be run on all primaries and return the first response that is not an error

async script_load(script: StringT) AnyStr

Loads a Lua script into the script cache.

Returns:

The SHA1 digest of the script added into the script cache

Redis command documentation: SCRIPT LOAD

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async publish(channel: StringT, message: ValueT) int

Publish message on channel.

Returns:

the number of subscribers the message was delivered to.

Redis command documentation: PUBLISH

async pubsub_channels(pattern: StringT | None = None) set[AnyStr]

Return channels that have at least one subscriber

Redis command documentation: PUBSUB CHANNELS

Cluster note

The command will be run on all nodes and return the union of the results

async pubsub_numpat() int

Get the count of unique patterns pattern subscriptions

Returns:

the number of patterns all the clients are subscribed to.

Redis command documentation: PUBSUB NUMPAT

async pubsub_numsub(*channels: StringT) dict[AnyStr, int]

Get the count of subscribers for channels

Returns:

Mapping of channels to number of subscribers per channel

Redis command documentation: PUBSUB NUMSUB

Cluster note

The command will be run on all nodes and return the merged mapping

async pubsub_shardchannels(pattern: StringT | None = None) set[AnyStr]

Return shard channels that have at least one subscriber

Redis command documentation: PUBSUB SHARDCHANNELS

Compatibility:

Added in version 3.6.0.

Cluster note

The command will be run on all nodes and return the union of the results

async pubsub_shardnumsub(*channels: StringT) dict[AnyStr, int]

Get the count of subscribers for shard channels

Returns:

Ordered mapping of shard channels to number of subscribers per channel

Redis command documentation: PUBSUB SHARDNUMSUB

Cluster note

The command will be run on all nodes and return the merged mapping

async spublish(channel: StringT, message: ValueT) int

Publish message on shard channel.

Returns:

the number of shard subscribers the message was delivered to.

Note

The number only represents subscribers listening to the exact node the message was published to, which means that if a subscriber is listening on a replica node, it will not be included in the count.

Redis command documentation: SPUBLISH

Compatibility:

Added in version 3.6.0.

async xack(key: KeyT, group: StringT, identifiers: Parameters[ValueT]) int

Marks a pending message as correctly processed, effectively removing it from the pending entries list of the consumer group.

Returns:

number of messages successfully acknowledged, that is, the IDs we were actually able to resolve in the PEL.

Redis command documentation: XACK

async xadd(key: KeyT, field_values: Mapping[StringT, ValueT], identifier: ValueT | None = None, nomkstream: bool | None = None, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID] | None = None, threshold: int | None = None, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None) AnyStr | None

Appends a new entry to a stream

Returns:

The identifier of the added entry. The identifier is the one auto-generated if * is passed as identifier, otherwise the it justs returns the same identifier specified

Returns None when used with nomkstream and the key doesn’t exist.

Redis command documentation: XADD

Compatibility:

async xautoclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | timedelta, start: ValueT, count: int | None = None, justid: bool | None = None) tuple[AnyStr, tuple[AnyStr, ...]] | tuple[AnyStr, tuple[StreamEntry, ...], tuple[AnyStr, ...]]

Changes (or acquires) ownership of messages in a consumer group, as if the messages were delivered to the specified consumer.

Returns:

A dictionary with keys as stream identifiers and values containing all the successfully claimed messages in the same format as xrange()

Redis command documentation: XAUTOCLAIM

Compatibility:

Added in version 3.0.0.

async xclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | datetime.timedelta, identifiers: Parameters[ValueT], idle: int | datetime.timedelta | None = None, time: int | datetime.datetime | None = None, retrycount: int | None = None, force: bool | None = None, justid: bool | None = None, lastid: ValueT | None = None) Tuple[AnyStr, ...] | Tuple[StreamEntry, ...]

Changes (or acquires) ownership of a message in a consumer group, as if the message was delivered to the specified consumer.

Redis command documentation: XCLAIM

async xdel(key: KeyT, identifiers: Parameters[ValueT]) int

Redis command documentation: XDEL

async xgroup_create(key: KeyT, groupname: StringT, identifier: ValueT | None = None, mkstream: bool | None = None, entriesread: int | None = None) bool

Create a consumer group.

Redis command documentation: XGROUP CREATE

Compatibility:

async xgroup_createconsumer(key: KeyT, groupname: StringT, consumername: StringT) bool

Create a consumer in a consumer group.

Returns:

whether the consumer was created

Redis command documentation: XGROUP CREATECONSUMER

Compatibility:

Added in version 3.0.0.

async xgroup_delconsumer(key: KeyT, groupname: StringT, consumername: StringT) int

Delete a consumer from a consumer group.

Returns:

The number of pending messages that the consumer had before it was deleted

Redis command documentation: XGROUP DELCONSUMER

Added in version 3.0.0.

async xgroup_destroy(key: KeyT, groupname: StringT) int

Destroy a consumer group.

Returns:

The number of destroyed consumer groups

Redis command documentation: XGROUP DESTROY

async xgroup_setid(key: KeyT, groupname: StringT, identifier: ValueT | None = None, entriesread: int | None = None) bool

Set a consumer group to an arbitrary last delivered ID value.

Redis command documentation: XGROUP SETID

Compatibility:

Added in version 3.0.0.

async xinfo_consumers(key: KeyT, groupname: StringT) tuple[dict[AnyStr, AnyStr], ...]

Get list of all consumers that belong to groupname of the stream stored at key

Redis command documentation: XINFO CONSUMERS

async xinfo_groups(key: KeyT) tuple[dict[AnyStr, AnyStr], ...]

Get list of all consumers groups of the stream stored at key

Redis command documentation: XINFO GROUPS

async xinfo_stream(key: KeyT, full: bool | None = None, count: int | None = None) StreamInfo

Get information about the stream stored at key

Parameters:

Redis command documentation: XINFO STREAM

async xlen(key: KeyT) int

Redis command documentation: XLEN

async xpending(key: KeyT, group: StringT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None, idle: int | None = None, consumer: StringT | None = None) tuple[StreamPendingExt, ...] | StreamPending

Return information and entries from a stream consumer group pending entries list, that are messages fetched but never acknowledged.

Redis command documentation: XPENDING

Compatibility:

async xrange(key: KeyT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None) tuple[StreamEntry, ...]

Return a range of elements in a stream, with IDs matching the specified IDs interval

Redis command documentation: XRANGE

async xread(streams: Mapping[ValueT, ValueT], count: int | None = None, block: int | timedelta | None = None) dict[AnyStr, tuple[StreamEntry, ...]] | None

Return never seen elements in multiple streams, with IDs greater than the ones reported by the caller for each stream. Can block.

Returns:

Mapping of streams to stream entries. Field and values are guaranteed to be reported in the same order they were added by xadd().

When block is used, on timeout None is returned.

Redis command documentation: XREAD

async xreadgroup(group: StringT, consumer: StringT, streams: Mapping[ValueT, ValueT], count: int | None = None, block: int | timedelta | None = None, noack: bool | None = None) dict[AnyStr, tuple[StreamEntry, ...]] | None

Redis command documentation: XREADGROUP

async xrevrange(key: KeyT, end: ValueT | None = None, start: ValueT | None = None, count: int | None = None) tuple[StreamEntry, ...]

Return a range of elements in a stream, with IDs matching the specified IDs interval, in reverse order (from greater to smaller IDs) compared to XRANGE

Redis command documentation: XREVRANGE

async xtrim(key: KeyT, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID], threshold: int, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None) int

Redis command documentation: XTRIM

Compatibility:

async acl_cat(categoryname: StringT | None = None) tuple[AnyStr, ...]

List the ACL categories or the commands inside a category

Returns:

a list of ACL categories or a list of commands inside a given category. The command may return an error if an invalid category name is given as argument.

Redis command documentation: ACL CAT

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_deluser(usernames: Parameters[StringT]) int

Remove the specified ACL users and the associated rules

Returns:

The number of users that were deleted. This number will not always match the number of arguments since certain users may not exist.

Redis command documentation: ACL DELUSER

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async acl_dryrun(username: StringT, command: StringT, *args: ValueT) bool

Returns whether the user can execute the given command without executing the command.

Redis command documentation: ACL DRYRUN

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_genpass(bits: int | None = None) AnyStr

Generate a pseudorandom secure password to use for ACL users

Returns:

by default 64 bytes string representing 256 bits of pseudorandom data. Otherwise if an argument if needed, the output string length is the number of specified bits (rounded to the next multiple of 4) divided by 4.

Redis command documentation: ACL GENPASS

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_getuser(username: StringT) dict[AnyStr, list[AnyStr] | set[AnyStr]]

Get the rules for a specific ACL user

Redis command documentation: ACL GETUSER

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_list() tuple[AnyStr, ...]

List the current ACL rules in ACL config file format

Redis command documentation: ACL LIST

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_load() bool

Reload the ACLs from the configured ACL file

Returns:

True if successful. The command may fail with an error for several reasons:

  • if the file is not readable

  • if there is an error inside the file, and in such case the error will be reported to the user in the error.

  • Finally the command will fail if the server is not configured to use an external ACL file.

Redis command documentation: ACL LOAD

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async acl_log(count: int | None = None, reset: bool | None = None) bool | tuple[dict[AnyStr, ResponsePrimitive] | None, ...]

List latest events denied because of ACLs in place

Returns:

When called to show security events a list of ACL security events. When called with RESET True if the security log was cleared.

Redis command documentation: ACL LOG

Compatibility:

Added in version 3.0.0.

async acl_save() bool

Save the current ACL rules in the configured ACL file

Returns:

True if successful. The command may fail with an error for several reasons: - if the file cannot be written, or - if the server is not configured to use an external ACL file.

Redis command documentation: ACL SAVE

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async acl_setuser(username: StringT, *rules: StringT) bool

Modify or create the rules for a specific ACL user

Returns:

True if successful. If the rules contain errors, the error is returned.

Redis command documentation: ACL SETUSER

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async acl_users() tuple[AnyStr, ...]

List the username of all the configured ACL rules

Redis command documentation: ACL USERS

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async acl_whoami() AnyStr

Return the name of the user associated to the current connection

Returns:

the username of the current connection.

Redis command documentation: ACL WHOAMI

Compatibility:

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async command() dict[str, Command]

Get Redis command details

Returns:

Mapping of command details. Commands are returned in random order.

Redis command documentation: COMMAND

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async command_count() int

Get total number of Redis commands

Returns:

number of commands returned by COMMAND

Redis command documentation: COMMAND COUNT

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async command_docs(*command_names: StringT) dict[AnyStr, dict[AnyStr, ResponseType]]

Mapping of commands to a dictionary containing it’s documentation

Redis command documentation: COMMAND DOCS

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async command_getkeys(command: StringT, arguments: Parameters[ValueT]) Tuple[AnyStr, ...]

Extract keys given a full Redis command

Returns:

Keys from your command.

Redis command documentation: COMMAND GETKEYS

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async command_getkeysandflags(command: StringT, arguments: Parameters[ValueT]) Dict[AnyStr, Set[AnyStr]]

Extract keys from a full Redis command and their usage flags.

Returns:

Mapping of keys from your command to flags

Redis command documentation: COMMAND GETKEYSANDFLAGS

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async command_info(*command_names: StringT) dict[str, Command]

Get specific Redis command details, or all when no argument is given.

Returns:

mapping of command details.

Redis command documentation: COMMAND INFO

Added in version 3.0.0.

Cluster note

The command will be run on a random node

async command_list(module: StringT | None = None, aclcat: StringT | None = None, pattern: StringT | None = None) set[AnyStr]

Get an array of Redis command names

Redis command documentation: COMMAND LIST

Compatibility:

Added in version 3.1.0.

Cluster note

The command will be run on a random node

async config_get(parameters: Parameters[StringT]) Dict[AnyStr, AnyStr]

Get the values of configuration parameters

Redis command documentation: CONFIG GET

async config_resetstat() bool

Resets runtime statistics

Redis command documentation: CONFIG RESETSTAT

Cluster note

The command will be run on all nodes and return success if all shards responded True

async config_rewrite() bool

Rewrites config file with the minimal change to reflect running config

Redis command documentation: CONFIG REWRITE

async config_set(parameter_values: Mapping[StringT, ValueT]) bool

Sets configuration parameters to the given values

Redis command documentation: CONFIG SET

Cluster note

The command will be run on all nodes and return success if all shards responded True

async dbsize() int

Returns the number of keys in the current database

Redis command documentation: DBSIZE

async debug_object(key: KeyT) dict[str, str | int]

Returns version specific meta information about a given key

Redis command documentation: DEBUG OBJECT

async failover(host: StringT | None = None, port: int | None = None, force: bool | None = None, abort: bool | None = None, timeout: int | timedelta | None = None) bool

Start a coordinated failover between this server and one of its replicas.

Returns:

True if the command was accepted and a coordinated failover is in progress.

Redis command documentation: FAILOVER

Compatibility:

Added in version 3.0.0.

async flushall(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Deletes all keys in all databases on the current host

Redis command documentation: FLUSHALL

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async flushdb(async_: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) bool

Deletes all keys in the current database

Redis command documentation: FLUSHDB

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async info(*sections: StringT) dict[str, ResponseType]

Get information and statistics about the server

The sections option can be used to select a specific section(s) of information.

Redis command documentation: INFO

Cluster note

The command will be run on a random node

async lastsave() datetime

Get the time of the last successful save to disk

Redis command documentation: LASTSAVE

async latency_doctor() AnyStr

Return a human readable latency analysis report.

Redis command documentation: LATENCY DOCTOR

Added in version 3.0.0.

async latency_graph(event: StringT) AnyStr

Return a latency graph for the event.

Redis command documentation: LATENCY GRAPH

Added in version 3.0.0.

async latency_histogram(*commands: StringT) dict[AnyStr, dict[AnyStr, ValueT]]

Return the cumulative distribution of latencies of a subset of commands or all.

Redis command documentation: LATENCY HISTOGRAM

Compatibility:

Added in version 3.2.0.

async latency_history(event: StringT) tuple[list[int], ...]

Return timestamp-latency samples for the event.

Returns:

The command returns a tuple where each element is a tuple representing the timestamp and the latency of the event.

Redis command documentation: LATENCY HISTORY

Added in version 3.0.0.

async latency_latest() dict[AnyStr, tuple[int, int, int]]

Return the latest latency samples for all events.

Returns:

Mapping of event name to (timestamp, latest, all-time) triplet

Redis command documentation: LATENCY LATEST

Added in version 3.0.0.

async latency_reset(*events: StringT) int

Reset latency data for one or more events.

Returns:

the number of event time series that were reset.

Redis command documentation: LATENCY RESET

Added in version 3.0.0.

async lolwut(version: int | None = None) AnyStr

Get the Redis version and a piece of generative computer art

Redis command documentation: LOLWUT

async memory_doctor() AnyStr

Outputs memory problems report

Redis command documentation: MEMORY DOCTOR

Added in version 3.0.0.

async memory_malloc_stats() AnyStr

Show allocator internal stats :return: the memory allocator’s internal statistics report

Redis command documentation: MEMORY MALLOC-STATS

Added in version 3.0.0.

async memory_purge() bool

Ask the allocator to release memory

Redis command documentation: MEMORY PURGE

Added in version 3.0.0.

Cluster note

The command will be run on all nodes and return success if all shards responded True

async memory_stats() dict[AnyStr, ValueT]

Show memory usage details :return: mapping of memory usage metrics and their values

Redis command documentation: MEMORY STATS

Added in version 3.0.0.

async memory_usage(key: KeyT, *, samples: int | None = None) int | None

Estimate the memory usage of a key

Returns:

the memory usage in bytes, or None when the key does not exist.

Redis command documentation: MEMORY USAGE

Added in version 3.0.0.

async module_list() tuple[dict[AnyStr, ResponsePrimitive], ...]

List all modules loaded by the server

Returns:

The loaded modules with each element represents a module containing a mapping with name and ver

Redis command documentation: MODULE LIST

Added in version 3.2.0.

Cluster note

The command will be run on a random node

async module_load(path: StringT, *args: str | bytes | int | float) bool

Load a module

Redis command documentation: MODULE LOAD

Added in version 3.2.0.

Cluster note

The command will be run on all nodes and return success if all shards responded True

async module_loadex(path: StringT, configs: Dict[StringT, ValueT] | None = None, args: Parameters[ValueT] | None = None) bool

Loads a module from a dynamic library at runtime with configuration directives.

Redis command documentation: MODULE LOADEX

Compatibility:

Added in version 3.4.0.

Cluster note

The command will be run on all nodes and return success if all shards responded True

async module_unload(name: StringT) bool

Unload a module

Redis command documentation: MODULE UNLOAD

Added in version 3.2.0.

Cluster note

The command will be run on all nodes and return success if all shards responded True

async replicaof(host: StringT | None = None, port: int | None = None) bool

Make the server a replica of another instance, or promote it as master.

Redis command documentation: REPLICAOF

Added in version 3.0.0.

async role() RoleInfo

Provides information on the role of a Redis instance in the context of replication, by returning if the instance is currently a master, slave, or sentinel. The command also returns additional information about the state of the replication (if the role is master or slave) or the list of monitored master names (if the role is sentinel).

Redis command documentation: ROLE

async save() bool

Tells the Redis server to save its data to disk, blocking until the save is complete

Redis command documentation: SAVE

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async shutdown(nosave_save: Literal[PureToken.NOSAVE, PureToken.SAVE] | None = None, *, now: bool | None = None, force: bool | None = None, abort: bool | None = None) bool

Stops Redis server

Redis command documentation: SHUTDOWN

Compatibility:

async slaveof(host: StringT | None = None, port: int | None = None) bool

Sets the server to be a replicated slave of the instance identified by the host and port. If called without arguments, the instance is promoted to a master instead.

Redis command documentation: SLAVEOF

async slowlog_get(count: int | None = None) tuple[SlowLogInfo, ...]

Gets the entries from the slowlog. If count is specified, get the most recent count items.

Redis command documentation: SLOWLOG GET

async slowlog_len() int

Gets the number of items in the slowlog

Redis command documentation: SLOWLOG LEN

async slowlog_reset() bool

Removes all items in the slowlog

Redis command documentation: SLOWLOG RESET

async swapdb(index1: int, index2: int) bool

Swaps two Redis databases

Redis command documentation: SWAPDB

Added in version 3.0.0.

async time() datetime

Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).

Redis command documentation: TIME

async asking() bool

Sent by cluster clients after an -ASK redirect

Redis command documentation: ASKING

Added in version 3.0.0.

async cluster_addslots(slots: Parameters[int]) bool

Assign new hash slots to receiving node

Redis command documentation: CLUSTER ADDSLOTS

async cluster_addslotsrange(slots: Parameters[Tuple[int, int]]) bool

Assign new hash slots to receiving node

Redis command documentation: CLUSTER ADDSLOTSRANGE

Compatibility:

Added in version 3.1.1.

async cluster_bumpepoch() AnyStr

Advance the cluster config epoch

Returns:

BUMPED if the epoch was incremented, or STILL if the node already has the greatest config epoch in the cluster.

Redis command documentation: CLUSTER BUMPEPOCH

Added in version 3.0.0.

async cluster_count_failure_reports(node_id: StringT) int

Return the number of failure reports active for a given node

Redis command documentation: CLUSTER COUNT-FAILURE-REPORTS

Cluster note

The command will be run on a random node

async cluster_countkeysinslot(slot: int) int

Return the number of local keys in the specified hash slot

Redis command documentation: CLUSTER COUNTKEYSINSLOT

Cluster note

The command will be run on one or more nodes based on the slots provided

async cluster_delslots(slots: Parameters[int]) bool

Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there

Redis command documentation: CLUSTER DELSLOTS

Cluster note

The command will be run on one or more nodes based on the slots provided

async cluster_delslotsrange(slots: Parameters[Tuple[int, int]]) bool

Set hash slots as unbound in receiving node

Redis command documentation: CLUSTER DELSLOTSRANGE

Compatibility:

Added in version 3.1.1.

Cluster note

The command will be run on one or more nodes based on the slots provided

async cluster_failover(options: Literal[PureToken.FORCE, PureToken.TAKEOVER] | None = None) bool

Forces a replica to perform a manual failover of its master.

Redis command documentation: CLUSTER FAILOVER

async cluster_flushslots() bool

Delete a node’s own slots information

Redis command documentation: CLUSTER FLUSHSLOTS

Added in version 3.0.0.

async cluster_forget(node_id: StringT) bool

remove a node via its node ID from the set of known nodes of the Redis Cluster node receiving the command

Redis command documentation: CLUSTER FORGET

async cluster_getkeysinslot(slot: int, count: int) tuple[AnyStr, ...]

Return local key names in the specified hash slot

Returns:

count key names

Redis command documentation: CLUSTER GETKEYSINSLOT

Added in version 3.0.0.

Cluster note

The command will be run on one or more nodes based on the slots provided

async cluster_info() dict[str, str]

Provides info about Redis Cluster node state

Redis command documentation: CLUSTER INFO

Cluster note

The command will be run on a random node

async cluster_keyslot(key: KeyT) int

Returns the hash slot of the specified key

Redis command documentation: CLUSTER KEYSLOT

Cluster note

The command will be run on a random node

Returns a list of all TCP links to and from peer nodes in cluster

Returns:

A map of maps where each map contains various attributes and their values of a cluster link.

Redis command documentation: CLUSTER LINKS

Compatibility:

Added in version 3.1.1.

async cluster_meet(ip: StringT, port: int, cluster_bus_port: int | None = None) bool

Force a node cluster to handshake with another node.

Redis command documentation: CLUSTER MEET

Cluster note

The command will be run on a random node

async cluster_myid() AnyStr

Return the node id

Redis command documentation: CLUSTER MYID

Added in version 3.1.1.

async cluster_nodes() list[ClusterNodeDetail]

Get Cluster config for the node

Redis command documentation: CLUSTER NODES

Cluster note

The command will be run on a random node

async cluster_replicas(node_id: StringT) list[ClusterNodeDetail]

List replica nodes of the specified master node

Redis command documentation: CLUSTER REPLICAS

Cluster note

The command will be run on a random node

async cluster_replicate(node_id: StringT) bool

Reconfigure a node as a replica of the specified master node

Redis command documentation: CLUSTER REPLICATE

async cluster_reset(hard_soft: Literal[PureToken.HARD, PureToken.SOFT] | None = None) bool

Reset a Redis Cluster node

Redis command documentation: CLUSTER RESET

async cluster_saveconfig() bool

Forces the node to save cluster state on disk

Redis command documentation: CLUSTER SAVECONFIG

Cluster note

The command will be run on all nodes and return success if all shards responded True

async cluster_set_config_epoch(config_epoch: int) bool

Set the configuration epoch in a new node

Redis command documentation: CLUSTER SET-CONFIG-EPOCH

async cluster_setslot(slot: int, *, importing: StringT | None = None, migrating: StringT | None = None, node: StringT | None = None, stable: bool | None = None) bool

Bind a hash slot to a specific node

Redis command documentation: CLUSTER SETSLOT

async cluster_shards() list[dict[AnyStr, list[ValueT] | Mapping[AnyStr, ValueT]]]

Get mapping of cluster slots to nodes

Redis command documentation: CLUSTER SHARDS

Compatibility:

Added in version 3.2.0.

Cluster note

The command will be run on a random node

async cluster_slaves(node_id: StringT) list[ClusterNodeDetail]

List replica nodes of the specified master node

Redis command documentation: CLUSTER SLAVES

Cluster note

The command will be run on a random node

async cluster_slots() dict[tuple[int, int], tuple[ClusterNode, ...]]

Get mapping of Cluster slot to nodes

Redis command documentation: CLUSTER SLOTS

Cluster note

The command will be run on a random node

async readonly() bool

Enables read queries for a connection to a cluster replica node

Redis command documentation: READONLY

Added in version 3.2.0.

async readwrite() bool

Disables read queries for a connection to a cluster replica node

Redis command documentation: READWRITE

Added in version 3.2.0.

async auth(password: StringT, username: StringT | None = None) bool

Authenticate to the server

Redis command documentation: AUTH

Compatibility:

Warning

Using auth directly is not recommended. Use the Redis.username and Redis.password arguments when initializing the client to ensure that all connections originating from this client are authenticated before being made available.

Added in version 3.0.0.

async bgrewriteaof() bool

Tell the Redis server to rewrite the AOF file from data in memory

Redis command documentation: BGREWRITEAOF

async bgsave(schedule: bool | None = None) bool

Tells the Redis server to save its data to disk. Unlike save(), this method is asynchronous and returns immediately.

Redis command documentation: BGSAVE

async client_caching(mode: Literal[PureToken.NO, PureToken.YES]) bool

Instruct the server about tracking or not keys in the next request

Redis command documentation: CLIENT CACHING

Compatibility:

Added in version 3.0.0.

async client_getname() AnyStr | None

Returns the current connection name

Returns:

The connection name, or None if no name is set.

Redis command documentation: CLIENT GETNAME

async client_getredir() int

Get tracking notifications redirection client ID if any

Returns:

the ID of the client we are redirecting the notifications to. The command returns -1 if client tracking is not enabled, or 0 if client tracking is enabled but we are not redirecting the notifications to any client.

Redis command documentation: CLIENT GETREDIR

Compatibility:

Added in version 3.0.0.

async client_id() int

Returns the client ID for the current connection

Returns:

The id of the client.

Redis command documentation: CLIENT ID

Added in version 3.0.0.

async client_info() ClientInfo

Returns information about the current client connection.

Redis command documentation: CLIENT INFO

Compatibility:

Added in version 3.0.0.

async client_kill(ip_port: StringT | None = None, identifier: int | None = None, type_: Literal[PureToken.NORMAL, PureToken.MASTER, PureToken.SLAVE, PureToken.REPLICA, PureToken.PUBSUB] | None = None, user: StringT | None = None, addr: StringT | None = None, laddr: StringT | None = None, skipme: bool | None = None) int | bool

Disconnects the client at ip_port

Returns:

True if the connection exists and has been closed or the number of clients killed.

Redis command documentation: CLIENT KILL

Compatibility:

async client_list(type_: Literal[PureToken.MASTER, PureToken.NORMAL, PureToken.PUBSUB, PureToken.REPLICA] | None = None, identifiers: Parameters[int] | None = None) Tuple[ClientInfo, ...]

Get client connections

Returns:

a tuple of dictionaries containing client fields

Redis command documentation: CLIENT LIST

Compatibility:

async client_no_evict(enabled: Literal[PureToken.ON, PureToken.OFF]) bool

Set client eviction mode for the current connection

Redis command documentation: CLIENT NO-EVICT

Compatibility:

Warning

Using client_no_evict directly is not recommended. Use Redis.noevict argument when initializing the client to ensure that all connections originating from this client use the desired mode

Added in version 3.2.0.

async client_no_touch(enabled: Literal[PureToken.OFF, PureToken.ON]) bool

Controls whether commands sent by the client will alter the LRU/LFU of the keys they access.

Redis command documentation: CLIENT NO-TOUCH

Compatibility:

Warning

Using client_no_touch directly is not recommended. Use Redis.notouch argument when initializing the client to ensure that all connections originating from this client use the desired mode

Added in version 4.12.0.

async client_pause(timeout: int, mode: Literal[PureToken.WRITE, PureToken.ALL] | None = None) bool

Stop processing commands from clients for some time

Returns:

The command returns True or raises an error if the timeout is invalid.

Redis command documentation: CLIENT PAUSE

Compatibility:

async client_reply(mode: Literal[PureToken.OFF, PureToken.ON, PureToken.SKIP]) bool

Instruct the server whether to reply to commands

Redis command documentation: CLIENT REPLY

Danger

Using client_reply directly is not supported. Use the Redis.noreply argument when initializing the client to ensure that all connections originating from this client disable or enable replies. You can also use the Redis.ignore_replies() context manager to selectively execute certain commands without waiting for a reply

Added in version 3.0.0.

async client_setinfo(lib_name: StringT | None = None, lib_ver: StringT | None = None) bool

Set client or connection specific info

Parameters:
  • lib_name – name of the library

  • lib_ver – version of the library

Redis command documentation: CLIENT SETINFO

Compatibility:

Warning

Using client_setinfo directly is not recommended. Coredis sets the library name and version by default during the handshake phase.Explicitly calling this command will only apply to the connection from the pool that was used to send it and not for subsequent commands

Added in version 4.12.0.

async client_setname(connection_name: StringT) bool

Set the current connection name :return: If the connection name was successfully set.

Redis command documentation: CLIENT SETNAME

Warning

Using client_setname directly is not recommended. Use the Redis.client_name argument when initializing the client to ensure the client name is consistent across all connections originating from the client

async client_tracking(status: Literal[PureToken.OFF, PureToken.ON], *prefixes: StringT, redirect: int | None = None, bcast: bool | None = None, optin: bool | None = None, optout: bool | None = None, noloop: bool | None = None) bool

Enable or disable server assisted client side caching support

Returns:

If the connection was successfully put in tracking mode or if the tracking mode was successfully disabled.

Redis command documentation: CLIENT TRACKING

Compatibility:

Added in version 3.0.0.

async client_trackinginfo() dict[AnyStr, AnyStr | set[AnyStr] | list[AnyStr]]

Return information about server assisted client side caching for the current connection

Returns:

a mapping of tracking information sections and their respective values

Redis command documentation: CLIENT TRACKINGINFO

Compatibility:

Added in version 3.0.0.

async client_unblock(client_id: int, timeout_error: Literal[PureToken.TIMEOUT, PureToken.ERROR] | None = None) bool

Unblock a client blocked in a blocking command from a different connection

Returns:

Whether the client was unblocked

Redis command documentation: CLIENT UNBLOCK

Added in version 3.0.0.

async client_unpause() bool

Resume processing of clients that were paused

Returns:

The command returns `True`

Redis command documentation: CLIENT UNPAUSE

Compatibility:

Added in version 3.0.0.

async echo(message: StringT) AnyStr

Echo the string back from the server

Redis command documentation: ECHO

Cluster note

The command will be run on all nodes and return the response from any shard if all responses are consistent

async hello(protover: int | None = None, username: StringT | None = None, password: StringT | None = None, setname: StringT | None = None) dict[AnyStr, AnyStr]

Handshake with Redis

Returns:

a mapping of server properties.

Redis command documentation: HELLO

Compatibility:

Added in version 3.0.0.

async ping(message: StringT | None = None) AnyStr

Ping the server

Returns:

PONG, when no argument is provided else the message provided

Redis command documentation: PING

Cluster note

The command will be run on all primaries and return the response from any shard if all responses are consistent

async quit() bool

Close the connection

Redis command documentation: QUIT

async reset() None

Reset the connection

Redis command documentation: RESET

Compatibility:

Added in version 3.0.0.

async select(index: int) bool

Change the selected database for the current connection

Redis command documentation: SELECT

Warning

Using select directly is not recommended. Use the db argument when initializing the client to ensure that all connections originating from this client use the desired database number

Added in version 3.0.0.

async sentinel_config_get(name: ValueT) dict[AnyStr, AnyStr]

Get the current value of a global Sentinel configuration parameter. The specified name may be a wildcard, similar to config_get()

Compatibility:

async sentinel_config_set(name: ValueT, value: ValueT) bool

Set the value of a global Sentinel configuration parameter

Compatibility:

async sentinel_failover(service_name: StringT) bool

Force a failover as if the master was not reachable, and without asking for agreement to other Sentinels

async sentinel_flushconfig() bool

Force Sentinel to rewrite its configuration on disk, including the current Sentinel state.

async sentinel_get_master_addr_by_name(service_name: StringT) tuple[str, int] | None

Returns a (host, port) pair for the given service_name

async sentinel_infocache(*nodenames: StringT) dict[AnyStr, dict[int, dict[str, ResponseType]]]

Return cached INFO output from masters and replicas.

async sentinel_master(service_name: StringT) dict[str, int | bool | str]

Returns a dictionary containing the specified masters state.

async sentinel_masters() dict[str, dict[str, int | bool | str]]

Returns a list of dictionaries containing each master’s state.

async sentinel_monitor(name: ValueT, ip: ValueT, port: int, quorum: int) bool

Adds a new master to Sentinel to be monitored

async sentinel_myid() AnyStr

Return the ID of the Sentinel instance Compatibility:

async sentinel_remove(name: ValueT) bool

Removes a master from Sentinel’s monitoring

async sentinel_replicas(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of replicas for service_name

async sentinel_reset(pattern: StringT) int

Reset all the masters with matching name. The pattern argument is a glob-style pattern. The reset process clears any previous state in a master (including a failover in progress), and removes every replica and sentinel already discovered and associated with the master.

async sentinel_sentinels(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of sentinels for service_name

async sentinel_set(name: ValueT, option: ValueT, value: ValueT) bool

Sets Sentinel monitoring parameters for a given master

async sentinel_slaves(service_name: StringT) tuple[dict[str, int | bool | str], ...]

Returns a list of slaves for paramref:service_name

property autocomplete: Autocomplete

Property to access Autocomplete commands.

Added in version 4.12.0.

property bf: BloomFilter

Property to access BloomFilter commands.

Added in version 4.12.0.

property cf: CuckooFilter

Property to access CuckooFilter commands.

Added in version 4.12.0.

property cms: CountMinSketch

Property to access CountMinSketch commands.

Added in version 4.12.0.

property graph: Graph

Property to access Graph commands.

Added in version 4.12.0.

property json: Json

Property to access Json commands.

Added in version 4.12.0.

property num_replicas_per_shard: int

Number of replicas per shard of the cluster determined by initial cluster topology discovery

property search: Search

Property to access Search commands.

Added in version 4.12.0.

property tdigest: TDigest

Property to access TDigest commands.

Added in version 4.12.0.

property timeseries: TimeSeries

Property to access TimeSeries commands.

Added in version 4.12.0.

property topk: TopK

Property to access TopK commands.

Added in version 4.12.0.

Sentinel

coredis.sentinel

class Sentinel(sentinels: Iterable[tuple[str, int]], min_other_sentinels: int = 0, sentinel_kwargs: dict[str, Any] | None = None, decode_responses: bool = False, cache: AbstractCache | None = None, **connection_kwargs: Any)[source]

Example use:

from coredis.sentinel import Sentinel
sentinel = Sentinel([('localhost', 26379)], stream_timeout=0.1)
async def test():
    primary = await sentinel.primary_for('my-instance', stream_timeout=0.1)
    await primary.set('foo', 'bar')
    replica = await sentinel.replica_for('my-instance', stream_timeout=0.1)
    await replica.get('foo')
Changes
  • Added in version 3.10.0: Accept cache parameter to be used with primaries and replicas returned from the sentinel instance.

Parameters:
  • sentinels – is a list of sentinel nodes. Each node is represented by a pair (hostname, port).

  • min_other_sentinels – defined a minimum number of peers for a sentinel. When querying a sentinel, if it doesn’t meet this threshold, responses from that sentinel won’t be considered valid.

  • sentinel_kwargs – is a dictionary of connection arguments used when connecting to sentinel instances. Any argument that can be passed to a normal Redis connection can be specified here. If sentinel_kwargs is not specified, stream_timeout, socket_keepalive, decode_responses and protocol_version options specified in connection_kwargs will be used.

  • cache – If provided the cache will be shared between both primaries and replicas returned by this sentinel.

  • connection_kwargs – are keyword arguments that will be used when establishing a connection to a Redis server (i.e. are passed on to the constructor of Redis for all primary and replicas).

async discover_primary(service_name: str) tuple[str, int][source]

Asks sentinel servers for the Redis primary’s address corresponding to the service labeled service_name.

Returns:

A pair (address, port) or raises PrimaryNotFoundError if no primary is found.

async discover_replicas(service_name: str) list[tuple[str, int]][source]

Returns a list of alive replicas for service service_name

primary_for(service_name: str, *, redis_class: ~typing.Type[~coredis.client.basic.Redis[bytes]] = coredis.client.basic.Redis[typing.Any], connection_pool_class: ~typing.Type[~coredis.sentinel.SentinelConnectionPool] = <class 'coredis.sentinel.SentinelConnectionPool'>, **kwargs: ~typing.Any) Redis[bytes][source]
primary_for(service_name: str, *, redis_class: ~typing.Type[~coredis.client.basic.Redis[str]] = coredis.client.basic.Redis[typing.Any], connection_pool_class: ~typing.Type[~coredis.sentinel.SentinelConnectionPool] = <class 'coredis.sentinel.SentinelConnectionPool'>, **kwargs: ~typing.Any) Redis[str]

Returns a redis client instance for the service_name primary.

A coredis.sentinel.SentinelConnectionPool class is used to retrive the primary’s address before establishing a new connection.

NOTE: If the primary’s address has changed, any cached connections to the old primary are closed.

By default clients will be a Redis instances. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any Sentinel.connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

replica_for(service_name: str, redis_class: ~typing.Type[~coredis.client.basic.Redis[bytes]] = coredis.client.basic.Redis[typing.Any], connection_pool_class: ~typing.Type[~coredis.sentinel.SentinelConnectionPool] = <class 'coredis.sentinel.SentinelConnectionPool'>, **kwargs: ~typing.Any) Redis[bytes][source]
replica_for(service_name: str, redis_class: ~typing.Type[~coredis.client.basic.Redis[str]] = coredis.client.basic.Redis[typing.Any], connection_pool_class: ~typing.Type[~coredis.sentinel.SentinelConnectionPool] = <class 'coredis.sentinel.SentinelConnectionPool'>, **kwargs: ~typing.Any) Redis[str]

Returns redis client instance for the service_name replica(s).

A SentinelConnectionPool class is used to retrieve the replica’s address before establishing a new connection.

By default clients will be a redis.Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any Sentinel.connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

KeyDB

class KeyDB(host: str | None = 'localhost', port: int | None = 6379, db: int = 0, *, username: str | None = None, password: str | None = None, stream_timeout: float | None = None, connect_timeout: float | None = None, connection_pool: ConnectionPool | None = None, connection_pool_cls: Type[ConnectionPool] = ConnectionPool, unix_socket_path: str | None = None, encoding: str = 'utf-8', decode_responses: bool = False, ssl: bool = False, ssl_context: SSLContext | None = None, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = None, ssl_check_hostname: bool | None = None, ssl_ca_certs: str | None = None, max_connections: int | None = None, max_idle_time: float = 0, idle_check_interval: float = 1, client_name: str | None = None, protocol_version: Literal[2, 3] = 3, verify_version: bool = True, cache: AbstractCache | None = None, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = ConstantRetryPolicy((ConnectionError, TimeoutError), 2, 0.01), **kwargs: Any)[source]

Client for KeyDB

The client is mostly coredis.Redis with a couple of extra commands specific to KeyDB.

async bitop(keys: Parameters[KeyT], operation: StringT, destkey: KeyT, value: int | None = None) int

Perform a bitwise operation using operation between keys and store the result in destkey.

KeyDB command documentation: BITOP

async cron(name: KeyT, repeat: bool, delay: int | datetime.timedelta, script: StringT, keys: Parameters[KeyT], args: Parameters[ValueT], start: int | datetime.datetime | None = None) bool

Schedule a LUA script to run at a specified time and/or intervals. To cancel the cron delete the key at name

Parameters:
  • name – Name of the cron which will be visible in the keyspace, can be searched, and deleted with DEL.

  • repeat – If the script will run only once, or if it will be repeated at the specified interval provided by delay

  • delay – is an integer specified in milliseconds used as the initial delay. If repeat is True, this will also be the length of the repeating timer which will execute the script each time the delay elapses (will continue to execute indefinitely).

  • start – unix time specified as milliseconds enforcing that the script should only start executing then this Unix time has been reached. If delay is greater than zero, this delay time will need to elapse prior to the script executing (timer begins to elapse at start time). If a start time is specified, the delay will always remain in reference intervals to that start time.

  • script – is the body of the LUA script to execute.

  • keys – The keys expected by the script

  • args – The args required by the script

KeyDB command documentation: KEYDB.CRON

async expiremember(key: KeyT, subkey: KeyT, delay: int, unit: Literal[b's', b'ms'] | None = None) bool

Set a subkey’s time to live in seconds (or milliseconds)

KeyDB command documentation: EXPIREMEMBER

async expirememberat(key: KeyT, subkey: KeyT, unix_time_seconds: int | datetime) bool

Set the expiration for a subkey as a UNIX timestamp

KeyDB command documentation: EXPIREMEMBERAT

async pexpirememberat(key: KeyT, subkey: KeyT, unix_time_milliseconds: int | datetime) bool

Set the expiration for a subkey as a UNIX timestamp in milliseconds

KeyDB command documentation: PEXPIREMEMBERAT

async hrename(key: KeyT, source_field: ValueT, destination_field: ValueT) bool

Rename a field source_field to destination_field in hash key

KeyDB command documentation: KEYDB.HRENAME

async mexists(keys: Iterable[KeyT]) tuple[bool, ...]

Returns a tuple of bools in the same order as keys denoting whether the keys exist

KeyDB command documentation: KEYDB.MEXISTS

async ttl(key: KeyT, subkey: ValueT | None = None) int

Get the time to live for a key (or subkey) in seconds

Returns:

TTL in seconds, or a negative value in order to signal an error

KeyDB command documentation: TTL

async pttl(key: KeyT, subkey: ValueT | None = None) int

Returns the number of milliseconds until the key key will expire. If subkey is provided the response will be for the subkey.

Returns:

TTL in milliseconds, or a negative value in order to signal an error

KeyDB command documentation: PTTL

async object_lastmodified(key: KeyT) int

Returns the time elapsed (in seconds) since the key was last modified. This differs from idletime as it is not affected by reads of a key.

Returns:

The time in seconds since the last modification

KeyDB command documentation: OBJECT LASTMODIFIED

class KeyDBCluster(host: str | None = None, port: int | None = None, *, startup_nodes: Iterable[Node] | None = None, stream_timeout: float | None = None, connect_timeout: float | None = None, ssl: bool = False, ssl_context: SSLContext | None = None, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = None, ssl_check_hostname: bool | None = None, ssl_ca_certs: str | None = None, max_connections: int = 32, max_connections_per_node: bool = False, readonly: bool = False, read_from_replicas: bool = False, reinitialize_steps: int | None = None, skip_full_coverage_check: bool = False, nodemanager_follow_cluster: bool = True, decode_responses: bool = False, connection_pool: ClusterConnectionPool | None = None, connection_pool_cls: Type[ClusterConnectionPool] = ClusterConnectionPool, protocol_version: Literal[2, 3] = 3, verify_version: bool = True, non_atomic_cross_slot: bool = True, cache: AbstractCache | None = None, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = CompositeRetryPolicy(ConstantRetryPolicy((ClusterDownError,), 2, 0.1), ConstantRetryPolicy((ConnectionError, TimeoutError), 2, 0.1)), **kwargs: Any)[source]

Cluster client for KeyDB

The client is mostly coredis.RedisCluster with a couple of extra commands specific to KeyDB.

async expiremember(key: KeyT, subkey: KeyT, delay: int, unit: Literal[b's', b'ms'] | None = None) bool

Set a subkey’s time to live in seconds (or milliseconds)

KeyDB command documentation: EXPIREMEMBER

async expirememberat(key: KeyT, subkey: KeyT, unix_time_seconds: int | datetime) bool

Set the expiration for a subkey as a UNIX timestamp

KeyDB command documentation: EXPIREMEMBERAT

async pexpirememberat(key: KeyT, subkey: KeyT, unix_time_milliseconds: int | datetime) bool

Set the expiration for a subkey as a UNIX timestamp in milliseconds

KeyDB command documentation: PEXPIREMEMBERAT

async hrename(key: KeyT, source_field: ValueT, destination_field: ValueT) bool

Rename a field source_field to destination_field in hash key

KeyDB command documentation: KEYDB.HRENAME

async mexists(keys: Iterable[KeyT]) tuple[bool, ...]

Returns a tuple of bools in the same order as keys denoting whether the keys exist

KeyDB command documentation: KEYDB.MEXISTS

async ttl(key: KeyT, subkey: ValueT | None = None) int

Get the time to live for a key (or subkey) in seconds

Returns:

TTL in seconds, or a negative value in order to signal an error

KeyDB command documentation: TTL

async pttl(key: KeyT, subkey: ValueT | None = None) int

Returns the number of milliseconds until the key key will expire. If subkey is provided the response will be for the subkey.

Returns:

TTL in milliseconds, or a negative value in order to signal an error

KeyDB command documentation: PTTL

async object_lastmodified(key: KeyT) int

Returns the time elapsed (in seconds) since the key was last modified. This differs from idletime as it is not affected by reads of a key.

Returns:

The time in seconds since the last modification

KeyDB command documentation: OBJECT LASTMODIFIED