Clients¶
- class Redis(host: str | None = ..., port: int | None = ..., db: int = ..., *, username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., connection_pool: ConnectionPool[Any] | None = ..., connection_pool_cls: type[ConnectionPool[Any]] = ..., unix_socket_path: str | None = ..., encoding: str = ..., decode_responses: Literal[False] = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int | None = ..., max_idle_time: int | None = ..., client_name: str | None = ..., verify_version: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)[source]¶
- class Redis(host: str | None = ..., port: int | None = ..., db: int = ..., *, username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., connection_pool: ConnectionPool[Any] | None = ..., connection_pool_cls: type[ConnectionPool[Any]] = ..., unix_socket_path: str | None = ..., encoding: str = ..., decode_responses: Literal[True] = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int | None = ..., max_idle_time: int | None = ..., client_name: str | None = ..., verify_version: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)
- class Redis(host: str | None = ..., port: int | None = ..., db: int = ..., *, username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., connection_pool: ConnectionPool[Any] | None = ..., connection_pool_cls: type[ConnectionPool[Any]] = ..., unix_socket_path: str | None = ..., encoding: str = ..., decode_responses: bool = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int | None = ..., max_idle_time: int | None = ..., client_name: str | None = ..., verify_version: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)
Changes
Removed in version 6.0.0.
protocol_versionremoved (and therefore support for RESP2)
Changed in version 6.0.0.
The client is now an async context manager and must always be used as such.
Added in version 4.12.0.
Redis.ensure_persistence()context managerRedis Module support
RedisJSON:
Redis.jsonRedisBloom:
BloomFilter:
Redis.bfCuckooFilter:
Redis.cfCountMinSketch:
Redis.cmsTopK:
Redis.topkTDigest:
Redis.tdigest
RedisTimeSeries:
Redis.timeseriesRedisGraph:
Redis.graphRediSearch:
Search & Aggregation:
Redis.searchAutocomplete: Added
Redis.autocomplete
Changed in version 4.12.0.
Removed
retry_on_timeoutconstructor argument. Useretry_policyinstead.
Added in version 4.3.0.
Added
connection_pool_cls
Changed in version 4.0.0.
non_atomic_cross_slotdefaults toTrueprotocol_version`defaults to3
Added in version 3.11.0.
Added
noreply
Added in version 3.9.0.
If
cacheis provided the client will check & populate the cache for read only commands and invalidate it for commands that could change the key(s) in the request.
Changed in version 3.5.0.
The
verify_versionparameter now defaults toTrue
Added in version 3.1.0.
The
protocol_versionandverify_version:parameters were added
- 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
credential_provider¶ – CredentialProvider to get authentication credentials
stream_timeout¶ – Timeout (seconds) when reading responses from the server
connect_timeout¶ – Timeout (seconds) for establishing a connection to the server
pool_timeout¶ – Timeout (seconds) for acquiring a connection from the connection pool
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
Truestring responses from the server will be decoded usingencodingbefore being returned. (See Encoding/Decoding)ssl¶ – Whether to use an SSL connection
ssl_context¶ – If provided the
ssl.SSLContextwill 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 otherssl_*parameters will be used.ssl_keyfile¶ – Path of the private key to use
ssl_certfile¶ – Path to the certificate corresponding to
ssl_keyfilessl_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_reqsis not"none"(Seessl.SSLContext.load_verify_locations()).max_connections¶ – Maximum capacity of the connection pool (Ignored if
connection_poolis notNone.max_idle_time¶ – Maximum number of a seconds an unused connection is cached before it is disconnected.
client_name¶ – The client name to identifiy with the redis server
verify_version¶ – Validate redis server version against the documented version introduced before executing a command and raises a
CommandNotSupportedErrorerror if the required version is higher than the reported server versioncache¶ – 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
Truethe 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
type_adapter¶ – The adapter to use for serializing / deserializing customs types when interacting with redis commands.
- acl_cat(categoryname: StringT | None = None) CommandRequest[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: CommandName.ACL_CAT
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_deluser(usernames: Parameters[StringT]) CommandRequest[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: CommandName.ACL_DELUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_dryrun(username: StringT, command: StringT, *args: ValueT) CommandRequest[bool]¶
Returns whether the user can execute the given command without executing the command.
Redis command documentation: CommandName.ACL_DRYRUN
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- acl_genpass(bits: int | None = None) CommandRequest¶
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: CommandName.ACL_GENPASS
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_getuser(username: StringT) CommandRequest[dict[AnyStr, list[AnyStr] | set[AnyStr]]]¶
Get the rules for a specific ACL user
Redis command documentation: CommandName.ACL_GETUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_list() CommandRequest[tuple[AnyStr, ...]]¶
List the current ACL rules in ACL config file format
Redis command documentation: CommandName.ACL_LIST
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_load() CommandRequest[bool]¶
Reload the ACLs from the configured ACL file
- Returns:
Trueif 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: CommandName.ACL_LOAD
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_log(count: int | None = None, reset: bool | None = None) CommandRequest[bool] | CommandRequest[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
RESETTrueif the security log was cleared.
Redis command documentation: CommandName.ACL_LOG
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_save() CommandRequest[bool]¶
Save the current ACL rules in the configured ACL file
- Returns:
Trueif 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: CommandName.ACL_SAVE
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_setuser(username: StringT, *rules: StringT) CommandRequest[bool]¶
Modify or create the rules for a specific ACL user
- Returns:
Trueif successful. If the rules contain errors, the error is returned.
Redis command documentation: CommandName.ACL_SETUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_users() CommandRequest[tuple[AnyStr, ...]]¶
List the username of all the configured ACL rules
Redis command documentation: CommandName.ACL_USERS
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_whoami() CommandRequest¶
Return the name of the user associated to the current connection
- Returns:
the username of the current connection.
Redis command documentation: CommandName.ACL_WHOAMI
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- append(key: KeyT, value: ValueT) CommandRequest[int]¶
Append a value to a key.
- Parameters:
- Returns:
The length of the string after the append operation.
Redis command documentation: CommandName.APPEND
- asking() CommandRequest[bool]¶
Send ASK to the server (used by cluster clients after an -ASK redirect).
- Returns:
Trueon success.
Redis command documentation: CommandName.ASKING
Added in version 3.0.0.
- auth(password: StringT, username: StringT | None = None) CommandRequest[bool]¶
Authenticate the connection to the server.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.AUTH
Compatibility:
username: New in Redis version: 6.0.0
Warning
Using
authdirectly is not recommended. Use theRedis.usernameandRedis.passwordarguments 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.
- property autocomplete: Autocomplete¶
Property to access
Autocompletecommands.Added in version 4.12.0.
- property bf: BloomFilter¶
Property to access
BloomFiltercommands.Added in version 4.12.0.
- bgrewriteaof() CommandRequest[bool]¶
Ask the server to rewrite the AOF file from data in memory.
- Returns:
Truewhen the rewrite has been scheduled.
Redis command documentation: CommandName.BGREWRITEAOF
- bgsave(schedule: bool | None = None) CommandRequest[bool]¶
Start a background save of the dataset to disk (non-blocking).
- Parameters:
schedule¶ – If
True, schedule a save if none in progress.- Returns:
Truewhen save has started or been scheduled.
Redis command documentation: CommandName.BGSAVE
- bitcount(key: KeyT, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) CommandRequest[int]¶
Return the number of set bits in the string value at key.
- Parameters:
- Returns:
Count of bits set to 1 in the (optionally ranged) value.
Redis command documentation: CommandName.BITCOUNT
Compatibility:
index_unit: New in Redis version: 7.0.0
- bitfield(key: KeyT) BitFieldOperation¶
Return a BitFieldOperation to build one or more bitfield ops on the key.
- Parameters:
key¶ – The key name.
- Returns:
BitFieldOperationfor chained get/set/incr.
- bitfield_ro(key: KeyT) BitFieldOperation¶
Return a read-only BitFieldOperation for bitfield GET on the key (e.g. on replica).
- Parameters:
key¶ – The key name.
- Returns:
BitFieldOperation(read-only; write raises ReadOnlyError).
- bitop(keys: Parameters[KeyT], operation: StringT, destkey: KeyT) CommandRequest[int]¶
Perform a bitwise operation (AND, OR, XOR, NOT) on keys and store result at destkey.
- Parameters:
- Returns:
Size in bytes of the result string.
Redis command documentation: CommandName.BITOP
- bitpos(key: KeyT, bit: int, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) CommandRequest[int]¶
Return the position of the first bit set to 1 or 0 in the string value.
- Parameters:
- Returns:
Bit position of first matching bit; -1 if no match (e.g. empty key for bit=1). For bit=0 with no range or start-only, string is considered right-padded with zeros.
Redis command documentation: CommandName.BITPOS
Compatibility:
index_unit: New in Redis version: 7.0.0
- blmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT], timeout: int | float) CommandRequest[AnyStr | None]¶
Pop an element from a list, push it to another list, and return it; block until one is available.
- Parameters:
- Returns:
The element that was moved, or
Noneif timeout was reached.
Redis command documentation: CommandName.BLMOVE
Compatibility:
New in Redis version: 6.2.0
- blmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) CommandRequest[list[AnyStr | list[AnyStr]] | None]¶
Pop elements from the first non-empty list among the given keys, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, [elements]].
Redis command documentation: CommandName.BLMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- blpop(keys: Parameters[KeyT], timeout: int | float) CommandRequest[list[AnyStr] | None]¶
Remove and return the first element from the first non-empty list, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, element].
Redis command documentation: CommandName.BLPOP
- brpop(keys: Parameters[KeyT], timeout: int | float) CommandRequest[list[AnyStr] | None]¶
Remove and return the last element from the first non-empty list, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, element].
Redis command documentation: CommandName.BRPOP
- brpoplpush(source: KeyT, destination: KeyT, timeout: int | float) CommandRequest[AnyStr | None]¶
Pop from the tail of source, push to the head of destination, and return the element; block until one is available.
- Parameters:
- Returns:
The element that was moved, or
Noneif timeout was reached.
Redis command documentation: CommandName.BRPOPLPUSH
Caution
Deprecated in Redis version: 6.2.0 Use
blmove()with the wherefrom and whereto arguments
- bzmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) CommandRequest[tuple[AnyStr, tuple[ScoredMember, ...]] | None]¶
Pop members with lowest or highest scores from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, [(member, score), …]).
Redis command documentation: CommandName.BZMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- bzpopmax(keys: Parameters[KeyT], timeout: int | float) CommandRequest[tuple[AnyStr, AnyStr, float] | None]¶
Pop the member with the highest score from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, member, score).
Redis command documentation: CommandName.BZPOPMAX
- bzpopmin(keys: Parameters[KeyT], timeout: int | float) CommandRequest[tuple[AnyStr, AnyStr, float] | None]¶
Pop the member with the lowest score from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, member, score).
Redis command documentation: CommandName.BZPOPMIN
- property cf: CuckooFilter¶
Property to access
CuckooFiltercommands.Added in version 4.12.0.
- client_caching(mode: Literal[PureToken.NO, PureToken.YES]) CommandRequest[bool]¶
Instruct the server about tracking or not keys in the next request
Redis command documentation: CommandName.CLIENT_CACHING
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_getname() CommandRequest[AnyStr | None]¶
Returns the current connection name
- Returns:
The connection name, or
Noneif no name is set.
Redis command documentation: CommandName.CLIENT_GETNAME
- client_getredir() CommandRequest[int]¶
Get tracking notifications redirection client ID if any
- Returns:
the ID of the client we are redirecting the notifications to. The command returns
-1if client tracking is not enabled, or0if client tracking is enabled but we are not redirecting the notifications to any client.
Redis command documentation: CommandName.CLIENT_GETREDIR
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_id() CommandRequest[int]¶
Returns the client ID for the current connection
- Returns:
The id of the client.
Redis command documentation: CommandName.CLIENT_ID
Added in version 3.0.0.
- client_info() CommandRequest[ClientInfo]¶
Returns information about the current client connection.
Redis command documentation: CommandName.CLIENT_INFO
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- client_kill(ip_port: StringT | None = None, identifier: int | None = None, type_: None | Literal[PureToken.NORMAL, PureToken.MASTER, PureToken.SLAVE, PureToken.REPLICA, PureToken.PUBSUB] = None, user: StringT | None = None, addr: StringT | None = None, laddr: StringT | None = None, skipme: bool | None = None, maxage: int | None = None) CommandRequest[int | bool]¶
Disconnect one or more clients by filter (ip:port, addr, type, user, etc.).
- Parameters:
ip_port¶ – Client address as
ip:port(legacy form).identifier¶ – Client ID (from client list).
type_¶ – NORMAL, MASTER, SLAVE, REPLICA, or PUBSUB.
user¶ – Disconnect clients of the given user.
addr¶ – Disconnect client at the given address.
laddr¶ – Match local address.
skipme¶ – If
True, do not disconnect this connection.maxage¶ – Disconnect idle clients older than this many seconds.
- Returns:
Trueif a single client was closed, or number of clients killed.
Redis command documentation: CommandName.CLIENT_KILL
Compatibility:
laddr: New in Redis version: 6.2.0maxage: New in Redis version: 7.4.0
- client_list(type_: None | Literal[PureToken.MASTER, PureToken.NORMAL, PureToken.PUBSUB, PureToken.REPLICA] = None, identifiers: Parameters[int] | None = None) CommandRequest[tuple[ClientInfo, ...]]¶
Get client connections
- Returns:
a tuple of dictionaries containing client fields
Redis command documentation: CommandName.CLIENT_LIST
Compatibility:
identifiers: New in Redis version: 6.2.0
- client_no_evict(enabled: Literal[PureToken.ON, PureToken.OFF]) CommandRequest[bool]¶
Set client eviction mode for the current connection
Redis command documentation: CommandName.CLIENT_NO_EVICT
Compatibility:
New in Redis version: 7.0.0
Warning
Using
client_no_evictdirectly is not recommended. UseRedis.noevictargument when initializing the client to ensure that all connections originating from this client use the desired modeAdded in version 3.2.0.
- client_no_touch(enabled: Literal[PureToken.OFF, PureToken.ON]) CommandRequest[bool]¶
Controls whether commands sent by the client will alter the LRU/LFU of the keys they access.
Redis command documentation: CommandName.CLIENT_NO_TOUCH
Compatibility:
New in Redis version: 7.1.240
Warning
Using
client_no_touchdirectly is not recommended. UseRedis.notouchargument when initializing the client to ensure that all connections originating from this client use the desired modeAdded in version 4.12.0.
- client_pause(timeout: int, mode: Literal[PureToken.WRITE, PureToken.ALL] | None = None) CommandRequest[bool]¶
Stop processing commands from clients for some time
- Returns:
The command returns
Trueor raises an error if the timeout is invalid.
Redis command documentation: CommandName.CLIENT_PAUSE
Compatibility:
mode: New in Redis version: 6.2.0
- client_reply(mode: Literal[PureToken.OFF, PureToken.ON, PureToken.SKIP]) CommandRequest[bool]¶
Instruct the server whether to reply to commands
Redis command documentation: CommandName.CLIENT_REPLY
Danger
Using
client_replydirectly is not supported. Use theRedis.noreplyargument when initializing the client to ensure that all connections originating from this client disable or enable replies. You can also use theRedis.ignore_replies()context manager to selectively execute certain commands without waiting for a replyAdded in version 3.0.0.
- client_setinfo(lib_name: StringT | None = None, lib_ver: StringT | None = None) CommandRequest[bool]¶
Set client or connection specific info
Redis command documentation: CommandName.CLIENT_SETINFO
Compatibility:
New in Redis version: 7.1.240
Warning
Using
client_setinfodirectly 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 commandsAdded in version 4.12.0.
- client_setname(connection_name: StringT) CommandRequest[bool]¶
Set the current connection name :return: If the connection name was successfully set.
Redis command documentation: CommandName.CLIENT_SETNAME
Warning
Using
client_setnamedirectly is not recommended. Use theRedis.client_nameargument when initializing the client to ensure the client name is consistent across all connections originating from the client
- 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) CommandRequest[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: CommandName.CLIENT_TRACKING
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_trackinginfo() CommandRequest[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: CommandName.CLIENT_TRACKINGINFO
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- client_unblock(client_id: int, unblock_type: Literal[PureToken.TIMEOUT, PureToken.ERROR] | None = None) CommandRequest[bool]¶
Unblock a client blocked in a blocking command from a different connection
- Parameters:
- Returns:
Whether the client was unblocked
Redis command documentation: CommandName.CLIENT_UNBLOCK
Added in version 3.0.0.
- client_unpause() CommandRequest[bool]¶
Resume processing of clients that were paused
- Returns:
The command returns
`True`
Redis command documentation: CommandName.CLIENT_UNPAUSE
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- cluster_addslots(slots: Parameters[int]) CommandRequest[bool]¶
Assign new hash slots to the receiving node.
- Parameters:
slots¶ – One or more slot numbers to assign.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_ADDSLOTS
- cluster_addslotsrange(slots: Parameters[tuple[int, int]]) CommandRequest[bool]¶
Assign ranges of hash slots to the receiving node.
- Parameters:
slots¶ – One or more (start, end) slot ranges (inclusive).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_ADDSLOTSRANGE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
- cluster_bumpepoch() CommandRequest¶
Advance the cluster configuration epoch.
- Returns:
BUMPEDif the epoch was incremented,STILLif this node already had the greatest epoch.
Redis command documentation: CommandName.CLUSTER_BUMPEPOCH
Added in version 3.0.0.
- cluster_count_failure_reports(node_id: StringT) CommandRequest[int]¶
Return the number of failure reports active for a given node.
- Parameters:
node_id¶ – The cluster node ID.
- Returns:
The number of failure reports.
Redis command documentation: CommandName.CLUSTER_COUNT_FAILURE_REPORTS
- cluster_countkeysinslot(slot: int) CommandRequest[int]¶
Return the number of local keys in the specified hash slot.
- Parameters:
slot¶ – The hash slot number.
- Returns:
The number of keys in the slot on this node.
Redis command documentation: CommandName.CLUSTER_COUNTKEYSINSLOT
- cluster_delslots(slots: Parameters[int]) CommandRequest[bool]¶
Mark the given hash slots as unbound in the cluster.
The command is routed to the node that owns each slot.
- Parameters:
slots¶ – One or more slot numbers to unbound.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_DELSLOTS
- cluster_delslotsrange(slots: Parameters[tuple[int, int]]) CommandRequest[bool]¶
Mark the given slot ranges as unbound on the receiving node.
- Parameters:
slots¶ – One or more (start, end) slot ranges (inclusive).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_DELSLOTSRANGE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
- cluster_failover(options: Literal[PureToken.FORCE, PureToken.TAKEOVER] | None = None) CommandRequest[bool]¶
Force a replica to perform a manual failover of its master.
- Parameters:
options¶ – Optional FORCE or TAKEOVER to alter failover behavior.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FAILOVER
- cluster_flushslots() CommandRequest[bool]¶
Delete this node’s assigned slot information (must have no keys in those slots).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FLUSHSLOTS
Added in version 3.0.0.
- cluster_forget(node_id: StringT) CommandRequest[bool]¶
Remove a node from the set of known nodes of the cluster node receiving the command.
- Parameters:
node_id¶ – The cluster node ID to forget.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FORGET
- cluster_getkeysinslot(slot: int, count: int) CommandRequest[tuple[AnyStr, ...]]¶
Return up to a given number of local key names in the specified hash slot.
- Parameters:
- Returns:
A tuple of key names (up to count).
Redis command documentation: CommandName.CLUSTER_GETKEYSINSLOT
Added in version 3.0.0.
- cluster_info() CommandRequest[dict[str, str]]¶
Return information about the Redis Cluster node state.
- Returns:
A mapping of cluster state keys and values.
Redis command documentation: CommandName.CLUSTER_INFO
- cluster_keyslot(key: KeyT) CommandRequest[int]¶
Return the hash slot number for the specified key.
- Parameters:
key¶ – The key name.
- Returns:
The slot number
Redis command documentation: CommandName.CLUSTER_KEYSLOT
- cluster_links() CommandRequest[list[dict[AnyStr, ResponsePrimitive]]]¶
Return a list of all TCP links to and from peer nodes in the cluster.
- Returns:
A list of mappings; each mapping contains attributes and values for one cluster link.
Redis command documentation: CommandName.CLUSTER_LINKS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
- cluster_meet(ip: StringT, port: int, cluster_bus_port: int | None = None) CommandRequest[bool]¶
Force this cluster node to handshake with another node.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_MEET
- cluster_myid() CommandRequest¶
Return this node’s cluster ID.
- Returns:
The node ID string.
Redis command documentation: CommandName.CLUSTER_MYID
Added in version 3.1.1.
- cluster_nodes() CommandRequest[list[ClusterNodeDetail]]¶
Return the current cluster configuration from the perspective of this node.
- Returns:
A list of cluster node details.
Redis command documentation: CommandName.CLUSTER_NODES
- cluster_replicas(node_id: StringT) CommandRequest[list[ClusterNodeDetail]]¶
List replica nodes of the specified master node.
- Parameters:
node_id¶ – The master node ID.
- Returns:
A list of replica node details.
Redis command documentation: CommandName.CLUSTER_REPLICAS
- cluster_replicate(node_id: StringT) CommandRequest[bool]¶
Reconfigure this node as a replica of the specified master node.
- Parameters:
node_id¶ – The master node ID to replicate.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_REPLICATE
- cluster_reset(reset_type: Literal[PureToken.HARD, PureToken.SOFT] | None = None) CommandRequest[bool]¶
Reset a Redis Cluster node (clears slots and peer state).
- Parameters:
reset_type¶ – HARD (full reset) or SOFT (only clear keys); default is HARD.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_RESET
- cluster_saveconfig() CommandRequest[bool]¶
Force the node to save the cluster state to disk.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SAVECONFIG
- cluster_set_config_epoch(config_epoch: int) CommandRequest[bool]¶
Set the configuration epoch for a new node (used during cluster creation).
- Parameters:
config_epoch¶ – The configuration epoch value.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SET_CONFIG_EPOCH
- cluster_setslot(slot: int, *, importing: StringT | None = None, migrating: StringT | None = None, node: StringT | None = None, stable: bool | None = None) CommandRequest[bool]¶
Bind a hash slot to a specific node or set slot migration state.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SETSLOT
- cluster_shards() CommandRequest[list[dict[AnyStr, list[RedisValueT] | Mapping[AnyStr, RedisValueT]]]]¶
Return a mapping of cluster slots to nodes.
- Returns:
A list of shard mappings with slot ranges and node info.
Redis command documentation: CommandName.CLUSTER_SHARDS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.2.0.
- cluster_slaves(node_id: StringT) CommandRequest[list[ClusterNodeDetail]]¶
List replica nodes of the specified master node.
- Parameters:
node_id¶ – The master node ID.
- Returns:
A list of replica node details.
Redis command documentation: CommandName.CLUSTER_SLAVES
Caution
Deprecated in Redis version: 5.0.0 Use
cluster_replicas()
- cluster_slots() CommandRequest[dict[tuple[int, int], tuple[ClusterNode, ...]]]¶
Return a mapping of cluster slot ranges to nodes.
- Returns:
A mapping of (start, end) slot ranges to node tuples.
Redis command documentation: CommandName.CLUSTER_SLOTS
Caution
Deprecated in Redis version: 7.0.0 Use
cluster_shards()
- property cms: CountMinSketch¶
Property to access
CountMinSketchcommands.Added in version 4.12.0.
- command() CommandRequest[dict[str, Command]]¶
Get Redis command details
- Returns:
Mapping of command details. Commands are returned in random order.
Redis command documentation: CommandName.COMMAND
Added in version 3.0.0.
- command_count() CommandRequest[int]¶
Get total number of Redis commands
- Returns:
number of commands returned by
COMMAND
Redis command documentation: CommandName.COMMAND_COUNT
Added in version 3.0.0.
- command_docs(*command_names: StringT) CommandRequest[dict[AnyStr, dict[AnyStr, ResponseType]]]¶
Mapping of commands to a dictionary containing it’s documentation
Redis command documentation: CommandName.COMMAND_DOCS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- command_getkeys(command: StringT, arguments: Parameters[ValueT]) CommandRequest[tuple[AnyStr, ...]]¶
Extract keys given a full Redis command
- Returns:
Keys from your command.
Redis command documentation: CommandName.COMMAND_GETKEYS
Added in version 3.0.0.
- command_getkeysandflags(command: StringT, arguments: Parameters[ValueT]) CommandRequest[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: CommandName.COMMAND_GETKEYSANDFLAGS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- command_info(*command_names: StringT) CommandRequest[dict[str, Command]]¶
Get specific Redis command details, or all when no argument is given.
- Returns:
mapping of command details.
Redis command documentation: CommandName.COMMAND_INFO
Added in version 3.0.0.
- command_list(module: StringT | None = None, aclcat: StringT | None = None, pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Get an array of Redis command names
Redis command documentation: CommandName.COMMAND_LIST
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- config_get(parameters: Parameters[StringT]) CommandRequest[dict[AnyStr, AnyStr]]¶
Get the values of configuration parameters
Redis command documentation: CommandName.CONFIG_GET
- config_resetstat() CommandRequest[bool]¶
Reset runtime statistics (keyspace hits/misses, commands processed, etc.).
- Returns:
Trueon success.
Redis command documentation: CommandName.CONFIG_RESETSTAT
- config_rewrite() CommandRequest[bool]¶
Rewrites config file with the minimal change to reflect running config
Redis command documentation: CommandName.CONFIG_REWRITE
- config_set(parameter_values: Mapping[MappingKeyT, ValueT]) CommandRequest[bool]¶
Set one or more server configuration parameters at runtime.
- Parameters:
parameter_values¶ – Mapping of parameter names to values.
- Returns:
Trueon success.
Redis command documentation: CommandName.CONFIG_SET
- copy(source: KeyT, destination: KeyT, db: int | None = None, replace: bool | None = None) CommandRequest[bool]¶
Copy a key to another key, optionally in another database.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.COPY
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- create_request(name: bytes, *arguments: ValueT | Key, callback: Callable[[...], T_co], execution_parameters: ExecutionParameters | None = None) CommandRequest[T_co]¶
Factory method to create a command request awaitable. Subclasses of
coredis.client.Clientcan override this method if custom behavior is required. SeeCommandRequestfor details.
- dbsize() CommandRequest[int]¶
Return the number of keys in the currently selected database.
- Returns:
The number of keys.
Redis command documentation: CommandName.DBSIZE
- debug_object(key: KeyT) CommandRequest[dict[str, str | int]]¶
Return version-specific debugging information about a key (internal encoding, refcount, etc.).
- Parameters:
key¶ – The key name.
- Returns:
A mapping of debug attributes.
Redis command documentation: CommandName.DEBUG_OBJECT
- decr(key: KeyT) CommandRequest[int]¶
Decrement the integer value of a key by one.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key after the decrement.
Redis command documentation: CommandName.DECR
- decrby(key: KeyT, decrement: int) CommandRequest[int]¶
Decrement the integer value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the decrement.
Redis command documentation: CommandName.DECRBY
- delete(keys: Parameters[KeyT]) CommandRequest[int]¶
Delete one or more keys.
- Parameters:
keys¶ – One or more key names to delete.
- Returns:
The number of keys that were removed.
Redis command documentation: CommandName.DEL
- delex(key: KeyT, *, ifeq: ValueT | None = None, ifne: ValueT | None = None, ifdeq: ValueT | None = None, ifdne: ValueT | None = None) CommandRequest[bool]¶
Remove a key only if its value or hash digest matches the given condition.
- Parameters:
- Returns:
Trueif the key was removed.
Redis command documentation: CommandName.DELEX
Compatibility:
New in Redis version: 8.4.0
- digest(key: KeyT) CommandRequest[AnyStr | None]¶
Return the hash digest of the value stored at key as a hexadecimal string.
- Parameters:
key¶ – The key name.
- Returns:
The hex digest string, or
Noneif the key does not exist.
Redis command documentation: CommandName.DIGEST
Compatibility:
New in Redis version: 8.4.0
- dump(key: KeyT) CommandRequest[bytes]¶
Return a serialized version of the value stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The serialized value as bytes (use with restore).
Redis command documentation: CommandName.DUMP
- echo(message: StringT) CommandRequest¶
Echo the given string back from the server.
- Parameters:
message¶ – The string to echo.
- Returns:
The same string.
Redis command documentation: CommandName.ECHO
- 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
localhost and/orreplicaswithintimeout_msmilliseconds.Internally this uses WAITAOF after each command executed within the context
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
replicaswithintimeout_msmilliseconds.Internally this uses WAIT after each command executed within the context
Example:
client = coredis.RedisCluster("localhost", 7000) with client.ensure_replication(1, 20): await client.set("fubar", 1)
- eval(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script with the given keys and arguments.
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVAL
- eval_ro(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script in read-only mode (no writes).
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVAL_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- evalsha(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script from the server cache by its SHA1 digest.
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVALSHA
- evalsha_ro(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a cached Lua script in read-only mode (no writes).
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVALSHA_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- exists(keys: Parameters[KeyT]) CommandRequest[int]¶
Return how many of the given keys exist.
- Parameters:
keys¶ – One or more key names to check.
- Returns:
The number of keys that exist.
Redis command documentation: CommandName.EXISTS
- expire(key: KeyT, seconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set a key’s time to live in seconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise (e.g. key does not exist).
Redis command documentation: CommandName.EXPIRE
Compatibility:
condition: New in Redis version: 7.0.0
- expireat(key: KeyT, unix_time_seconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set the expiration for a key to an absolute Unix timestamp in seconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.EXPIREAT
Compatibility:
condition: New in Redis version: 7.0.0
- expiretime(key: KeyT) CommandRequest[datetime]¶
Return the expiration Unix timestamp for a key in seconds.
- Parameters:
key¶ – The key name.
- Returns:
Expiration as datetime. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.EXPIRETIME
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- failover(host: StringT | None = None, port: int | None = None, force: bool | None = None, abort: bool | None = None, timeout: int | timedelta | None = None) CommandRequest[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: CommandName.FAILOVER
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- fcall(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Invoke a Redis function by name.
- Parameters:
- Returns:
The return value of the function (type depends on the function).
Redis command documentation: CommandName.FCALL
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- fcall_ro(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Invoke a Redis function in read-only mode (same as fcall but only for read-only functions).
- Parameters:
- Returns:
The return value of the function.
Redis command documentation: CommandName.FCALL_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- flushall(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Deletes all keys in all databases on the current host
- Parameters:
flush_type¶ – Whether to perform an asynchronous or synchronous flush
Redis command documentation: CommandName.FLUSHALL
- flushdb(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Deletes all keys in the current database
- Parameters:
flush_type¶ – Whether to perform an asynchronous or synchronous flush
Redis command documentation: CommandName.FLUSHDB
- function_delete(library_name: StringT) CommandRequest[bool]¶
Delete a library and all its functions from the server.
- Parameters:
library_name¶ – The name of the library to delete.
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_DELETE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_dump() CommandRequest[bytes]¶
Return a serialized binary payload of all loaded functions.
- Returns:
The serialized payload (use with function_restore).
Redis command documentation: CommandName.FUNCTION_DUMP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_flush(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Delete all functions from the server.
- Parameters:
flush_type¶ – ASYNC to flush asynchronously, SYNC to block until done.
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_FLUSH
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_kill() CommandRequest[bool]¶
Kill the function currently in execution.
Redis command documentation: CommandName.FUNCTION_KILL
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_list(libraryname: StringT | None = None, withcode: bool | None = None) CommandRequest[Mapping[AnyStr, LibraryDefinition]]¶
List libraries and functions (optionally filtered by library name).
- Parameters:
- Returns:
Mapping of library name to library definition (functions, code, etc.).
Redis command documentation: CommandName.FUNCTION_LIST
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_load(function_code: StringT, replace: bool | None = None) CommandRequest¶
Load a library of Redis functions (Lua or other engine).
- Parameters:
- Returns:
Library name on success.
Redis command documentation: CommandName.FUNCTION_LOAD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_restore(serialized_value: bytes, policy: Literal[PureToken.FLUSH, PureToken.APPEND, PureToken.REPLACE] | None = None) CommandRequest[bool]¶
Restore libraries/functions from a serialized payload (from function_dump).
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_RESTORE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- function_stats() CommandRequest[dict[AnyStr, AnyStr | dict[AnyStr, dict[AnyStr, ResponsePrimitive]] | None]]¶
Return runtime statistics for the currently running function (if any).
- Returns:
Dict with running_script, engines, etc.; None if no function is running.
Redis command documentation: CommandName.FUNCTION_STATS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- 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) CommandRequest[int]¶
Add one or more geospatial items (longitude, latitude, name) to the index at key.
- Parameters:
- Returns:
The number of elements added; or, if
changeisTrue, the number changed.
Redis command documentation: CommandName.GEOADD
Compatibility:
condition: New in Redis version: 6.2.0change: New in Redis version: 6.2.0
- geodist(key: KeyT, member1: StringT, member2: StringT, unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None) CommandRequest[float | None]¶
Return the distance between two members in the geospatial index.
- Parameters:
- Returns:
The distance in the requested unit, or
Noneif a member is missing.
Redis command documentation: CommandName.GEODIST
- geohash(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[AnyStr, ...]]¶
Return geohash strings for the given members in the geospatial index.
- Parameters:
- Returns:
A tuple of geohash strings (same order as members).
Redis command documentation: CommandName.GEOHASH
- geopos(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[GeoCoordinates | None, ...]]¶
Return longitude and latitude for the given members in the geospatial index.
- Parameters:
- Returns:
A tuple of
(lon, lat)pairs orNonefor missing members.
Redis command documentation: CommandName.GEOPOS
- 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index for members within radius of a center.
- Parameters:
key¶ – The key name.
longitude¶ – Center longitude.
latitude¶ – Center latitude.
radius¶ – Maximum distance from center.
unit¶ – M, KM, FT, or MI.
withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.order¶ – ASC or DESC by distance.
store¶ – Store results in this key (sorted set).
storedist¶ – Store results with distances in this key.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.Count of stored results if
storeorstoredistare provided
Redis command documentation: CommandName.GEORADIUS
Compatibility:
Caution
Deprecated in Redis version: 6.2.0 Use
geosearch()andgeosearchstore()with the radius argumentany_: New in Redis version: 6.2.0
- 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index for members within radius of an existing member.
- Parameters:
key¶ – The key name.
member¶ – Member to use as center.
radius¶ – Maximum distance from member.
unit¶ – M, KM, FT, or MI.
withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.order¶ – ASC or DESC by distance.
store¶ – Store results in this key (sorted set).
storedist¶ – Store results with distances in this key.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.Count of stored results if
storeorstoredistare provided
Redis command documentation: CommandName.GEORADIUSBYMEMBER
Caution
Deprecated in Redis version: 6.2.0 Use
geosearch()andgeosearchstore()with the radius and member arguments
- geosearch(key: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: None | Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] = 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index by center (member or lon/lat) and radius or bounding box.
- Parameters:
key¶ – The key name.
member¶ – Use this member as center (alternative to longitude/latitude).
longitude¶ – Center longitude (with latitude).
latitude¶ – Center latitude (with longitude).
radius¶ – Maximum distance; use with circle_unit.
circle_unit¶ – M, KM, FT, or MI for radius.
width¶ – Box width; use with height and box_unit.
height¶ – Box height; use with width and box_unit.
box_unit¶ – M, KM, FT, or MI for box.
order¶ – ASC or DESC by distance.
count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.
Redis command documentation: CommandName.GEOSEARCH
Compatibility:
New in Redis version: 6.2.0
- 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: None | Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] = 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) CommandRequest[int]¶
Query a geospatial index and store the result in a sorted set at destination.
- Parameters:
destination¶ – Key where the result is stored.
source¶ – Source geospatial index key.
member¶ – Use this member as center (alternative to longitude/latitude).
longitude¶ – Center longitude (with latitude).
latitude¶ – Center latitude (with longitude).
radius¶ – Maximum distance; use with circle_unit.
circle_unit¶ – M, KM, FT, or MI for radius.
width¶ – Box width; use with height and box_unit.
height¶ – Box height; use with width and box_unit.
box_unit¶ – M, KM, FT, or MI for box.
order¶ – ASC or DESC by distance.
count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.storedist¶ – If
True, store distances as scores.
- Returns:
The number of elements stored in the resulting set.
Redis command documentation: CommandName.GEOSEARCHSTORE
Compatibility:
New in Redis version: 6.2.0
- get(key: KeyT) CommandRequest[AnyStr | None]¶
Get the string value of a key.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key, or
Noneif the key does not exist.
Redis command documentation: CommandName.GET
Hint
Supports client side caching
- async get_library(name: StringT) Library¶
Fetch a pre registered library
- Parameters:
name¶ – name of the library
Added in version 3.1.0.
- getbit(key: KeyT, offset: int) CommandRequest[int]¶
Return the bit value at the given offset in the string value at key.
- Parameters:
- Returns:
0 or 1; 0 if key is missing or offset is beyond the string.
Redis command documentation: CommandName.GETBIT
- getdel(key: KeyT) CommandRequest[AnyStr | None]¶
Get the value of a key and delete the key.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key, or
Noneif the key does not exist. Raises an error if the key exists but is not a string.
Redis command documentation: CommandName.GETDEL
Compatibility:
New in Redis version: 6.2.0
- 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) CommandRequest[AnyStr | None]¶
Get the value of a key and optionally set or remove its expiration.
Similar to GET but supports expiry options. Time parameters may be
datetime.timedeltaordatetime.datetimeor integers.- Parameters:
key¶ – The key name.
ex¶ – Set key to expire after this many seconds (relative).
px¶ – Set key to expire after this many milliseconds (relative).
exat¶ – Set key to expire at this Unix timestamp in seconds (absolute).
pxat¶ – Set key to expire at this Unix timestamp in milliseconds (absolute).
persist¶ – If
True, remove the time-to-live from the key.
- Returns:
The value of the key, or
Noneif the key does not exist.
Redis command documentation: CommandName.GETEX
Compatibility:
New in Redis version: 6.2.0
- getrange(key: KeyT, start: int, end: int) CommandRequest¶
Return a substring of the string stored at a key.
Offsets are zero-based; negative offsets count from the end of the string. Both start and end are inclusive.
- Parameters:
- Returns:
The substring determined by the given offsets.
Redis command documentation: CommandName.GETRANGE
Hint
Supports client side caching
- getset(key: KeyT, value: ValueT) CommandRequest[AnyStr | None]¶
Set the string value of a key and return its old value
- Returns:
The previous value of the key, or
Noneif the key did not exist.
Redis command documentation: CommandName.GETSET
Caution
Deprecated in Redis version: 6.2.0 Use
set()with the get argument
- hdel(key: KeyT, fields: Parameters[StringT]) CommandRequest[int]¶
Delete one or more fields from a hash.
- Parameters:
- Returns:
The number of fields that were removed.
Redis command documentation: CommandName.HDEL
- hello(protover: int | None = None, username: StringT | None = None, password: StringT | None = None, setname: StringT | None = None) CommandRequest[dict[AnyStr, AnyStr]]¶
Perform a handshake with Redis (protocol version, auth, client name).
- Parameters:
- Returns:
A mapping of server properties (e.g. version, mode).
Redis command documentation: CommandName.HELLO
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- hexists(key: KeyT, field: StringT) CommandRequest[bool]¶
Return whether a field exists in a hash.
- Parameters:
- Returns:
Trueif the field exists,Falseotherwise.
Redis command documentation: CommandName.HEXISTS
Hint
Supports client side caching
- hexpire(key: KeyT, seconds: int | datetime.timedelta, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set a TTL in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HEXPIRE
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hexpireat(key: KeyT, unix_time_seconds: int | datetime.datetime, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set an absolute expiration Unix timestamp (seconds) for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HEXPIREAT
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hexpiretime(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the expiration Unix timestamp in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of Unix timestamps (-1 if no expiry, -2 if field missing).
Redis command documentation: CommandName.HEXPIRETIME
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hget(key: KeyT, field: StringT) CommandRequest[AnyStr | None]¶
Return the value of a field in a hash.
- Parameters:
- Returns:
The field value, or
Noneif the field or key does not exist.
Redis command documentation: CommandName.HGET
Hint
Supports client side caching
- hgetall(key: KeyT) CommandRequest[dict[AnyStr, AnyStr]]¶
Return all fields and values in a hash as a mapping.
- Parameters:
key¶ – The key name.
- Returns:
A mapping of field names to values.
Redis command documentation: CommandName.HGETALL
Hint
Supports client side caching
- hgetdel(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Get and delete the value of one or more fields of a given hash key. When the last field is deleted, the key will also be deleted.
- Parameters:
- Returns:
the values of the fields requested (Missing fields are returned as
None)
Redis command documentation: CommandName.HGETDEL
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hgetex(key: KeyT, fields: Parameters[StringT], ex: int | datetime.timedelta | None = None, px: int | datetime.timedelta | None = None, exat: int | datetime.datetime | None = None, pxat: int | datetime.datetime | None = None, persist: bool | None = None) CommandRequest[tuple[AnyStr | None, ...]]¶
Get the value of one or more fields of a given hash key and optionally set their expiration time or time-to-live (TTL).
- Parameters:
key¶ – The key of the hash
fields¶ – The fields to get values for
ex¶ – Set the expiry of the fields to
exsecondspx¶ – Set the expiry of the fields to
pxmillisecondsexat¶ – Set the expiry of the fields to the specified Unix time (seconds).
pxat¶ – Set the expiry of the fields to the specified Unix time (milliseconds).
persist¶ – Remove TTL from the fields.
- Returns:
the values of each of the fields requested (Missing fields are returned as
None)
Redis command documentation: CommandName.HGETEX
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hincrby(key: KeyT, field: StringT, increment: int) CommandRequest[int]¶
Increment the integer value of a hash field by the given amount.
- Parameters:
- Returns:
The value of the field after the increment.
Redis command documentation: CommandName.HINCRBY
- hincrbyfloat(key: KeyT, field: StringT, increment: int | float) CommandRequest[float]¶
Increment the float value of a hash field by the given amount.
- Parameters:
- Returns:
The value of the field after the increment.
Redis command documentation: CommandName.HINCRBYFLOAT
- hkeys(key: KeyT) CommandRequest[tuple[AnyStr, ...]]¶
Return all field names in a hash.
- Parameters:
key¶ – The key name.
- Returns:
A tuple of field names.
Redis command documentation: CommandName.HKEYS
Hint
Supports client side caching
- hlen(key: KeyT) CommandRequest[int]¶
Return the number of fields in a hash.
- Parameters:
key¶ – The key name.
- Returns:
The number of fields.
Redis command documentation: CommandName.HLEN
Hint
Supports client side caching
- hmget(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Return the values of multiple hash fields in one call.
- Parameters:
- Returns:
A tuple of values in the same order as fields.
Nonefor missing fields.
Redis command documentation: CommandName.HMGET
Hint
Supports client side caching
- hmset(key: KeyT, field_values: Mapping[MappingKeyT, ValueT]) CommandRequest[bool]¶
Set multiple field-value pairs in a hash.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.HMSET
Caution
Deprecated in Redis version: 4.0.0 Use
hset()with multiple field-value pairs
- hpersist(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Remove the expiration from one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that had TTL removed, 0 for each that did not.
Redis command documentation: CommandName.HPERSIST
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpire(key: KeyT, milliseconds: int | datetime.timedelta, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set a TTL in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HPEXPIRE
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpireat(key: KeyT, unix_time_milliseconds: int | datetime.datetime, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set an absolute expiration Unix timestamp (milliseconds) for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HPEXPIREAT
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpiretime(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the expiration Unix timestamp in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of Unix timestamps in ms (-1 if no expiry, -2 if field missing).
Redis command documentation: CommandName.HPEXPIRETIME
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpttl(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the TTL in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of TTLs in milliseconds (-1 if no expiry, -2 if field or key missing).
Redis command documentation: CommandName.HPTTL
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hrandfield(key: KeyT, *, count: int | None = None, withvalues: bool | None = None) CommandRequest[AnyStr | tuple[AnyStr, ...] | dict[AnyStr, AnyStr] | None]¶
Return one or more random fields from a hash, optionally with values.
- Parameters:
- Returns:
A single field, a tuple of fields, a dict (if withvalues), or
Noneif key is empty.
Redis command documentation: CommandName.HRANDFIELD
Compatibility:
New in Redis version: 6.2.0
- hscan(key: KeyT, cursor: int | None = None, match: StringT | None = None, count: int | None = None, novalues: bool | None = None) CommandRequest[tuple[int, dict[AnyStr, AnyStr] | tuple[AnyStr, ...]]]¶
Incrementally iterate over fields (and optionally values) in a hash.
- Parameters:
- Returns:
A tuple of
(next_cursor, mapping).If
novaluesis set, a tuple of(next_cursor, fields)
next_cursor0 means done.
Redis command documentation: CommandName.HSCAN
Compatibility:
novalues: New in Redis version: 7.4.0
- async hscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None, novalues: Literal[True] | None = None) AsyncGenerator[tuple[AnyStr, AnyStr], None] | AsyncGenerator[AnyStr, None]¶
Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.
- hset(key: KeyT, field_values: Mapping[MappingKeyT, ValueT]) CommandRequest[int]¶
Set one or more field-value pairs in a hash.
- Parameters:
- Returns:
The number of fields that were added (new fields only).
Redis command documentation: CommandName.HSET
- hsetex(key: KeyT, field_values: Mapping[MappingKeyT, ValueT], condition: Literal[PureToken.FNX, PureToken.FXX] | 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) CommandRequest[bool]¶
Set the value of one or more fields of a given hash key, and optionally set their expiration time or time-to-live (TTL).
- Parameters:
key¶ – The key of the hash
field_values¶ – Mapping of fields and the values to set
condition¶ – If
FNXonly set the fields if none of them exist, ifFXXonly set the fields if all of them already existsex¶ – Set the expiry of the fields to
exsecondspx¶ – Set the expiry of the fields to
pxmillisecondsexat¶ – Set the expiry of the fields to the specified Unix time (seconds).
pxat¶ – Set the expiry of the fields to the specified Unix time (milliseconds).
keepttl¶ – Retain the TTL already associated with the fields.
- Returns:
Trueif all the fields were successfully set
Redis command documentation: CommandName.HSETEX
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hsetnx(key: KeyT, field: StringT, value: ValueT) CommandRequest[bool]¶
Set a hash field only if it does not already exist.
- Parameters:
- Returns:
Trueif the field was set,Falseif it already existed.
Redis command documentation: CommandName.HSETNX
- hstrlen(key: KeyT, field: StringT) CommandRequest[int]¶
Return the length of the string value of a hash field.
- Parameters:
- Returns:
The length in bytes, or 0 if the field or key does not exist.
Redis command documentation: CommandName.HSTRLEN
Hint
Supports client side caching
- httl(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the TTL in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of TTLs in seconds (-1 if no expiry, -2 if field or key missing).
Redis command documentation: CommandName.HTTL
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hvals(key: KeyT) CommandRequest[tuple[AnyStr, ...]]¶
Return all values in a hash.
- Parameters:
key¶ – The key name.
- Returns:
A tuple of values. Empty tuple if the key does not exist.
Redis command documentation: CommandName.HVALS
Hint
Supports client side caching
- 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"
- incr(key: KeyT) CommandRequest[int]¶
Increment the integer value of a key by one.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key after the increment (1 if the key did not exist).
Redis command documentation: CommandName.INCR
- incrby(key: KeyT, increment: int) CommandRequest[int]¶
Increment the integer value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the increment (increment if key did not exist).
Redis command documentation: CommandName.INCRBY
- incrbyfloat(key: KeyT, increment: int | float) CommandRequest[float]¶
Increment the float value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the increment (increment if key did not exist).
Redis command documentation: CommandName.INCRBYFLOAT
- info(*sections: StringT) CommandRequest[dict[str, ResponseType]]¶
Return server information and statistics.
- Parameters:
sections¶ – Optional section names (e.g. server, memory, stats); default all.
- Returns:
Dict of section name to section data (parsed).
Redis command documentation: CommandName.INFO
- keys(pattern: StringT = '*') CommandRequest[set[AnyStr]]¶
Return all key names matching the given glob pattern.
- Parameters:
pattern¶ – Glob pattern (e.g.
*,user:*).- Returns:
A set of matching key names.
Redis command documentation: CommandName.KEYS
- lastsave() CommandRequest[datetime]¶
Return the time of the last successful background save to disk.
- Returns:
Datetime of last save.
Redis command documentation: CommandName.LASTSAVE
- latency_doctor() CommandRequest¶
Return a human-readable latency analysis report.
- Returns:
Report string.
Redis command documentation: CommandName.LATENCY_DOCTOR
Added in version 3.0.0.
- latency_graph(event: StringT) CommandRequest¶
Return an ASCII latency graph for the given event.
- Parameters:
event¶ – Event name (e.g. command name).
- Returns:
Graph string.
Redis command documentation: CommandName.LATENCY_GRAPH
Added in version 3.0.0.
- latency_histogram(*commands: StringT) CommandRequest[dict[AnyStr, dict[AnyStr, RedisValueT | dict[AnyStr, RedisValueT]]]]¶
Return the cumulative distribution of latencies for the given or all commands.
- Parameters:
commands¶ – Command names to include (empty = all).
- Returns:
Mapping of command to latency distribution info.
Redis command documentation: CommandName.LATENCY_HISTOGRAM
Compatibility:
New in Redis version: 7.0.0
Added in version 3.2.0.
- latency_history(event: StringT) CommandRequest[tuple[list[int], ...]]¶
Return timestamp-latency samples for the event.
- Parameters:
event¶ – Event name.
- Returns:
Tuple of (timestamp, latency) pairs.
Redis command documentation: CommandName.LATENCY_HISTORY
Added in version 3.0.0.
- latency_latest() CommandRequest[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: CommandName.LATENCY_LATEST
Added in version 3.0.0.
- latency_reset(*events: StringT) CommandRequest[int]¶
Reset latency data for one or more events.
- Returns:
the number of event time series that were reset.
Redis command documentation: CommandName.LATENCY_RESET
Added in version 3.0.0.
- lcs(key1: KeyT, key2: KeyT, *, len_: bool | None = None, idx: bool | None = None, minmatchlen: int | None = None, withmatchlen: bool | None = None) CommandRequest | CommandRequest[int] | CommandRequest[LCSResult]¶
Find the longest common substring between two string keys.
- Parameters:
- Returns:
The matched string (default), the length (if len_), or match positions and optionally lengths (if idx). Type depends on arguments.
Redis command documentation: CommandName.LCS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- lindex(key: KeyT, index: int) CommandRequest[AnyStr | None]¶
Return the element at index in the list.
- Parameters:
- Returns:
The element at that index, or
Noneif index is out of range.
Redis command documentation: CommandName.LINDEX
Hint
Supports client side caching
- linsert(key: KeyT, where: Literal[PureToken.AFTER, PureToken.BEFORE], pivot: ValueT, element: ValueT) CommandRequest[int]¶
Insert an element in the list before or after a pivot value.
- Parameters:
- Returns:
The length of the list after the insert, or -1 if pivot was not found.
Redis command documentation: CommandName.LINSERT
- llen(key: KeyT) CommandRequest[int]¶
Return the length of the list stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The length of the list (0 if key does not exist).
Redis command documentation: CommandName.LLEN
Hint
Supports client side caching
- lmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT]) CommandRequest[AnyStr | None]¶
Atomically pop an element from one list and push it to another.
- Parameters:
- Returns:
The element that was moved.
Redis command documentation: CommandName.LMOVE
Compatibility:
New in Redis version: 6.2.0
- lmpop(keys: Parameters[KeyT], where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) CommandRequest[list[AnyStr | list[AnyStr]] | None]¶
Pop elements from the first non-empty list among the given keys.
- Parameters:
- Returns:
Noneif all lists are empty; otherwise [key_name, [elements]].
Redis command documentation: CommandName.LMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- lolwut(version: int | None = None) CommandRequest[str]¶
Get the Redis version and a piece of generative computer art
Redis command documentation: CommandName.LOLWUT
- lpop(key: KeyT, count: int | None = None) CommandRequest[AnyStr | None] | CommandRequest[list[AnyStr] | None]¶
Remove and return the first element(s) from the list.
- Parameters:
- Returns:
The first element, or a list of elements if count is set;
Noneif key is empty or missing.
Redis command documentation: CommandName.LPOP
Compatibility:
count: New in Redis version: 6.2.0
- lpos(key: KeyT, element: ValueT, rank: int | None = None, count: int | None = None, maxlen: int | None = None) CommandRequest[int | None] | CommandRequest[list[int] | None]¶
Return the index of the first (or rank-th) occurrence of element in the list.
- Parameters:
- Returns:
A single index, or a list of indices if count is set;
Noneif no match.
Redis command documentation: CommandName.LPOS
Compatibility:
New in Redis version: 6.0.6
Hint
Supports client side caching
- lpush(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Prepend one or more elements to a list.
- Parameters:
- Returns:
The length of the list after the push.
Redis command documentation: CommandName.LPUSH
- lpushx(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Prepend elements to a list only if the list exists.
- Parameters:
- Returns:
The length of the list after the push (0 if key did not exist).
Redis command documentation: CommandName.LPUSHX
- lrange(key: KeyT, start: int, stop: int) CommandRequest[list[AnyStr]]¶
Return a range of elements from the list (inclusive of both ends).
- Parameters:
- Returns:
A list of elements in the specified range.
Redis command documentation: CommandName.LRANGE
Hint
Supports client side caching
- lrem(key: KeyT, count: int, element: ValueT) CommandRequest[int]¶
Remove occurrences of element from the list. Count controls direction and limit.
- Parameters:
- Returns:
The number of elements removed.
Redis command documentation: CommandName.LREM
- lset(key: KeyT, index: int, element: ValueT) CommandRequest[bool]¶
Set the list element at index to the given value.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.LSET
- ltrim(key: KeyT, start: int, stop: int) CommandRequest[bool]¶
Trim the list to the specified range (inclusive); remove elements outside the range.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.LTRIM
- memory_doctor() CommandRequest¶
Outputs memory problems report
Redis command documentation: CommandName.MEMORY_DOCTOR
Added in version 3.0.0.
- memory_malloc_stats() CommandRequest¶
Show allocator internal stats :return: the memory allocator’s internal statistics report
Redis command documentation: CommandName.MEMORY_MALLOC_STATS
Added in version 3.0.0.
- memory_purge() CommandRequest[bool]¶
Ask the allocator to release memory
Redis command documentation: CommandName.MEMORY_PURGE
Added in version 3.0.0.
- memory_stats() CommandRequest[dict[AnyStr, ValueT]]¶
Show memory usage details :return: mapping of memory usage metrics and their values
Redis command documentation: CommandName.MEMORY_STATS
Added in version 3.0.0.
- memory_usage(key: KeyT, *, samples: int | None = None) CommandRequest[int | None]¶
Estimate the memory usage of a key
- Returns:
the memory usage in bytes, or
Nonewhen the key does not exist.
Redis command documentation: CommandName.MEMORY_USAGE
Added in version 3.0.0.
- mget(keys: Parameters[KeyT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Get the values of multiple keys in a single call.
- Parameters:
keys¶ – One or more key names.
- Returns:
A tuple of values in the same order as keys;
Nonefor missing keys.
Redis command documentation: CommandName.MGET
- 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) CommandRequest[bool]¶
Atomically transfer one or more keys from this instance to another Redis instance.
- Parameters:
host¶ – Host of the target instance.
port¶ – Port of the target instance.
destination_db¶ – Database index on the target.
timeout¶ – Maximum idle time for the connection in milliseconds.
keys¶ – One or more key names to migrate.
copy¶ – If
True, copy the key instead of moving it.replace¶ – If
True, replace existing keys on the target.auth¶ – Password for the target (legacy).
username¶ – Username for ACL auth on the target.
password¶ – Password for ACL auth on the target.
- Returns:
Trueon success indicates keys were found and transferred.
Redis command documentation: CommandName.MIGRATE
Added in version 3.0.0.
- module_list() CommandRequest[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
nameandver
Redis command documentation: CommandName.MODULE_LIST
Added in version 3.2.0.
- module_load(path: StringT, *args: str | bytes | int | float) CommandRequest[bool]¶
Load a module
Redis command documentation: CommandName.MODULE_LOAD
Added in version 3.2.0.
- module_loadex(path: StringT, configs: dict[StringT, ValueT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[bool]¶
Loads a module from a dynamic library at runtime with configuration directives.
Redis command documentation: CommandName.MODULE_LOADEX
Compatibility:
New in Redis version: 7.0.0
Added in version 3.4.0.
- module_unload(name: StringT) CommandRequest[bool]¶
Unload a module by name.
- Parameters:
name¶ – Module name to unload.
- Returns:
Trueon success.
Redis command documentation: CommandName.MODULE_UNLOAD
Added in version 3.2.0.
- move(key: KeyT, db: int) CommandRequest[bool]¶
Move a key from the currently selected database to the specified database.
- Parameters:
- Returns:
Trueif the key was moved,Falseif it already existed in the target db.
Redis command documentation: CommandName.MOVE
- mset(key_values: Mapping[KeyT, ValueT]) CommandRequest[bool]¶
Set multiple keys to their respective values in one operation.
- Parameters:
key_values¶ – Mapping of key names to string values.
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.MSET
- msetex(key_values: Mapping[KeyT, ValueT], *, condition: Literal[PureToken.NX, PureToken.XX] | 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) CommandRequest[bool]¶
Atomically set multiple string keys with an optional shared expiration.
- Parameters:
key_values¶ – Mapping of key names to string values.
condition¶ – Optional NX (only if not exists) or XX (only if exists).
ex¶ – Expire keys after this many seconds (relative).
px¶ – Expire keys after this many milliseconds (relative).
exat¶ – Expire keys at this Unix timestamp in seconds (absolute).
pxat¶ – Expire keys at this Unix timestamp in milliseconds (absolute).
keepttl¶ – If
True, retain existing TTL on keys that have one.
- Returns:
Trueif all keys were set.
Redis command documentation: CommandName.MSETEX
Compatibility:
New in Redis version: 8.4.0
- msetnx(key_values: Mapping[KeyT, ValueT]) CommandRequest[bool]¶
Set multiple keys to multiple values only if none of the keys exist.
- Parameters:
key_values¶ – Mapping of key names to string values.
- Returns:
Trueif all keys were set,Falseif any key already existed.
Redis command documentation: CommandName.MSETNX
- object_encoding(key: KeyT) CommandRequest[AnyStr | None]¶
Return the internal encoding for the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The encoding string (e.g. int, ziplist), or
Noneif the key does not exist.
Redis command documentation: CommandName.OBJECT_ENCODING
- object_freq(key: KeyT) CommandRequest[int]¶
Return the logarithmic access frequency counter for the object stored at key (LFU).
- Parameters:
key¶ – The key name.
- Returns:
The counter value.
Redis command documentation: CommandName.OBJECT_FREQ
- object_idletime(key: KeyT) CommandRequest[int]¶
Return the time in seconds since the last access to the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The idle time in seconds.
Redis command documentation: CommandName.OBJECT_IDLETIME
- object_refcount(key: KeyT) CommandRequest[int]¶
Return the reference count of the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The number of references.
Redis command documentation: CommandName.OBJECT_REFCOUNT
- persist(key: KeyT) CommandRequest[bool]¶
Remove the expiration from a key so it no longer expires.
- Parameters:
key¶ – The key name.
- Returns:
Trueif the expiration was removed,Falseif the key had no expiry.
Redis command documentation: CommandName.PERSIST
- pexpire(key: KeyT, milliseconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set a key’s time to live in milliseconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.PEXPIRE
Compatibility:
condition: New in Redis version: 7.0.0
- pexpireat(key: KeyT, unix_time_milliseconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set the expiration for a key to an absolute Unix timestamp in milliseconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.PEXPIREAT
Compatibility:
condition: New in Redis version: 7.0.0
- pexpiretime(key: KeyT) CommandRequest[datetime]¶
Return the expiration Unix timestamp for a key in milliseconds.
- Parameters:
key¶ – The key name.
- Returns:
Expiration as datetime (ms). -1 if no expiry, -2 if key does not exist.
Redis command documentation: CommandName.PEXPIRETIME
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- pfadd(key: KeyT, *elements: ValueT) CommandRequest[bool]¶
Add the specified elements to the HyperLogLog at key.
- Parameters:
- Returns:
Trueif at least one internal register was altered.
Redis command documentation: CommandName.PFADD
- pfcount(keys: Parameters[KeyT]) CommandRequest[int]¶
Return the approximated cardinality of the set(s) observed by the HyperLogLog(s) at key(s).
- Parameters:
keys¶ – One or more HyperLogLog key names.
- Returns:
The approximated number of unique elements.
Redis command documentation: CommandName.PFCOUNT
- pfmerge(destkey: KeyT, sourcekeys: Parameters[KeyT]) CommandRequest[bool]¶
Merge multiple HyperLogLogs into a single one at the destination key.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.PFMERGE
- ping(message: StringT | None = None) CommandRequest¶
Ping the server to test the connection.
- Parameters:
message¶ – Optional message; if provided, server echoes it instead of PONG.
- Returns:
PONGor the echoed message.
Redis command documentation: CommandName.PING
- psetex(key: KeyT, milliseconds: int | timedelta, value: ValueT) CommandRequest[bool]¶
Set the value of a key with an expiration in milliseconds.
- Parameters:
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.PSETEX
- pttl(key: KeyT) CommandRequest[int]¶
Return the number of milliseconds until the key will expire.
- Parameters:
key¶ – The key name.
- Returns:
TTL in milliseconds. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.PTTL
- publish(channel: StringT, message: ValueT) CommandRequest[int]¶
Publish a message to a channel.
- Parameters:
- Returns:
Number of subscribers that received the message.
Redis command documentation: CommandName.PUBLISH
- pubsub_channels(pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Return channel names that have at least one subscriber.
- Parameters:
pattern¶ – Optional glob pattern (default
*).- Returns:
Set of channel names.
Redis command documentation: CommandName.PUBSUB_CHANNELS
- pubsub_numpat() CommandRequest[int]¶
Return the number of unique pattern subscriptions (PSUBSCRIBE) on this server.
- Returns:
Number of pattern subscriptions.
Redis command documentation: CommandName.PUBSUB_NUMPAT
- pubsub_numsub(*channels: StringT) CommandRequest[dict[AnyStr, int]]¶
Return the number of subscribers for each given channel.
- Parameters:
channels¶ – Channel names to query (empty = all with 0).
- Returns:
Mapping of channel name to subscriber count.
Redis command documentation: CommandName.PUBSUB_NUMSUB
- pubsub_shardchannels(pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Return shard channel names that have at least one subscriber.
- Parameters:
pattern¶ – Optional glob pattern (default
*).- Returns:
Set of shard channel names.
Redis command documentation: CommandName.PUBSUB_SHARDCHANNELS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.6.0.
- pubsub_shardnumsub(*channels: StringT) CommandRequest[dict[AnyStr, int]]¶
Return the number of subscribers for each given shard channel.
- Parameters:
channels¶ – Shard channel names to query (empty = all with 0).
- Returns:
Mapping of shard channel name to subscriber count.
Redis command documentation: CommandName.PUBSUB_SHARDNUMSUB
- quit() CommandRequest[bool]¶
Close the connection to the server.
- Returns:
Trueon success.
Redis command documentation: CommandName.QUIT
Caution
Deprecated in Redis version: 7.1.240
- randomkey() CommandRequest[AnyStr | None]¶
Return a random key name from the currently selected database.
- Returns:
A key name, or
Nonewhen the database is empty.
Redis command documentation: CommandName.RANDOMKEY
- readonly() CommandRequest[bool]¶
Enable read queries for this connection to a cluster replica node.
- Returns:
Trueon success.
Redis command documentation: CommandName.READONLY
Added in version 3.2.0.
- readwrite() CommandRequest[bool]¶
Disable read-only mode; use this connection for read and write to the primary.
- Returns:
Trueon success.
Redis command documentation: CommandName.READWRITE
Added in version 3.2.0.
- async register_library(name: StringT, code: StringT, replace: bool = False) Library¶
Register a new library
- Parameters:
Added in version 3.1.0.
- register_script(script: RedisValueT) Script¶
Registers a Lua
script- Returns:
A
coredis.commands.script.Scriptinstance that is callable and hides the complexity of dealing with scripts, keys, and shas.
- rename(key: KeyT, newkey: KeyT) CommandRequest[bool]¶
Rename a key to a new name (overwrites newkey if it exists).
Redis command documentation: CommandName.RENAME
- renamenx(key: KeyT, newkey: KeyT) CommandRequest[bool]¶
Rename a key only if the new name does not already exist.
- Parameters:
- Returns:
Trueif the key was renamed,Falseif newkey already exists.
Redis command documentation: CommandName.RENAMENX
- replicaof(host: StringT | None = None, port: int | None = None) CommandRequest[bool]¶
Make the server a replica of the instance at host and port; no args to promote to master.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.REPLICAOF
Added in version 3.0.0.
- reset() CommandRequest[None]¶
Reset the connection (clear client state; server may disconnect).
- Returns:
None.
Redis command documentation: CommandName.RESET
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- 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) CommandRequest[bool]¶
Create a key from a serialized value (e.g. from dump).
- Parameters:
key¶ – The key name to create.
ttl¶ – TTL in milliseconds, or datetime for absolute expiry if absttl.
serialized_value¶ – The serialized value (bytes from dump).
replace¶ – If
True, overwrite existing key.absttl¶ – If
True, ttl is an absolute Unix timestamp in ms.idletime¶ – Optional idle time in seconds before eviction.
freq¶ – Optional access frequency for LFU eviction.
- Returns:
Trueon success.
Redis command documentation: CommandName.RESTORE
- role() CommandRequest[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: CommandName.ROLE
- rpop(key: KeyT, count: int | None = None) CommandRequest[AnyStr | None] | CommandRequest[list[AnyStr] | None]¶
Remove and return the last element(s) from the list.
- Parameters:
- Returns:
The last element, or a list if count is set;
Noneif key is empty or missing.
Redis command documentation: CommandName.RPOP
Compatibility:
count: New in Redis version: 6.2.0
- rpoplpush(source: KeyT, destination: KeyT) CommandRequest[AnyStr | None]¶
Atomically pop the last element from source and prepend it to destination.
- Parameters:
- Returns:
The element that was moved.
Redis command documentation: CommandName.RPOPLPUSH
Caution
Deprecated in Redis version: 6.2.0 Use
lmove()with the wherefrom and whereto arguments
- rpush(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Append one or more elements to a list.
- Parameters:
- Returns:
The length of the list after the push.
Redis command documentation: CommandName.RPUSH
- rpushx(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Append elements to a list only if the list exists.
- Parameters:
- Returns:
The length of the list after the push (0 if key did not exist).
Redis command documentation: CommandName.RPUSHX
- sadd(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Add one or more members to a set.
- Parameters:
- Returns:
The number of members that were added (excluding those already in the set).
Redis command documentation: CommandName.SADD
- save() CommandRequest[bool]¶
Tells the Redis server to save its data to disk, blocking until the save is complete
Redis command documentation: CommandName.SAVE
- scan(cursor: int | None = 0, match: StringT | None = None, count: int | None = None, type_: StringT | None = None) CommandRequest[tuple[int, tuple[AnyStr, ...]]]¶
Incrementally iterate over the key space using a cursor.
- Parameters:
- Returns:
A tuple of
(next_cursor, tuple_of_keys).next_cursor0 means done.
Redis command documentation: CommandName.SCAN
- 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.
- scard(key: KeyT) CommandRequest[int]¶
Return the number of members in a set.
- Parameters:
key¶ – The key name.
- Returns:
The cardinality of the set (0 if key does not exist).
Redis command documentation: CommandName.SCARD
Hint
Supports client side caching
- script_debug(mode: Literal[PureToken.NO, PureToken.SYNC, PureToken.YES]) CommandRequest[bool]¶
Set the debug mode for executed scripts
- Raises:
Redis command documentation: CommandName.SCRIPT_DEBUG
Added in version 3.0.0.
- script_exists(sha1s: Parameters[StringT]) CommandRequest[tuple[bool, ...]]¶
Check whether the given scripts exist in the server script cache.
- Parameters:
sha1s¶ – One or more SHA1 digests of scripts.
- Returns:
Tuple of booleans, one per digest (
Trueif cached).
Redis command documentation: CommandName.SCRIPT_EXISTS
- script_flush(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Remove all scripts from the server script cache.
- Parameters:
flush_type¶ – ASYNC (default) or SYNC.
- Returns:
Trueon success.
Redis command documentation: CommandName.SCRIPT_FLUSH
Compatibility:
sync_type: New in Redis version: 6.2.0
- script_kill() CommandRequest[bool]¶
Terminate the currently running Lua script (if any).
- Returns:
Trueif a script was killed.
Redis command documentation: CommandName.SCRIPT_KILL
- script_load(script: StringT) CommandRequest¶
Load a Lua script into the server script cache.
- Parameters:
script¶ – The Lua script source code.
- Returns:
The SHA1 digest of the script.
Redis command documentation: CommandName.SCRIPT_LOAD
- sdiff(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the difference of the first set and all successive sets (members in first but not in others).
- Parameters:
keys¶ – One or more set key names (first is the base set).
- Returns:
A set of members in the difference.
Redis command documentation: CommandName.SDIFF
- sdiffstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set difference and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SDIFFSTORE
- select(index: int) CommandRequest[bool]¶
Change the selected database for the current connection.
- Parameters:
index¶ – The database index (typically 0-15).
- Returns:
Trueon success.
Redis command documentation: CommandName.SELECT
Warning
Using
selectdirectly is not recommended. Use the db argument when initializing the client to ensure that all connections originating from this client use the desired database numberAdded in version 3.0.0.
- sentinel_config_get(name: RedisValueT) CommandRequest[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:
New in Redis version: 6.2.0
- sentinel_config_set(name: RedisValueT, value: RedisValueT) CommandRequest[bool]¶
Set the value of a global Sentinel configuration parameter
Compatibility:
New in Redis version: 6.2
- sentinel_failover(service_name: StringT) CommandRequest[bool]¶
Force a failover as if the master was not reachable, and without asking for agreement to other Sentinels
- sentinel_flushconfig() CommandRequest[bool]¶
Force Sentinel to rewrite its configuration on disk, including the current Sentinel state.
- sentinel_get_master_addr_by_name(service_name: StringT) CommandRequest[tuple[str, int] | None]¶
Returns a (host, port) pair for the given
service_name
- sentinel_infocache(*nodenames: StringT) CommandRequest[dict[AnyStr, dict[int, dict[str, ResponsePrimitive]]]]¶
Return cached INFO output from masters and replicas.
- sentinel_master(service_name: StringT) CommandRequest[dict[str, ResponsePrimitive]]¶
Returns a dictionary containing the specified masters state.
- sentinel_masters() CommandRequest[dict[str, dict[str, ResponsePrimitive]]]¶
Returns a list of dictionaries containing each master’s state.
- sentinel_monitor(name: RedisValueT, ip: RedisValueT, port: int, quorum: int) CommandRequest[bool]¶
Adds a new master to Sentinel to be monitored
- sentinel_myid() CommandRequest¶
Return the ID of the Sentinel instance Compatibility:
New in Redis version: 6.2.0
- sentinel_remove(name: RedisValueT) CommandRequest[bool]¶
Removes a master from Sentinel’s monitoring
- sentinel_replicas(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of replicas for
service_name
- sentinel_reset(pattern: StringT) CommandRequest[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.
- sentinel_sentinels(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of sentinels for
service_name
- sentinel_set(name: RedisValueT, option: RedisValueT, value: RedisValueT) CommandRequest[bool]¶
Sets Sentinel monitoring parameters for a given master
- sentinel_slaves(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of slaves for paramref:service_name
- 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, ifeq: ValueT | None = None, ifne: ValueT | None = None, ifdeq: ValueT | None = None, ifdne: ValueT | None = None) CommandRequest[AnyStr | bool | None]¶
Set the string value of a key with optional condition and expiration.
- Parameters:
key¶ – The key name.
value¶ – The string value to set.
condition¶ – NX (set only if not exists) or XX (set only if exists).
get¶ – If
True, return the previous value (orNone); aborts if not a string.ex¶ – Expire after this many seconds (relative).
px¶ – Expire after this many milliseconds (relative).
exat¶ – Expire at this Unix timestamp in seconds (absolute).
pxat¶ – Expire at this Unix timestamp in milliseconds (absolute).
keepttl¶ – If
True, retain the existing TTL.ifeq¶ – Set only if current value equals this value.
ifne¶ – Set only if current value does not equal this value.
ifdeq¶ – Set only if current hash digest equals this value.
ifdne¶ – Set only if current hash digest does not equal this value.
- Returns:
True/Falseif the set operation succeeded unlessgetisTrue, in which case the previous value orNoneif the key didn’t exist.
Redis command documentation: CommandName.SET
Compatibility:
exat: New in Redis version: 6.2.0pxat: New in Redis version: 6.2.0get: New in Redis version: 6.2.0ifeq: New in Redis version: 8.4.0ifne: New in Redis version: 8.4.0ifdeq: New in Redis version: 8.4.0ifdne: New in Redis version: 8.4.0
- setbit(key: KeyT, offset: int, value: int) CommandRequest[int]¶
Set or clear the bit at the given offset in the string value at key.
- Parameters:
- Returns:
Previous bit value at that offset.
Redis command documentation: CommandName.SETBIT
- setex(key: KeyT, value: ValueT, seconds: int | timedelta) CommandRequest[bool]¶
Set the value of a key with an expiration in seconds.
- Parameters:
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.SETEX
- setnx(key: KeyT, value: ValueT) CommandRequest[bool]¶
Set the value of a key only if the key does not exist.
- Parameters:
- Returns:
Trueif the key was set,Falseif it already existed.
Redis command documentation: CommandName.SETNX
- setrange(key: KeyT, offset: int, value: ValueT) CommandRequest[int]¶
Overwrite part of the string value at a key starting at the given offset.
If offset plus value length exceeds the current length, the string is extended. If offset is past the end, the gap is padded with zero bytes.
- Parameters:
- Returns:
The length of the string after the operation.
Redis command documentation: CommandName.SETRANGE
- shutdown(nosave_save: Literal[PureToken.NOSAVE, PureToken.SAVE] | None = None, *, now: bool | None = None, force: bool | None = None, abort: bool | None = None) CommandRequest[bool]¶
Stop the Redis server (optionally save, nosave, now, force, or abort).
- Parameters:
- Returns:
Trueon success (connection will close).
Redis command documentation: CommandName.SHUTDOWN
Compatibility:
now: New in Redis version: 7.0.0force: New in Redis version: 7.0.0abort: New in Redis version: 7.0.0
- sinter(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the intersection of all given sets.
- Parameters:
keys¶ – One or more set key names.
- Returns:
A set of members in the intersection.
Redis command documentation: CommandName.SINTER
- sintercard(keys: Parameters[KeyT], limit: int | None = None) CommandRequest[int]¶
Return the cardinality of the intersection of multiple sets.
- Parameters:
- Returns:
The number of elements in the resulting intersection.
Redis command documentation: CommandName.SINTERCARD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- sinterstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set intersection and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SINTERSTORE
- sismember(key: KeyT, member: ValueT) CommandRequest[bool]¶
Return whether the given value is a member of the set.
- Parameters:
- Returns:
Trueif member is in the set,Falseotherwise or if key does not exist.
Redis command documentation: CommandName.SISMEMBER
Hint
Supports client side caching
- slaveof(host: StringT | None = None, port: int | None = None) CommandRequest[bool]¶
Make the server a replica of the instance at host and port; no args to promote to master.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.SLAVEOF
Caution
Deprecated in Redis version: 5.0.0 Use
replicaof()
- slowlog_get(count: int | None = None) CommandRequest[tuple[SlowLogInfo, ...]]¶
Return entries from the slow query log.
- Parameters:
count¶ – Limit to this many most recent entries (optional).
- Returns:
Tuple of slowlog entry dicts (id, timestamp, duration, command, client, name).
Redis command documentation: CommandName.SLOWLOG_GET
- slowlog_len() CommandRequest[int]¶
Return the number of entries currently in the slow log.
- Returns:
The number of slow log entries.
Redis command documentation: CommandName.SLOWLOG_LEN
- slowlog_reset() CommandRequest[bool]¶
Remove all entries from the slow log.
- Returns:
Trueon success.
Redis command documentation: CommandName.SLOWLOG_RESET
- smembers(key: KeyT) CommandRequest[set[AnyStr]]¶
Return all members of a set.
- Parameters:
key¶ – The key name.
- Returns:
A set of all members; empty set if the key does not exist.
Redis command documentation: CommandName.SMEMBERS
Hint
Supports client side caching
- smismember(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[bool, ...]]¶
Return whether each given value is a member of the set.
- Parameters:
- Returns:
A tuple of booleans in the same order as members.
Redis command documentation: CommandName.SMISMEMBER
Compatibility:
New in Redis version: 6.2.0
Hint
Supports client side caching
- smove(source: KeyT, destination: KeyT, member: ValueT) CommandRequest[bool]¶
Move a member from one set to another (atomic).
- Parameters:
- Returns:
Trueif the member was moved,Falseif it was not in source.
Redis command documentation: CommandName.SMOVE
- 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) CommandRequest[tuple[AnyStr, ...] | int]¶
Sort elements in a list, set, or sorted set, optionally storing the result.
- Parameters:
key¶ – The key name.
gets¶ – Optional keys or patterns to retrieve external values (e.g. *->field).
offset¶ – Skip this many elements (use with count for LIMIT).
count¶ – Return this many elements (use with offset).
order¶ – ASC or DESC.
alpha¶ – If
True, sort lexicographically.store¶ – If set, store the result in this key instead of returning.
- Returns:
A tuple of sorted elements, or the number of stored elements if store is set.
Redis command documentation: CommandName.SORT
- 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) CommandRequest[tuple[AnyStr, ...]]¶
Sort the elements in a list, set or sorted set. Read-only variant of SORT.
- Returns:
sorted elements.
Redis command documentation: CommandName.SORT_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- spop(key: KeyT, count: int | None = None) CommandRequest | CommandRequest[set[AnyStr] | None]¶
Remove and return one or more random members from the set.
- Parameters:
- Returns:
A single member, or a set if count is set;
Noneor empty if key is empty/missing.
Redis command documentation: CommandName.SPOP
- spublish(channel: StringT, message: ValueT) CommandRequest[int]¶
Publish a message to a shard channel.
- Parameters:
- Returns:
Number of shard subscribers that received the message (exact node only).
Redis command documentation: CommandName.SPUBLISH
Compatibility:
New in Redis version: 7.0.0
Added in version 3.6.0.
- srandmember(key: KeyT, count: int | None = None) CommandRequest[AnyStr | set[AnyStr]]¶
Return one or more random members from the set (without removing).
- Parameters:
- Returns:
A single member, or a set/tuple if count is set;
Noneor empty if key is empty.
Redis command documentation: CommandName.SRANDMEMBER
- srem(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Remove one or more members from the set.
- Parameters:
- Returns:
The number of members that were removed.
Redis command documentation: CommandName.SREM
- sscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) CommandRequest[tuple[int, set[AnyStr]]]¶
Incrementally iterate over members of a set using a cursor.
- Parameters:
- Returns:
A tuple of (next_cursor, set_of_members); next_cursor 0 means done.
Redis command documentation: CommandName.SSCAN
- 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.
- strlen(key: KeyT) CommandRequest[int]¶
Return the length of the string value stored at a key.
- Parameters:
key¶ – The key name.
- Returns:
The length of the string in bytes, or
0if the key does not exist.
Redis command documentation: CommandName.STRLEN
Hint
Supports client side caching
- substr(key: KeyT, start: int, end: int) CommandRequest¶
Return a substring of the string stored at a key.
- Parameters:
- Returns:
The substring in the given range.
Redis command documentation: CommandName.SUBSTR
Caution
Deprecated in Redis version: 2.0.0 Use
getrange()Hint
Supports client side caching
- sunion(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the union of all given sets.
- Parameters:
keys¶ – One or more set key names.
- Returns:
A set of all members in the union.
Redis command documentation: CommandName.SUNION
- sunionstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set union and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SUNIONSTORE
- swapdb(index1: int, index2: int) CommandRequest[bool]¶
Swaps two Redis databases
Redis command documentation: CommandName.SWAPDB
Added in version 3.0.0.
- time() CommandRequest[datetime]¶
Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).
Redis command documentation: CommandName.TIME
- property timeseries: TimeSeries¶
Property to access
TimeSeriescommands.Added in version 4.12.0.
- touch(keys: Parameters[KeyT]) CommandRequest[int]¶
Update the last access time of one or more keys (only existing keys are counted).
- Parameters:
keys¶ – One or more key names.
- Returns:
The number of keys that existed and were touched.
Redis command documentation: CommandName.TOUCH
- ttl(key: KeyT) CommandRequest[int]¶
Return the time to live for a key in seconds.
- Parameters:
key¶ – The key name.
- Returns:
TTL in seconds. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.TTL
- type(key: KeyT) CommandRequest[AnyStr | None]¶
Return the type of the value stored at key.
- Parameters:
key¶ – The key name.
- Returns:
One of string, list, set, zset, hash, stream, etc.;
Noneif key does not exist.
Redis command documentation: CommandName.TYPE
Hint
Supports client side caching
- unlink(keys: Parameters[KeyT]) CommandRequest[int]¶
Delete keys asynchronously in a background thread (non-blocking).
- Parameters:
keys¶ – One or more key names to unlink.
- Returns:
The number of keys that were unlinked.
Redis command documentation: CommandName.UNLINK
- vadd(key: KeyT, element: ValueT, values: Parameters[float | int] | bytes, reduce: int | None = None, cas: bool | None = None, quantization: Literal[PureToken.BIN, PureToken.NOQUANT, PureToken.Q8] | None = None, ef: int | None = None, attributes: JsonType | None = None, numlinks: int | None = None) CommandRequest[bool]¶
Add a new element into the vector set specified by key
- Parameters:
key¶ – The key containing the vector set
element¶ – The name of the element being added to the vector set
values¶ – either a byte representation of a 32-bit floating point (FP32) blob of values or a sequence of doubles representing the vector.
reduce¶ – dimensions to reduce the vector values to
cas¶ – whether to add using check-and-set
quantization¶ – The quantization type to use
ef¶ – exploration factor to use when connecting the element to the existing graph
attributes¶ – json attributes to associate with the element
numlinks¶ – maximum number of connections each node in the graph will have with other nodes.
- Returns:
Trueif the element was successfully added to the vector set
Redis command documentation: CommandName.VADD
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vcard(key: KeyT) CommandRequest[int]¶
Return the number of elements in a vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
The number of elements in the vector set
Redis command documentation: CommandName.VCARD
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vdim(key: KeyT) CommandRequest[int]¶
Return the dimension of vectors in the vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
The dimensions of the vectors in the vector set
Redis command documentation: CommandName.VDIM
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vemb(key: KeyT, element: StringT, raw: bool | None = None) CommandRequest[tuple[float, ...] | VectorData | None]¶
Return the vector associated with an element
- Parameters:
- Returns:
Tuple of floats for the vector; if raw is True, VectorData with metadata.
Redis command documentation: CommandName.VEMB
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vgetattr(key: KeyT, element: StringT) CommandRequest[JsonType]¶
Retrieve the JSON attributes of elements
- Parameters:
- Returns:
the attributes of the element or None if they don’t exist.
Redis command documentation: CommandName.VGETATTR
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vinfo(key: KeyT) CommandRequest[dict[AnyStr, AnyStr | int] | None]¶
Return information about a vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
mapping of attributes and values describing the vector set
Redis command documentation: CommandName.VINFO
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vismember(key: KeyT, element: StringT) CommandRequest[bool]¶
Check if an element exists in a vector set
Redis command documentation: CommandName.VISMEMBER
Compatibility:
New in Redis version: 8.2.0
Added in version 5.2.0.
- vlinks(key: KeyT, element: StringT, withscores: bool | None = None) CommandRequest[tuple[tuple[AnyStr, ...] | dict[AnyStr, float], ...] | None]¶
Return the neighbors of an element at each layer in the HNSW graph
- Parameters:
- Returns:
Tuple of layers, each a tuple of neighbours (or mapping to scores if withscores); last is lowest layer.
Redis command documentation: CommandName.VLINKS
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vrandmember(key: KeyT, count: int | None = None) CommandRequest[tuple[AnyStr | None, ...] | AnyStr | None]¶
Return one or multiple random members from a vector set
- Parameters:
- Returns:
A random element, or a tuple of elements if count is specified; negative count allows duplicates.
Redis command documentation: CommandName.VRANDMEMBER
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vrange(key: KeyT, start: StringT, end: StringT, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Retreives all elements inside a vector set (optionally, in small batches with the use of
count)- Parameters:
- Returns:
The elements in lexicographical order within the range
Redis command documentation: CommandName.VRANGE
Compatibility:
New in Redis version: 8.4.0
Added in version 6.0.0.
- vrem(key: KeyT, element: ValueT) CommandRequest[bool]¶
Remove an element from a vector set.
- Parameters:
- Returns:
Trueif the element was successfully deleted from the set
Redis command documentation: CommandName.VREM
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vsetattr(key: KeyT, element: StringT, attributes: JsonType) CommandRequest[bool]¶
Associate or remove the JSON attributes of elements
- Parameters:
- Returns:
Trueif the attributes were successfully set
Redis command documentation: CommandName.VSETATTR
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vsim(key: KeyT, *, element: StringT | None = None, values: Parameters[float] | bytes | None = None, withscores: bool | None = None, withattribs: bool | None = None, count: int | None = None, epsilon: float | None = None, ef: int | None = None, filter: StringT | None = None, filter_ef: int | None = None, truth: bool | None = None, nothread: bool | None = None) CommandRequest[tuple[AnyStr, ...] | dict[AnyStr, float] | dict[AnyStr, JsonType] | dict[AnyStr, tuple[float, JsonType]]]¶
Return elements similar to a given vector or element
- Parameters:
key¶ – The key containing the vector set
element¶ – An existing element to find similar elements for
values¶ – either a byte representation of a 32-bit floating point (FP32) blob of values or a sequence of doubles representing the vector to use as the similarity reference.
withscores¶ – whether to return similarity scores for each result
withattribs¶ – whether to include attributes for for each result
count¶ – number of results to limit to
epsilon¶ – distance threshold; results with distance greater than this are excluded.
ef¶ – Search exploration factor
filter¶ – Expression to restrict matching elements
filter_ef¶ – limits the number of filtering attempts
truth¶ – forces an exact linear scan of all elements bypassing the HSNW graph
nothread¶ – execute the search in the main thread instead of a background thread
- Returns:
Matching elements; optionally with scores (if withscores) and/or attributes (if withattribs).
Redis command documentation: CommandName.VSIM
Compatibility:
New in Redis version: 8.0.0
withattribs: New in Redis version: 8.2epsilon: New in Redis version: 8.2
Added in version 5.0.0.
- wait(numreplicas: int, timeout: int) CommandRequest[int]¶
Block until write commands are replicated to at least the given number of replicas.
- Parameters:
- Returns:
The number of replicas that acknowledged the writes.
Redis command documentation: CommandName.WAIT
Warning
Using
waitdirectly is not recommended. Use theRedis.ensure_replication()orRedisCluster.ensure_replication()context managers to ensure a command is replicated to the number of replicas
- waitaof(numlocal: int, numreplicas: int, timeout: int) CommandRequest[tuple[int, ...]]¶
Block until write commands are synced to AOF on the local host and/or replicas.
- Parameters:
- Returns:
A tuple of (numlocal, numreplicas) that were synced.
Redis command documentation: CommandName.WAITAOF
Compatibility:
New in Redis version: 7.1.240
Warning
Using
waitaofdirectly is not recommended. Use theRedis.ensure_persistence()orRedisCluster.ensure_persistence()context managers to ensure a command is synced to the AOF of the number of local hosts or replicasAdded in version 4.12.0.
- xack(key: KeyT, group: StringT, identifiers: Parameters[ValueT]) CommandRequest[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: CommandName.XACK
- xackdel(key: KeyT, group: StringT, identifiers: Parameters[ValueT], condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[tuple[int, ...]]¶
Acknowledge and optionally delete one or more stream entries for a consumer group.
- Parameters:
- Returns:
Tuple of 1 for each entry that was acked/deleted, 0 for others.
Redis command documentation: CommandName.XACKDEL
Compatibility:
New in Redis version: 8.2.0
Added in version 5.2.0.
- xadd(key: KeyT, field_values: Mapping[MappingKeyT, ValueT], *, identifier: ValueT | None = None, nomkstream: bool | None = None, idmpauto: StringT | None = None, idmp: tuple[StringT, StringT] | None = None, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID] | None = None, threshold: ValueT | None = None, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None, condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[AnyStr | None]¶
Append a new entry to a stream.
- Parameters:
key¶ – The stream key.
field_values¶ – Field names and values for the entry.
identifier¶ – Entry ID, or
*for auto-generated.nomkstream¶ – If
True, do not create the stream if it does not exist.idmpauto¶ – Auto ID mode (e.g. node-id).
idmp¶ – Manual ID range (min, max).
trim_strategy¶ – MAXLEN or MINID for trimming.
threshold¶ – Limit for trim (max length or min id).
trim_operator¶ – EQUAL or APPROXIMATELY for trim.
limit¶ – Max entries to evict per trim (optional).
condition¶ – KEEPREF, DELREF, or ACKED for trim.
- Returns:
The entry ID (auto or specified), or
Noneif nomkstream and key does not exist.
Redis command documentation: CommandName.XADD
Compatibility:
nomkstream: New in Redis version: 6.2.0limit: New in Redis version: 6.2.0condition: New in Redis version: 8.2.0idmpauto: New in Redis version: 8.6.0idmp: New in Redis version: 8.6.0
- xautoclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | timedelta, start: ValueT, count: int | None = None, justid: bool | None = None) CommandRequest[tuple[AnyStr, tuple[AnyStr, ...]] | tuple[AnyStr, tuple[StreamEntry, ...], tuple[AnyStr, ...]]]¶
Transfer ownership of pending stream entries that match the specified criteria to the consumer group specified.
- Parameters:
key¶ – The stream key.
group¶ – Consumer group name.
consumer¶ – Consumer name to assign messages to.
min_idle_time¶ – Only claim entries idle at least this long (ms or timedelta).
start¶ – Start scanning from this ID (e.g.
0-0).count¶ – Max number of entries to claim per call.
justid¶ – If
True, return only entry IDs.
- Returns:
k(next_start_id, claimed_entries) or (next_start_id, claimed_entries, deleted_ids).
Redis command documentation: CommandName.XAUTOCLAIM
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- xcfgset(key: KeyT, idmp_duration: int | timedelta | None = None, idmp_maxsize: int | None = None) CommandRequest[bool]¶
Set IDMP (Idempotent Message Processing) configuration for a stream.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XCFGSET
Compatibility:
New in Redis version: 8.6.0
- 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) CommandRequest[tuple[AnyStr, ...] | tuple[StreamEntry, ...]]¶
Claim (or acquire) ownership of pending messages for a consumer in a group.
- Parameters:
key¶ – The stream key.
group¶ – Consumer group name.
consumer¶ – Consumer name to assign messages to.
min_idle_time¶ – Only claim entries idle at least this long (ms or timedelta).
identifiers¶ – Entry IDs to claim.
idle¶ – Set idle time for claimed entries (ms or timedelta).
time¶ – Set last-delivery time for claimed entries.
retrycount¶ – Set retry count for claimed entries.
force¶ – If
True, claim even if another consumer has them.justid¶ – If
True, return only entry IDs.lastid¶ – Optional last ID for the consumer (streaming).
- Returns:
Tuple of claimed entry IDs, or tuple of stream entries (unless justid).
Redis command documentation: CommandName.XCLAIM
- xdel(key: KeyT, identifiers: Parameters[ValueT]) CommandRequest[int]¶
Remove the specified entries from a stream.
- Parameters:
- Returns:
Number of entries deleted.
Redis command documentation: CommandName.XDEL
- xdelex(key: KeyT, identifiers: Parameters[ValueT], condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[tuple[int, ...]]¶
Delete one or more entries from the stream with optional condition.
- Parameters:
- Returns:
Tuple of 1 for each deleted entry, 0 for skipped.
Redis command documentation: CommandName.XDELEX
Compatibility:
New in Redis version: 8.2
Added in version 5.2.0.
- xgroup_create(key: KeyT, groupname: StringT, identifier: ValueT | None = None, mkstream: bool | None = None, entriesread: int | None = None) CommandRequest[bool]¶
Create a consumer group for the stream.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XGROUP_CREATE
Compatibility:
entriesread: New in Redis version: 7.0.0
- xgroup_createconsumer(key: KeyT, groupname: StringT, consumername: StringT) CommandRequest[bool]¶
Create a consumer in a consumer group.
- Parameters:
- Returns:
Trueif the consumer was created, False if it already existed.
Redis command documentation: CommandName.XGROUP_CREATECONSUMER
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- xgroup_delconsumer(key: KeyT, groupname: StringT, consumername: StringT) CommandRequest[int]¶
Delete a consumer from a consumer group.
- Parameters:
- Returns:
Number of pending messages the consumer had before deletion.
Redis command documentation: CommandName.XGROUP_DELCONSUMER
Added in version 3.0.0.
- xgroup_destroy(key: KeyT, groupname: StringT) CommandRequest[int]¶
Destroy a consumer group.
- Parameters:
- Returns:
Number of groups destroyed (1 or 0).
Redis command documentation: CommandName.XGROUP_DESTROY
- xgroup_setid(key: KeyT, groupname: StringT, identifier: ValueT | None = None, entriesread: int | None = None) CommandRequest[bool]¶
Set the consumer group’s last-delivered ID (e.g. to reprocess or skip).
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XGROUP_SETID
Compatibility:
entriesread: New in Redis version: 7.0.0
Added in version 3.0.0.
- xinfo_consumers(key: KeyT, groupname: StringT) CommandRequest[tuple[dict[AnyStr, AnyStr | int | None], ...]]¶
Return all consumers in a consumer group for the stream.
- Parameters:
- Returns:
Tuple of consumer info dicts (name, pending, idle, etc.).
Redis command documentation: CommandName.XINFO_CONSUMERS
- xinfo_groups(key: KeyT) CommandRequest[tuple[dict[AnyStr, AnyStr | int | None], ...]]¶
Return all consumer groups for the stream.
- Parameters:
key¶ – The stream key.
- Returns:
Tuple of group info dicts (name, consumers, pending, last-delivered-id, etc.).
Redis command documentation: CommandName.XINFO_GROUPS
- xinfo_stream(key: KeyT, full: bool | None = None, count: int | None = None) CommandRequest[StreamInfo]¶
Return information about the stream.
- Parameters:
key¶ – The stream key.
full¶ – If
True, include extended info (seecoredis.response.types.StreamInfo).count¶ – When full is true, limit number of entries in the result.
- Returns:
Stream info (length, groups, first/last entry, etc.; entries if full).
Redis command documentation: CommandName.XINFO_STREAM
- xlen(key: KeyT) CommandRequest[int]¶
Return the number of entries in a stream.
- Parameters:
key¶ – The stream key.
- Returns:
Number of entries in the stream.
Redis command documentation: CommandName.XLEN
- 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) CommandRequest[tuple[StreamPendingExt, ...] | StreamPending]¶
Return information about pending entries (fetched but not acknowledged) for a consumer group.
- Parameters:
- Returns:
Summary (total, min/max ids, consumers) or tuple of pending entry details.
Redis command documentation: CommandName.XPENDING
Compatibility:
idle: New in Redis version: 6.2.0
- xrange(key: KeyT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None) CommandRequest[tuple[StreamEntry, ...]]¶
Return a range of stream entries by ID interval.
- Parameters:
- Returns:
Tuple of stream entries in the range.
Redis command documentation: CommandName.XRANGE
- xread(streams: Mapping[MappingStringKeyT, ValueT], count: int | None = None, block: int | timedelta | None = None) CommandRequest[dict[AnyStr, tuple[StreamEntry, ...]] | None]¶
Read new entries from one or more streams with IDs greater than the given IDs.
- Parameters:
- Returns:
Mapping of stream key to tuple of entries;
Noneif block timeout is exceeded.
Redis command documentation: CommandName.XREAD
- xreadgroup(group: StringT, consumer: StringT, streams: Mapping[MappingStringKeyT, ValueT], count: int | None = None, block: int | timedelta | None = None, noack: bool | None = None) CommandRequest[dict[AnyStr, tuple[StreamEntry, ...]] | None]¶
Read entries from streams as a consumer in a group, with IDs greater than the given IDs.
- Parameters:
group¶ – Consumer group name.
consumer¶ – Consumer name.
streams¶ – Mapping of stream key to last-seen ID (use
>for new for this consumer).count¶ – Max entries to return per stream.
block¶ – Block up to this many milliseconds (or timedelta) for new data.
noack¶ – If
True, do not add messages to PEL (no XACK needed).
- Returns:
Mapping of stream key to tuple of entries;
Noneif block timeout is exceeded.
Redis command documentation: CommandName.XREADGROUP
- xrevrange(key: KeyT, end: ValueT | None = None, start: ValueT | None = None, count: int | None = None) CommandRequest[tuple[StreamEntry, ...]]¶
Return a range of stream entries by ID interval in reverse order.
- Parameters:
- Returns:
Tuple of stream entries in the range, high to low IDs.
Redis command documentation: CommandName.XREVRANGE
- 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, condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[int]¶
Trim the stream by evicting older entries.
- Parameters:
- Returns:
Number of entries removed.
Redis command documentation: CommandName.XTRIM
Compatibility:
limit: New in Redis version: 6.2.0condition: New in Redis version: 8.2.0
- 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) CommandRequest[int | float]¶
Add one or more members to a sorted set, or update their scores.
- Parameters:
key¶ – The key name.
member_scores¶ – Mapping of member names to scores.
condition¶ – NX (only add new) or XX (only update existing).
comparison¶ – GT (only if new score greater) or LT (only if new score less).
change¶ – If
True, return the number of elements changed (added or updated).increment¶ – If
True, add increment to existing score (like zincrby); return new score.
- Returns:
Number of elements added; or number changed if change; or new score if increment; or
Noneif aborted.
Redis command documentation: CommandName.ZADD
Compatibility:
comparison: New in Redis version: 6.2.0
- zcard(key: KeyT) CommandRequest[int]¶
Return the number of members in the sorted set.
- Parameters:
key¶ – The key name.
- Returns:
The cardinality (0 if key does not exist).
Redis command documentation: CommandName.ZCARD
- zcount(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Return the number of members in the sorted set with scores between min and max (inclusive).
- Parameters:
- Returns:
The number of members in the score range.
Redis command documentation: CommandName.ZCOUNT
- zdiff(keys: Parameters[KeyT], withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the difference of the first sorted set and all successive sets (members in first but not in others).
- Parameters:
- Returns:
Members (and optionally scores) in the difference.
Redis command documentation: CommandName.ZDIFF
Compatibility:
New in Redis version: 6.2.0
- zdiffstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute sorted set difference and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZDIFFSTORE
Compatibility:
New in Redis version: 6.2.0
- zincrby(key: KeyT, member: ValueT, increment: int) CommandRequest[float]¶
Increment the score of a member in the sorted set (creates the member with score 0 if missing).
- Parameters:
- Returns:
The new score of the member.
Redis command documentation: CommandName.ZINCRBY
- zinter(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the intersection of multiple sorted sets (aggregating scores by weights and aggregate rule).
- Parameters:
- Returns:
Members (and optionally scores) in the intersection.
Redis command documentation: CommandName.ZINTER
Compatibility:
New in Redis version: 6.2.0
- zintercard(keys: Parameters[KeyT], limit: int | None = None) CommandRequest[int]¶
Return the cardinality of the intersection of multiple sorted sets.
- Parameters:
- Returns:
The number of elements in the resulting intersection.
Redis command documentation: CommandName.ZINTERCARD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- zinterstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None) CommandRequest[int]¶
Compute sorted set intersection and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZINTERSTORE
- zlexcount(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Return the number of members in the sorted set between min and max (lexicographic order).
- Parameters:
- Returns:
The number of members in the range.
Redis command documentation: CommandName.ZLEXCOUNT
Hint
Supports client side caching
- zmpop(keys: Parameters[KeyT], where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) CommandRequest[tuple[AnyStr, tuple[ScoredMember, ...]] | None]¶
Pop members with lowest or highest scores from the first non-empty sorted set.
- Parameters:
- Returns:
Noneif all sets are empty; otherwise (key_name, [(member, score), …]).
Redis command documentation: CommandName.ZMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- zmscore(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[float | None, ...]]¶
Return the scores associated with the given members in the sorted set.
- Parameters:
- Returns:
A tuple of scores in the same order as members;
Nonefor missing members.
Redis command documentation: CommandName.ZMSCORE
Compatibility:
New in Redis version: 6.2.0
Hint
Supports client side caching
- zpopmax(key: KeyT, count: int | None = None) CommandRequest[ScoredMember | tuple[ScoredMember, ...] | None]¶
Remove and return the member(s) with the highest scores in the sorted set.
- Parameters:
- Returns:
A single (member, score) pair, or a tuple of pairs if count is set;
Noneif key is empty.
Redis command documentation: CommandName.ZPOPMAX
- zpopmin(key: KeyT, count: int | None = None) CommandRequest[ScoredMember | tuple[ScoredMember, ...] | None]¶
Remove and return members with the lowest scores in a sorted set
- Returns:
popped elements and scores.
Redis command documentation: CommandName.ZPOPMIN
- zrandmember(key: KeyT, count: int | None = None, withscores: bool | None = None) CommandRequest[AnyStr | tuple[AnyStr, ...] | tuple[ScoredMember, ...] | None]¶
Return one or more random members from the sorted set (without removing).
- Parameters:
- Returns:
A single member, a tuple of members, or (member, score) tuples;
Noneor empty if key is empty.
Redis command documentation: CommandName.ZRANDMEMBER
Compatibility:
New in Redis version: 6.2.0
- 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) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in the sorted set by rank, score, or lexicographic order.
- Parameters:
key¶ – The key name.
min_¶ – Minimum rank, score, or lex (depending on sortby).
max_¶ – Maximum rank, score, or lex (depending on sortby).
sortby¶ – BYSCORE or BYLEX.
rev¶ – If
True, reverse the order (high to low).offset¶ – Skip this many elements (use with count).
count¶ – Return this many elements (use with offset).
withscores¶ – If
True, include scores in the result.
- Returns:
Members (and optionally scores) in the specified range.
Redis command documentation: CommandName.ZRANGE
Compatibility:
sortby: New in Redis version: 6.2.0rev: New in Redis version: 6.2.0offset: New in Redis version: 6.2.0count: New in Redis version: 6.2.0
Hint
Supports client side caching
- zrangebylex(key: KeyT, min_: ValueT, max_: ValueT, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Return a range of members in a sorted set by lexicographical range.
- Parameters:
- Returns:
Tuple of members in the specified lex range.
Redis command documentation: CommandName.ZRANGEBYLEX
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the sortby=BYLEX argumentHint
Supports client side caching
- zrangebyscore(key: KeyT, min_: int | float, max_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in a sorted set by score.
- Parameters:
- Returns:
Tuple of members, or (member, score) tuples if withscores.
Redis command documentation: CommandName.ZRANGEBYSCORE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the sortby=BYSCORE argumentHint
Supports client side caching
- 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) CommandRequest[int]¶
Store a range of members from a sorted set into another key.
- Parameters:
dst¶ – Destination key for the stored range.
src¶ – Source sorted set key.
min_¶ – Start of range (score or lex depending on sortby).
max_¶ – End of range (score or lex depending on sortby).
sortby¶ – BYSCORE or BYLEX.
rev¶ – If
True, reverse order.offset¶ – Skip this many members (use with count).
count¶ – Store at most this many members (use with offset).
- Returns:
Number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZRANGESTORE
Compatibility:
New in Redis version: 6.2.0
- zrank(key: KeyT, member: ValueT, withscore: bool | None = None) CommandRequest[int | tuple[int, float] | None]¶
Return the rank (index) of the member in the sorted set (lowest score has rank 0).
- Parameters:
- Returns:
The rank, or (rank, score) if withscore;
Noneif member is not in the set.
Redis command documentation: CommandName.ZRANK
Compatibility:
withscore: New in Redis version: 7.1.240
Hint
Supports client side caching
- zrem(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Remove one or more members from the sorted set.
- Parameters:
- Returns:
The number of members that were removed.
Redis command documentation: CommandName.ZREM
- zremrangebylex(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Remove all members in the sorted set between min and max (lexicographic order).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYLEX
- zremrangebyrank(key: KeyT, start: int, stop: int) CommandRequest[int]¶
Remove all members in the sorted set with rank between start and stop (inclusive).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYRANK
- zremrangebyscore(key: KeyT, min_: int | float, max_: int | float) CommandRequest[int]¶
Remove all members in the sorted set with scores between min and max (inclusive).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYSCORE
- zrevrange(key: KeyT, start: int, stop: int, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members by index, highest scores first.
- Parameters:
- Returns:
Members (and optionally scores) in the specified range.
Redis command documentation: CommandName.ZREVRANGE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev argumentHint
Supports client side caching
- zrevrangebylex(key: KeyT, max_: ValueT, min_: ValueT, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Return a range of members in a sorted set by lexicographical range, high to low.
- Parameters:
- Returns:
Tuple of members in the specified lex range.
Redis command documentation: CommandName.ZREVRANGEBYLEX
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev and sort=BYLEX argumentsHint
Supports client side caching
- zrevrangebyscore(key: KeyT, max_: int | float, min_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in a sorted set by score, high to low.
- Parameters:
- Returns:
Tuple of members, or (member, score) tuples if withscores.
Redis command documentation: CommandName.ZREVRANGEBYSCORE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev and sort=BYSCORE argumentsHint
Supports client side caching
- zrevrank(key: KeyT, member: ValueT, withscore: bool | None = None) CommandRequest[int | tuple[int, float] | None]¶
Return the rank of the member when the set is ordered high to low.
- Parameters:
- Returns:
The rank, or (rank, score) if withscore;
Noneif member is not in the set.
Redis command documentation: CommandName.ZREVRANK
Compatibility:
withscore: New in Redis version: 7.1.240
Hint
Supports client side caching
- zscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) CommandRequest[tuple[int, tuple[ScoredMember, ...]]]¶
Incrementally iterate over members and scores in the sorted set using a cursor.
- Parameters:
- Returns:
A tuple of (next_cursor, (member, score), …); next_cursor 0 means done.
Redis command documentation: CommandName.ZSCAN
- 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.
- zscore(key: KeyT, member: ValueT) CommandRequest[float | None]¶
Return the score associated with the member in the sorted set.
- Parameters:
- Returns:
The score, or
Noneif the member is not in the set.
Redis command documentation: CommandName.ZSCORE
Hint
Supports client side caching
- zunion(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the union of multiple sorted sets (aggregating scores by weights and aggregate rule).
- Parameters:
- Returns:
Members (and optionally scores) in the union.
Redis command documentation: CommandName.ZUNION
Compatibility:
New in Redis version: 6.2.0
- zunionstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None) CommandRequest[int]¶
Compute the union of sorted sets and store the result at destination.
- Parameters:
- Returns:
Number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZUNIONSTORE
- classmethod from_url(url: str, db: int | None = None, *, decode_responses: Literal[False] = False, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = ConstantRetryPolicy((ConnectionError, TimeoutError), retries=2, delay=0.01), cache: AbstractCache | None = None, pool_timeout: float | None = None, **kwargs: Any) Redis[bytes][source]¶
- classmethod from_url(url: str, db: int | None = None, *, decode_responses: Literal[True] = False, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, retry_policy: RetryPolicy = ConstantRetryPolicy((ConnectionError, TimeoutError), retries=2, delay=0.01), cache: AbstractCache | None = None, pool_timeout: float | None = None, **kwargs: Any) Redis[str]
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/0rediss://[:password]@localhost:6379/0unix://[:password]@/path/to/socket.sock?db=0
urlandkwargsare passed as is to thecoredis.pool.ConnectionPool.from_url().
- async execute_command(command: CommandRequest[R]) R[source]¶
Executes a command with configured retries and returns the parsed response
- decoding(mode: Literal[False], encoding: str | None = None) contextlib.AbstractContextManager[Redis[bytes]][source]¶
- decoding(mode: Literal[True], encoding: str | None = None) contextlib.AbstractContextManager[Redis[str]]
Context manager to temporarily change the decoding behavior of the client
- Parameters:
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.
- pubsub(*, channels: Parameters[StringT] | None = None, channel_handlers: Mapping[StringT, SubscriptionCallback] | None = None, patterns: Parameters[StringT] | None = None, pattern_handlers: Mapping[StringT, SubscriptionCallback] | None = None, ignore_subscribe_messages: bool = False, retry_policy: RetryPolicy | None = CompositeRetryPolicy(ExponentialBackoffRetryPolicy((ConnectionError,), retries=None, base_delay=0.1, max_delay=16, jitter=True), ConstantRetryPolicy((TimeoutError,), retries=2, delay=0.1)), subscription_timeout: float = 1, max_idle_seconds: float = 15) PubSub[AnyStr][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:
channels¶ – channels that the constructed Pubsub instance should automatically subscribe to
channel_handlers¶ – Mapping of channels to automatically subscribe to and the associated handlers that will be invoked when a message is received on the specific channel.
patterns¶ – patterns that the constructed Pubsub instance should automatically subscribe to
pattern_handlers¶ – Mapping of patterns to automatically subscribe to and the associated handlers that will be invoked when a message is received on channel matching the pattern.
ignore_subscribe_messages¶ – Whether to skip subscription acknowledgement messages
retry_policy¶ – An explicit retry policy to use in the subscriber.
subscription_timeout¶ – Maximum amount of time in seconds to wait for acknowledgement of subscriptions.
max_idle_seconds¶ – Maximum duration (in seconds) to tolerate no messages from the server before performing a keepalive check with a
PING.
- pipeline(transaction: bool = True, *, raise_on_error: bool = True, timeout: float | None = None) coredis.patterns.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.
raise_on_error¶ – Whether to raise errors upon executing the pipeline. If set to False errors will be accumulated and retrievable from the individual commands that had errors.
timeout¶ – If specified this value will take precedence over
Redis.stream_timeout
- lock(name: StringT, timeout: float | None = None, sleep: float = 0.1, blocking: bool = True, blocking_timeout: float | None = None) Lock[AnyStr][source]¶
Return a lock instance which can be used to guard resource access across multiple clients.
- Parameters:
name¶ – key for the lock
timeout¶ – indicates a maximum life for the lock. By default, it will remain locked until
release()is called.timeoutcan be specified as a float or integer, both representing the number of seconds to wait.sleep¶ – indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.
blocking¶ – indicates whether calling
acquire()should block until the lock has been acquired or to fail immediately, causingacquire()to returnFalseand the lock not being acquired. Defaults toTrue.blocking_timeout¶ – indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of
Noneindicates continue trying forever.blocking_timeoutcan be specified as afloatorint, both representing the number of seconds to wait.
- async transaction(func: Callable[[coredis.patterns.pipeline.Pipeline[AnyStr]], Awaitable[R]], *watches: KeyT, watch_delay: float | None = None) R[source]¶
Convenience method for executing the callable
funcas a transaction while watching all keys specified inwatches.- Parameters:
func¶ – callable should expect a single argument which is a
coredis.patterns.pipeline.Pipelineobject retrieved by callingpipeline().watches¶ – The keys to watch during the transaction
watch_delay¶ – Time in seconds to wait after each watch error before retrying
- xconsumer(streams: Parameters[KeyT], *, buffer_size: int = 0, timeout: int | None = None, group: Literal[None] = None, consumer: Literal[None] = None, auto_create: bool = True, auto_acknowledge: bool = False, start_from_backlog: bool = False, **stream_parameters: StreamParameters) Consumer[AnyStr][source]¶
- xconsumer(streams: Parameters[KeyT], *, buffer_size: int = 0, timeout: int | None = None, group: StringT = None, consumer: StringT = None, auto_create: bool = True, auto_acknowledge: bool = False, start_from_backlog: bool = False, **stream_parameters: StreamParameters) GroupConsumer[AnyStr]
Create a stream consumer for one or more Redis streams.
Depending on whether
groupandconsumerare provided, this method creates either a standalone stream consumer or a member of a stream consumer group.If
groupandconsumerare not provided, a standalone stream consumer is created that starts reading from the latest entry of each stream provided instreams.The latest entry is determined by calling
xinfo_stream()and using thelast-entryattribute at the point of initializing the consumer instance or on first fetch (whichever comes first). If the stream(s) do not exist at the time of consumer creation, the consumer will simply start from the minimum identifier (0-0).If
groupandconsumerare provided, a member of a stream consumer group is created. The consumer has an identical interface ascoredis.patterns.streams.Consumer.- Parameters:
streams¶ – the stream identifiers to consume from
buffer_size¶ – Size of buffer (per stream) to maintain. This translates to the maximum number of stream entries that are fetched on each request to redis.
timeout¶ – Maximum amount of time in milliseconds to block for new entries to appear on the streams the consumer is reading from.
group¶ – The name of the group this consumer is part of
auto_create¶ – If True the group will be created upon initialization or first fetch if it doesn’t already exist.
auto_acknowledge¶ – If
Truethe stream entries fetched will be fetched without needing to be acknowledged withxack()to remove them from the pending entries list.start_from_backlog¶ – If
Truethe consumer will start by fetching any pending entries from the pending entry list before considering any new messages not seen by any other consumer in thegroupstream_parameters¶ –
Mapping of optional parameters to use by stream for the streams provided in
streams.Warning
Providing an
identifierinstream_parametershas a different meaning for a group consumer. If the value is any valid identifier other than>the consumer will only access the history of pending messages. That is, the set of messages that were delivered to this consumer (identified byconsumer) and never acknowledged.
Added in version 6.0.0.
- class RedisCluster(host: str | None = ..., port: int | None = ..., *, startup_nodes: Iterable[Node] | None = ..., username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int = ..., max_connections_per_node: bool = ..., readonly: bool = ..., read_from_replicas: bool = ..., reinitialize_steps: int | None = ..., skip_full_coverage_check: bool = ..., nodemanager_follow_cluster: bool = ..., encoding: str = ..., decode_responses: Literal[False] = ..., connection_pool: ClusterConnectionPool | None = ..., connection_pool_cls: type[ClusterConnectionPool] = ..., verify_version: bool = ..., non_atomic_cross_slot: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)[source]¶
- class RedisCluster(host: str | None = ..., port: int | None = ..., *, startup_nodes: Iterable[Node | TCPLocation] | None = ..., username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int = ..., max_connections_per_node: bool = ..., readonly: bool = ..., read_from_replicas: bool = ..., reinitialize_steps: int | None = ..., skip_full_coverage_check: bool = ..., nodemanager_follow_cluster: bool = ..., encoding: str = ..., decode_responses: Literal[True] = ..., connection_pool: ClusterConnectionPool | None = ..., connection_pool_cls: type[ClusterConnectionPool] = ..., verify_version: bool = ..., non_atomic_cross_slot: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)
- class RedisCluster(host: str | None = ..., port: int | None = ..., *, startup_nodes: Iterable[Node | TCPLocation] | None = ..., username: str | None = ..., password: str | None = ..., credential_provider: AbstractCredentialProvider | None = ..., stream_timeout: float | None = ..., connect_timeout: float | None = ..., pool_timeout: float | None = ..., ssl: bool = ..., ssl_context: SSLContext | None = ..., ssl_keyfile: str | None = ..., ssl_certfile: str | None = ..., ssl_cert_reqs: Literal['optional', 'required', 'none'] | None = ..., ssl_check_hostname: bool | None = ..., ssl_ca_certs: str | None = ..., max_connections: int = ..., max_connections_per_node: bool = ..., readonly: bool = ..., read_from_replicas: bool = ..., reinitialize_steps: int | None = ..., skip_full_coverage_check: bool = ..., nodemanager_follow_cluster: bool = ..., encoding: str = ..., decode_responses: bool = ..., connection_pool: ClusterConnectionPool | None = ..., connection_pool_cls: type[ClusterConnectionPool] = ..., verify_version: bool = ..., non_atomic_cross_slot: bool = ..., cache: AbstractCache | None = ..., noreply: bool = ..., noevict: bool = ..., notouch: bool = ..., retry_policy: RetryPolicy = ..., type_adapter: TypeAdapter | None = ...)
- Changes
Removed in version 6.0.0.
protocol_versionremoved (and therefore support for RESP2)
Changed in version 6.0.0.
The cluster client is now an async context manager and must always be used as such.
Added in version 4.12.0.
RedisCluster.ensure_persistence()context managerRedis Module support
RedisJSON:
RedisCluster.jsonRedisBloom:
BloomFilter:
RedisCluster.bfCuckooFilter:
RedisCluster.cfCountMinSketch:
RedisCluster.cmsTopK:
RedisCluster.topkTDigest:
RedisCluster.tdigest
RedisTimeSeries:
RedisCluster.timeseriesRedisGraph:
RedisCluster.graphRediSearch:
Search & Aggregation:
RedisCluster.searchAutocomplete: Added
RedisCluster.autocomplete
Changed in version 4.4.0.
nodemanager_follow_clusternow defaults toTrue
Deprecated since version 4.4.0.
The
readonlyargument is deprecated in favour ofread_from_replicas
Added in version 4.3.0.
Added
connection_pool_cls
Changed in version 4.0.0.
non_atomic_cross_slotdefaults toTrueprotocol_version`defaults to3
Added in version 3.11.0.
Added
noreply
Added in version 3.10.0.
Synchronized ssl constructor parameters with
coredis.Redis
Added in version 3.9.0.
If
cacheis provided the client will check & populate the cache for read only commands and invalidate it for commands that could change the key(s) in the request.
Added in version 3.6.0.
The
non_atomic_cross_slotparameter was added
Changed in version 3.5.0.
The
verify_versionparameter now defaults toTrue
Added in version 3.1.0.
The
protocol_versionandverify_versionparameters were added
- 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
pool_timeout¶ – Timeout (seconds) for acquiring a connection from the connection pool
ssl¶ – Whether to use an SSL connection
ssl_context¶ – If provided the
ssl.SSLContextwill 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 otherssl_*parameters will be used.ssl_keyfile¶ – Path of the private key to use
ssl_certfile¶ – Path to the certificate corresponding to
ssl_keyfilessl_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_reqsis not"none"(Seessl.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
Truethe client will route readonly commands to replicasreinitialize_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.
encoding¶ – The codec to use to encode strings transmitted to redis and decode responses with. (See Encoding/Decoding)
decode_responses¶ – If
Truestring responses from the server will be decoded usingencodingbefore 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.
verify_version¶ – Validate redis server version against the documented version introduced before executing a command and raises a
CommandNotSupportedErrorerror if the required version is higher than the reported server versionnon_atomic_cross_slot¶ – If
Truecertain 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
Truethe 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
type_adapter¶ – The adapter to use for serializing / deserializing customs types when interacting with redis commands.
- classmethod from_url(url: str, *, skip_full_coverage_check: bool = False, decode_responses: Literal[False] = False, verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, non_atomic_cross_slot: bool = True, cache: AbstractCache | None = None, retry_policy: RetryPolicy = CompositeRetryPolicy(ConstantRetryPolicy((ClusterDownError,), retries=2, delay=0.1), ConstantRetryPolicy((ConnectionError, TimeoutError), retries=2, delay=0.1)), type_adapter: TypeAdapter | None = None, pool_timeout: float | None = None, **kwargs: Any) RedisCluster[bytes][source]¶
- classmethod from_url(url: str, *, skip_full_coverage_check: bool = False, decode_responses: Literal[True], verify_version: bool = True, noreply: bool = False, noevict: bool = False, notouch: bool = False, non_atomic_cross_slot: bool = True, cache: AbstractCache | None = None, retry_policy: RetryPolicy = CompositeRetryPolicy(ConstantRetryPolicy((ClusterDownError,), retries=2, delay=0.1), ConstantRetryPolicy((ConnectionError, TimeoutError), retries=2, delay=0.1)), type_adapter: TypeAdapter | None = None, pool_timeout: float | None = None, **kwargs: Any) RedisCluster[str]
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/redisFor example:
redis://[:password]@localhost:6379rediss://[:password]@localhost:6379
urlandkwargsare passed as is to thecoredis.pool.ClusterConnectionPool.from_url().
- property num_replicas_per_shard: int¶
Number of replicas per shard of the cluster determined by initial cluster topology discovery
- async execute_command(command: CommandRequest[R]) R[source]¶
Sends a command to one or many nodes in the cluster with retries based on
RedisCluster.retry_policy
- acl_cat(categoryname: StringT | None = None) CommandRequest[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: CommandName.ACL_CAT
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_deluser(usernames: Parameters[StringT]) CommandRequest[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: CommandName.ACL_DELUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- acl_dryrun(username: StringT, command: StringT, *args: ValueT) CommandRequest[bool]¶
Returns whether the user can execute the given command without executing the command.
Redis command documentation: CommandName.ACL_DRYRUN
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_genpass(bits: int | None = None) CommandRequest¶
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: CommandName.ACL_GENPASS
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_getuser(username: StringT) CommandRequest[dict[AnyStr, list[AnyStr] | set[AnyStr]]]¶
Get the rules for a specific ACL user
Redis command documentation: CommandName.ACL_GETUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_list() CommandRequest[tuple[AnyStr, ...]]¶
List the current ACL rules in ACL config file format
Redis command documentation: CommandName.ACL_LIST
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_load() CommandRequest[bool]¶
Reload the ACLs from the configured ACL file
- Returns:
Trueif 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: CommandName.ACL_LOAD
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- acl_log(count: int | None = None, reset: bool | None = None) CommandRequest[bool] | CommandRequest[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
RESETTrueif the security log was cleared.
Redis command documentation: CommandName.ACL_LOG
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- acl_save() CommandRequest[bool]¶
Save the current ACL rules in the configured ACL file
- Returns:
Trueif 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: CommandName.ACL_SAVE
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- acl_setuser(username: StringT, *rules: StringT) CommandRequest[bool]¶
Modify or create the rules for a specific ACL user
- Returns:
Trueif successful. If the rules contain errors, the error is returned.
Redis command documentation: CommandName.ACL_SETUSER
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- acl_users() CommandRequest[tuple[AnyStr, ...]]¶
List the username of all the configured ACL rules
Redis command documentation: CommandName.ACL_USERS
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- acl_whoami() CommandRequest¶
Return the name of the user associated to the current connection
- Returns:
the username of the current connection.
Redis command documentation: CommandName.ACL_WHOAMI
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- append(key: KeyT, value: ValueT) CommandRequest[int]¶
Append a value to a key.
- Parameters:
- Returns:
The length of the string after the append operation.
Redis command documentation: CommandName.APPEND
- asking() CommandRequest[bool]¶
Send ASK to the server (used by cluster clients after an -ASK redirect).
- Returns:
Trueon success.
Redis command documentation: CommandName.ASKING
Added in version 3.0.0.
- auth(password: StringT, username: StringT | None = None) CommandRequest[bool]¶
Authenticate the connection to the server.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.AUTH
Compatibility:
username: New in Redis version: 6.0.0
Warning
Using
authdirectly is not recommended. Use theRedis.usernameandRedis.passwordarguments 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.
- property autocomplete: Autocomplete¶
Property to access
Autocompletecommands.Added in version 4.12.0.
- property bf: BloomFilter¶
Property to access
BloomFiltercommands.Added in version 4.12.0.
- bgrewriteaof() CommandRequest[bool]¶
Ask the server to rewrite the AOF file from data in memory.
- Returns:
Truewhen the rewrite has been scheduled.
Redis command documentation: CommandName.BGREWRITEAOF
- bgsave(schedule: bool | None = None) CommandRequest[bool]¶
Start a background save of the dataset to disk (non-blocking).
- Parameters:
schedule¶ – If
True, schedule a save if none in progress.- Returns:
Truewhen save has started or been scheduled.
Redis command documentation: CommandName.BGSAVE
- bitcount(key: KeyT, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) CommandRequest[int]¶
Return the number of set bits in the string value at key.
- Parameters:
- Returns:
Count of bits set to 1 in the (optionally ranged) value.
Redis command documentation: CommandName.BITCOUNT
Compatibility:
index_unit: New in Redis version: 7.0.0
- bitfield(key: KeyT) BitFieldOperation¶
Return a BitFieldOperation to build one or more bitfield ops on the key.
- Parameters:
key¶ – The key name.
- Returns:
BitFieldOperationfor chained get/set/incr.
- bitfield_ro(key: KeyT) BitFieldOperation¶
Return a read-only BitFieldOperation for bitfield GET on the key (e.g. on replica).
- Parameters:
key¶ – The key name.
- Returns:
BitFieldOperation(read-only; write raises ReadOnlyError).
- bitop(keys: Parameters[KeyT], operation: StringT, destkey: KeyT) CommandRequest[int]¶
Perform a bitwise operation (AND, OR, XOR, NOT) on keys and store result at destkey.
- Parameters:
- Returns:
Size in bytes of the result string.
Redis command documentation: CommandName.BITOP
- bitpos(key: KeyT, bit: int, start: int | None = None, end: int | None = None, index_unit: Literal[PureToken.BIT, PureToken.BYTE] | None = None) CommandRequest[int]¶
Return the position of the first bit set to 1 or 0 in the string value.
- Parameters:
- Returns:
Bit position of first matching bit; -1 if no match (e.g. empty key for bit=1). For bit=0 with no range or start-only, string is considered right-padded with zeros.
Redis command documentation: CommandName.BITPOS
Compatibility:
index_unit: New in Redis version: 7.0.0
- blmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT], timeout: int | float) CommandRequest[AnyStr | None]¶
Pop an element from a list, push it to another list, and return it; block until one is available.
- Parameters:
- Returns:
The element that was moved, or
Noneif timeout was reached.
Redis command documentation: CommandName.BLMOVE
Compatibility:
New in Redis version: 6.2.0
- blmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) CommandRequest[list[AnyStr | list[AnyStr]] | None]¶
Pop elements from the first non-empty list among the given keys, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, [elements]].
Redis command documentation: CommandName.BLMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- blpop(keys: Parameters[KeyT], timeout: int | float) CommandRequest[list[AnyStr] | None]¶
Remove and return the first element from the first non-empty list, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, element].
Redis command documentation: CommandName.BLPOP
- brpop(keys: Parameters[KeyT], timeout: int | float) CommandRequest[list[AnyStr] | None]¶
Remove and return the last element from the first non-empty list, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise [key_name, element].
Redis command documentation: CommandName.BRPOP
- brpoplpush(source: KeyT, destination: KeyT, timeout: int | float) CommandRequest[AnyStr | None]¶
Pop from the tail of source, push to the head of destination, and return the element; block until one is available.
- Parameters:
- Returns:
The element that was moved, or
Noneif timeout was reached.
Redis command documentation: CommandName.BRPOPLPUSH
Caution
Deprecated in Redis version: 6.2.0 Use
blmove()with the wherefrom and whereto arguments
- bzmpop(keys: Parameters[KeyT], timeout: int | float, where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) CommandRequest[tuple[AnyStr, tuple[ScoredMember, ...]] | None]¶
Pop members with lowest or highest scores from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, [(member, score), …]).
Redis command documentation: CommandName.BZMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- bzpopmax(keys: Parameters[KeyT], timeout: int | float) CommandRequest[tuple[AnyStr, AnyStr, float] | None]¶
Pop the member with the highest score from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, member, score).
Redis command documentation: CommandName.BZPOPMAX
- bzpopmin(keys: Parameters[KeyT], timeout: int | float) CommandRequest[tuple[AnyStr, AnyStr, float] | None]¶
Pop the member with the lowest score from the first non-empty sorted set, or block until one is available.
- Parameters:
- Returns:
Noneif timeout reached; otherwise (key_name, member, score).
Redis command documentation: CommandName.BZPOPMIN
- property cf: CuckooFilter¶
Property to access
CuckooFiltercommands.Added in version 4.12.0.
- client_caching(mode: Literal[PureToken.NO, PureToken.YES]) CommandRequest[bool]¶
Instruct the server about tracking or not keys in the next request
Redis command documentation: CommandName.CLIENT_CACHING
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_getname() CommandRequest[AnyStr | None]¶
Returns the current connection name
- Returns:
The connection name, or
Noneif no name is set.
Redis command documentation: CommandName.CLIENT_GETNAME
- client_getredir() CommandRequest[int]¶
Get tracking notifications redirection client ID if any
- Returns:
the ID of the client we are redirecting the notifications to. The command returns
-1if client tracking is not enabled, or0if client tracking is enabled but we are not redirecting the notifications to any client.
Redis command documentation: CommandName.CLIENT_GETREDIR
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_id() CommandRequest[int]¶
Returns the client ID for the current connection
- Returns:
The id of the client.
Redis command documentation: CommandName.CLIENT_ID
Added in version 3.0.0.
- client_info() CommandRequest[ClientInfo]¶
Returns information about the current client connection.
Redis command documentation: CommandName.CLIENT_INFO
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- client_kill(ip_port: StringT | None = None, identifier: int | None = None, type_: None | Literal[PureToken.NORMAL, PureToken.MASTER, PureToken.SLAVE, PureToken.REPLICA, PureToken.PUBSUB] = None, user: StringT | None = None, addr: StringT | None = None, laddr: StringT | None = None, skipme: bool | None = None, maxage: int | None = None) CommandRequest[int | bool]¶
Disconnect one or more clients by filter (ip:port, addr, type, user, etc.).
- Parameters:
ip_port¶ – Client address as
ip:port(legacy form).identifier¶ – Client ID (from client list).
type_¶ – NORMAL, MASTER, SLAVE, REPLICA, or PUBSUB.
user¶ – Disconnect clients of the given user.
addr¶ – Disconnect client at the given address.
laddr¶ – Match local address.
skipme¶ – If
True, do not disconnect this connection.maxage¶ – Disconnect idle clients older than this many seconds.
- Returns:
Trueif a single client was closed, or number of clients killed.
Redis command documentation: CommandName.CLIENT_KILL
Compatibility:
laddr: New in Redis version: 6.2.0maxage: New in Redis version: 7.4.0
- client_list(type_: None | Literal[PureToken.MASTER, PureToken.NORMAL, PureToken.PUBSUB, PureToken.REPLICA] = None, identifiers: Parameters[int] | None = None) CommandRequest[tuple[ClientInfo, ...]]¶
Get client connections
- Returns:
a tuple of dictionaries containing client fields
Redis command documentation: CommandName.CLIENT_LIST
Compatibility:
identifiers: New in Redis version: 6.2.0
- client_no_evict(enabled: Literal[PureToken.ON, PureToken.OFF]) CommandRequest[bool]¶
Set client eviction mode for the current connection
Redis command documentation: CommandName.CLIENT_NO_EVICT
Compatibility:
New in Redis version: 7.0.0
Warning
Using
client_no_evictdirectly is not recommended. UseRedis.noevictargument when initializing the client to ensure that all connections originating from this client use the desired modeAdded in version 3.2.0.
- client_no_touch(enabled: Literal[PureToken.OFF, PureToken.ON]) CommandRequest[bool]¶
Controls whether commands sent by the client will alter the LRU/LFU of the keys they access.
Redis command documentation: CommandName.CLIENT_NO_TOUCH
Compatibility:
New in Redis version: 7.1.240
Warning
Using
client_no_touchdirectly is not recommended. UseRedis.notouchargument when initializing the client to ensure that all connections originating from this client use the desired modeAdded in version 4.12.0.
- client_pause(timeout: int, mode: Literal[PureToken.WRITE, PureToken.ALL] | None = None) CommandRequest[bool]¶
Stop processing commands from clients for some time
- Returns:
The command returns
Trueor raises an error if the timeout is invalid.
Redis command documentation: CommandName.CLIENT_PAUSE
Compatibility:
mode: New in Redis version: 6.2.0
- client_reply(mode: Literal[PureToken.OFF, PureToken.ON, PureToken.SKIP]) CommandRequest[bool]¶
Instruct the server whether to reply to commands
Redis command documentation: CommandName.CLIENT_REPLY
Danger
Using
client_replydirectly is not supported. Use theRedis.noreplyargument when initializing the client to ensure that all connections originating from this client disable or enable replies. You can also use theRedis.ignore_replies()context manager to selectively execute certain commands without waiting for a replyAdded in version 3.0.0.
- client_setinfo(lib_name: StringT | None = None, lib_ver: StringT | None = None) CommandRequest[bool]¶
Set client or connection specific info
Redis command documentation: CommandName.CLIENT_SETINFO
Compatibility:
New in Redis version: 7.1.240
Warning
Using
client_setinfodirectly 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 commandsAdded in version 4.12.0.
- client_setname(connection_name: StringT) CommandRequest[bool]¶
Set the current connection name :return: If the connection name was successfully set.
Redis command documentation: CommandName.CLIENT_SETNAME
Warning
Using
client_setnamedirectly is not recommended. Use theRedis.client_nameargument when initializing the client to ensure the client name is consistent across all connections originating from the client
- 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) CommandRequest[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: CommandName.CLIENT_TRACKING
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- client_trackinginfo() CommandRequest[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: CommandName.CLIENT_TRACKINGINFO
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- client_unblock(client_id: int, unblock_type: Literal[PureToken.TIMEOUT, PureToken.ERROR] | None = None) CommandRequest[bool]¶
Unblock a client blocked in a blocking command from a different connection
- Parameters:
- Returns:
Whether the client was unblocked
Redis command documentation: CommandName.CLIENT_UNBLOCK
Added in version 3.0.0.
- client_unpause() CommandRequest[bool]¶
Resume processing of clients that were paused
- Returns:
The command returns
`True`
Redis command documentation: CommandName.CLIENT_UNPAUSE
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- cluster_addslots(slots: Parameters[int]) CommandRequest[bool]¶
Assign new hash slots to the receiving node.
- Parameters:
slots¶ – One or more slot numbers to assign.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_ADDSLOTS
- cluster_addslotsrange(slots: Parameters[tuple[int, int]]) CommandRequest[bool]¶
Assign ranges of hash slots to the receiving node.
- Parameters:
slots¶ – One or more (start, end) slot ranges (inclusive).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_ADDSLOTSRANGE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
- cluster_bumpepoch() CommandRequest¶
Advance the cluster configuration epoch.
- Returns:
BUMPEDif the epoch was incremented,STILLif this node already had the greatest epoch.
Redis command documentation: CommandName.CLUSTER_BUMPEPOCH
Added in version 3.0.0.
- cluster_count_failure_reports(node_id: StringT) CommandRequest[int]¶
Return the number of failure reports active for a given node.
- Parameters:
node_id¶ – The cluster node ID.
- Returns:
The number of failure reports.
Redis command documentation: CommandName.CLUSTER_COUNT_FAILURE_REPORTS
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_countkeysinslot(slot: int) CommandRequest[int]¶
Return the number of local keys in the specified hash slot.
- Parameters:
slot¶ – The hash slot number.
- Returns:
The number of keys in the slot on this node.
Redis command documentation: CommandName.CLUSTER_COUNTKEYSINSLOT
Cluster note
The command will be routed to node(s) based on the slot id(s) in the command arguments and return the response from the node.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- cluster_delslots(slots: Parameters[int]) CommandRequest[bool]¶
Mark the given hash slots as unbound in the cluster.
The command is routed to the node that owns each slot.
- Parameters:
slots¶ – One or more slot numbers to unbound.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_DELSLOTS
Cluster note
The command will be routed to node(s) based on the slot id(s) in the command arguments and return
Trueif all responses areTrue.To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- cluster_delslotsrange(slots: Parameters[tuple[int, int]]) CommandRequest[bool]¶
Mark the given slot ranges as unbound on the receiving node.
- Parameters:
slots¶ – One or more (start, end) slot ranges (inclusive).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_DELSLOTSRANGE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
Cluster note
The command will be routed to node(s) based on the slot id(s) in the command arguments and return
Trueif all responses areTrue.To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- cluster_failover(options: Literal[PureToken.FORCE, PureToken.TAKEOVER] | None = None) CommandRequest[bool]¶
Force a replica to perform a manual failover of its master.
- Parameters:
options¶ – Optional FORCE or TAKEOVER to alter failover behavior.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FAILOVER
- cluster_flushslots() CommandRequest[bool]¶
Delete this node’s assigned slot information (must have no keys in those slots).
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FLUSHSLOTS
Added in version 3.0.0.
- cluster_forget(node_id: StringT) CommandRequest[bool]¶
Remove a node from the set of known nodes of the cluster node receiving the command.
- Parameters:
node_id¶ – The cluster node ID to forget.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_FORGET
- cluster_getkeysinslot(slot: int, count: int) CommandRequest[tuple[AnyStr, ...]]¶
Return up to a given number of local key names in the specified hash slot.
- Parameters:
- Returns:
A tuple of key names (up to count).
Redis command documentation: CommandName.CLUSTER_GETKEYSINSLOT
Added in version 3.0.0.
Cluster note
The command will be routed to node(s) based on the slot id(s) in the command arguments and return the response from the node.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- cluster_info() CommandRequest[dict[str, str]]¶
Return information about the Redis Cluster node state.
- Returns:
A mapping of cluster state keys and values.
Redis command documentation: CommandName.CLUSTER_INFO
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_keyslot(key: KeyT) CommandRequest[int]¶
Return the hash slot number for the specified key.
- Parameters:
key¶ – The key name.
- Returns:
The slot number
Redis command documentation: CommandName.CLUSTER_KEYSLOT
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_links() CommandRequest[list[dict[AnyStr, ResponsePrimitive]]]¶
Return a list of all TCP links to and from peer nodes in the cluster.
- Returns:
A list of mappings; each mapping contains attributes and values for one cluster link.
Redis command documentation: CommandName.CLUSTER_LINKS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.1.
- cluster_meet(ip: StringT, port: int, cluster_bus_port: int | None = None) CommandRequest[bool]¶
Force this cluster node to handshake with another node.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_MEET
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_myid() CommandRequest¶
Return this node’s cluster ID.
- Returns:
The node ID string.
Redis command documentation: CommandName.CLUSTER_MYID
Added in version 3.1.1.
- cluster_nodes() CommandRequest[list[ClusterNodeDetail]]¶
Return the current cluster configuration from the perspective of this node.
- Returns:
A list of cluster node details.
Redis command documentation: CommandName.CLUSTER_NODES
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_replicas(node_id: StringT) CommandRequest[list[ClusterNodeDetail]]¶
List replica nodes of the specified master node.
- Parameters:
node_id¶ – The master node ID.
- Returns:
A list of replica node details.
Redis command documentation: CommandName.CLUSTER_REPLICAS
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_replicate(node_id: StringT) CommandRequest[bool]¶
Reconfigure this node as a replica of the specified master node.
- Parameters:
node_id¶ – The master node ID to replicate.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_REPLICATE
- cluster_reset(reset_type: Literal[PureToken.HARD, PureToken.SOFT] | None = None) CommandRequest[bool]¶
Reset a Redis Cluster node (clears slots and peer state).
- Parameters:
reset_type¶ – HARD (full reset) or SOFT (only clear keys); default is HARD.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_RESET
- cluster_saveconfig() CommandRequest[bool]¶
Force the node to save the cluster state to disk.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SAVECONFIG
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- cluster_set_config_epoch(config_epoch: int) CommandRequest[bool]¶
Set the configuration epoch for a new node (used during cluster creation).
- Parameters:
config_epoch¶ – The configuration epoch value.
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SET_CONFIG_EPOCH
- cluster_setslot(slot: int, *, importing: StringT | None = None, migrating: StringT | None = None, node: StringT | None = None, stable: bool | None = None) CommandRequest[bool]¶
Bind a hash slot to a specific node or set slot migration state.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.CLUSTER_SETSLOT
- cluster_shards() CommandRequest[list[dict[AnyStr, list[RedisValueT] | Mapping[AnyStr, RedisValueT]]]]¶
Return a mapping of cluster slots to nodes.
- Returns:
A list of shard mappings with slot ranges and node info.
Redis command documentation: CommandName.CLUSTER_SHARDS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.2.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_slaves(node_id: StringT) CommandRequest[list[ClusterNodeDetail]]¶
List replica nodes of the specified master node.
- Parameters:
node_id¶ – The master node ID.
- Returns:
A list of replica node details.
Redis command documentation: CommandName.CLUSTER_SLAVES
Caution
Deprecated in Redis version: 5.0.0 Use
cluster_replicas()Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- cluster_slots() CommandRequest[dict[tuple[int, int], tuple[ClusterNode, ...]]]¶
Return a mapping of cluster slot ranges to nodes.
- Returns:
A mapping of (start, end) slot ranges to node tuples.
Redis command documentation: CommandName.CLUSTER_SLOTS
Caution
Deprecated in Redis version: 7.0.0 Use
cluster_shards()Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- property cms: CountMinSketch¶
Property to access
CountMinSketchcommands.Added in version 4.12.0.
- command() CommandRequest[dict[str, Command]]¶
Get Redis command details
- Returns:
Mapping of command details. Commands are returned in random order.
Redis command documentation: CommandName.COMMAND
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_count() CommandRequest[int]¶
Get total number of Redis commands
- Returns:
number of commands returned by
COMMAND
Redis command documentation: CommandName.COMMAND_COUNT
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_docs(*command_names: StringT) CommandRequest[dict[AnyStr, dict[AnyStr, ResponseType]]]¶
Mapping of commands to a dictionary containing it’s documentation
Redis command documentation: CommandName.COMMAND_DOCS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_getkeys(command: StringT, arguments: Parameters[ValueT]) CommandRequest[tuple[AnyStr, ...]]¶
Extract keys given a full Redis command
- Returns:
Keys from your command.
Redis command documentation: CommandName.COMMAND_GETKEYS
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_getkeysandflags(command: StringT, arguments: Parameters[ValueT]) CommandRequest[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: CommandName.COMMAND_GETKEYSANDFLAGS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_info(*command_names: StringT) CommandRequest[dict[str, Command]]¶
Get specific Redis command details, or all when no argument is given.
- Returns:
mapping of command details.
Redis command documentation: CommandName.COMMAND_INFO
Added in version 3.0.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- command_list(module: StringT | None = None, aclcat: StringT | None = None, pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Get an array of Redis command names
Redis command documentation: CommandName.COMMAND_LIST
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- config_get(parameters: Parameters[StringT]) CommandRequest[dict[AnyStr, AnyStr]]¶
Get the values of configuration parameters
Redis command documentation: CommandName.CONFIG_GET
- config_resetstat() CommandRequest[bool]¶
Reset runtime statistics (keyspace hits/misses, commands processed, etc.).
- Returns:
Trueon success.
Redis command documentation: CommandName.CONFIG_RESETSTAT
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- config_rewrite() CommandRequest[bool]¶
Rewrites config file with the minimal change to reflect running config
Redis command documentation: CommandName.CONFIG_REWRITE
- config_set(parameter_values: Mapping[MappingKeyT, ValueT]) CommandRequest[bool]¶
Set one or more server configuration parameters at runtime.
- Parameters:
parameter_values¶ – Mapping of parameter names to values.
- Returns:
Trueon success.
Redis command documentation: CommandName.CONFIG_SET
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- copy(source: KeyT, destination: KeyT, db: int | None = None, replace: bool | None = None) CommandRequest[bool]¶
Copy a key to another key, optionally in another database.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.COPY
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- create_request(name: bytes, *arguments: ValueT | Key, callback: Callable[[...], T_co], execution_parameters: ExecutionParameters | None = None) CommandRequest[T_co]¶
Factory method to create a command request awaitable. Subclasses of
coredis.client.Clientcan override this method if custom behavior is required. SeeCommandRequestfor details.
- dbsize() CommandRequest[int]¶
Return the number of keys in the currently selected database.
- Returns:
The number of keys.
Redis command documentation: CommandName.DBSIZE
- debug_object(key: KeyT) CommandRequest[dict[str, str | int]]¶
Return version-specific debugging information about a key (internal encoding, refcount, etc.).
- Parameters:
key¶ – The key name.
- Returns:
A mapping of debug attributes.
Redis command documentation: CommandName.DEBUG_OBJECT
- decoding(mode: Literal[False], encoding: str | None = None) contextlib.AbstractContextManager[RedisCluster[bytes]][source]¶
- decoding(mode: Literal[True], encoding: str | None = None) contextlib.AbstractContextManager[RedisCluster[str]]
Context manager to temporarily change the decoding behavior of the client
- Parameters:
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.
- decr(key: KeyT) CommandRequest[int]¶
Decrement the integer value of a key by one.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key after the decrement.
Redis command documentation: CommandName.DECR
- decrby(key: KeyT, decrement: int) CommandRequest[int]¶
Decrement the integer value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the decrement.
Redis command documentation: CommandName.DECRBY
- delete(keys: Parameters[KeyT]) CommandRequest[int]¶
Delete one or more keys.
- Parameters:
keys¶ – One or more key names to delete.
- Returns:
The number of keys that were removed.
Redis command documentation: CommandName.DEL
Cluster note
The command will be routed to the nodes serving the keys in the command and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- delex(key: KeyT, *, ifeq: ValueT | None = None, ifne: ValueT | None = None, ifdeq: ValueT | None = None, ifdne: ValueT | None = None) CommandRequest[bool]¶
Remove a key only if its value or hash digest matches the given condition.
- Parameters:
- Returns:
Trueif the key was removed.
Redis command documentation: CommandName.DELEX
Compatibility:
New in Redis version: 8.4.0
- digest(key: KeyT) CommandRequest[AnyStr | None]¶
Return the hash digest of the value stored at key as a hexadecimal string.
- Parameters:
key¶ – The key name.
- Returns:
The hex digest string, or
Noneif the key does not exist.
Redis command documentation: CommandName.DIGEST
Compatibility:
New in Redis version: 8.4.0
- dump(key: KeyT) CommandRequest[bytes]¶
Return a serialized version of the value stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The serialized value as bytes (use with restore).
Redis command documentation: CommandName.DUMP
- echo(message: StringT) CommandRequest¶
Echo the given string back from the server.
- Parameters:
message¶ – The string to echo.
- Returns:
The same string.
Redis command documentation: CommandName.ECHO
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- 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
localhost and/orreplicaswithintimeout_msmilliseconds.Internally this uses WAITAOF after each command executed within the context
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
replicaswithintimeout_msmilliseconds.Internally this uses WAIT after each command executed within the context
Example:
client = coredis.RedisCluster("localhost", 7000) with client.ensure_replication(1, 20): await client.set("fubar", 1)
- eval(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script with the given keys and arguments.
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVAL
- eval_ro(script: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script in read-only mode (no writes).
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVAL_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- evalsha(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a Lua script from the server cache by its SHA1 digest.
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVALSHA
- evalsha_ro(sha1: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Execute a cached Lua script in read-only mode (no writes).
- Parameters:
- Returns:
Script result as returned by Redis.
Redis command documentation: CommandName.EVALSHA_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- exists(keys: Parameters[KeyT]) CommandRequest[int]¶
Return how many of the given keys exist.
- Parameters:
keys¶ – One or more key names to check.
- Returns:
The number of keys that exist.
Redis command documentation: CommandName.EXISTS
Cluster note
The command will be routed to the nodes serving the keys in the command and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- expire(key: KeyT, seconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set a key’s time to live in seconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise (e.g. key does not exist).
Redis command documentation: CommandName.EXPIRE
Compatibility:
condition: New in Redis version: 7.0.0
- expireat(key: KeyT, unix_time_seconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set the expiration for a key to an absolute Unix timestamp in seconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.EXPIREAT
Compatibility:
condition: New in Redis version: 7.0.0
- expiretime(key: KeyT) CommandRequest[datetime]¶
Return the expiration Unix timestamp for a key in seconds.
- Parameters:
key¶ – The key name.
- Returns:
Expiration as datetime. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.EXPIRETIME
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- failover(host: StringT | None = None, port: int | None = None, force: bool | None = None, abort: bool | None = None, timeout: int | timedelta | None = None) CommandRequest[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: CommandName.FAILOVER
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- fcall(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Invoke a Redis function by name.
- Parameters:
- Returns:
The return value of the function (type depends on the function).
Redis command documentation: CommandName.FCALL
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- fcall_ro(function: StringT, keys: Parameters[KeyT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[ResponseType]¶
Invoke a Redis function in read-only mode (same as fcall but only for read-only functions).
- Parameters:
- Returns:
The return value of the function.
Redis command documentation: CommandName.FCALL_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
- flushall(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Deletes all keys in all databases on the current host
- Parameters:
flush_type¶ – Whether to perform an asynchronous or synchronous flush
Redis command documentation: CommandName.FLUSHALL
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- flushdb(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Deletes all keys in the current database
- Parameters:
flush_type¶ – Whether to perform an asynchronous or synchronous flush
Redis command documentation: CommandName.FLUSHDB
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- function_delete(library_name: StringT) CommandRequest[bool]¶
Delete a library and all its functions from the server.
- Parameters:
library_name¶ – The name of the library to delete.
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_DELETE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- function_dump() CommandRequest[bytes]¶
Return a serialized binary payload of all loaded functions.
- Returns:
The serialized payload (use with function_restore).
Redis command documentation: CommandName.FUNCTION_DUMP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- function_flush(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Delete all functions from the server.
- Parameters:
flush_type¶ – ASYNC to flush asynchronously, SYNC to block until done.
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_FLUSH
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- function_kill() CommandRequest[bool]¶
Kill the function currently in execution.
Redis command documentation: CommandName.FUNCTION_KILL
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to all primaries in the cluster and return the first response that is not an error.
- function_list(libraryname: StringT | None = None, withcode: bool | None = None) CommandRequest[Mapping[AnyStr, LibraryDefinition]]¶
List libraries and functions (optionally filtered by library name).
- Parameters:
- Returns:
Mapping of library name to library definition (functions, code, etc.).
Redis command documentation: CommandName.FUNCTION_LIST
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- function_load(function_code: StringT, replace: bool | None = None) CommandRequest¶
Load a library of Redis functions (Lua or other engine).
- Parameters:
- Returns:
Library name on success.
Redis command documentation: CommandName.FUNCTION_LOAD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- function_restore(serialized_value: bytes, policy: Literal[PureToken.FLUSH, PureToken.APPEND, PureToken.REPLACE] | None = None) CommandRequest[bool]¶
Restore libraries/functions from a serialized payload (from function_dump).
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.FUNCTION_RESTORE
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- function_stats() CommandRequest[dict[AnyStr, AnyStr | dict[AnyStr, dict[AnyStr, ResponsePrimitive]] | None]]¶
Return runtime statistics for the currently running function (if any).
- Returns:
Dict with running_script, engines, etc.; None if no function is running.
Redis command documentation: CommandName.FUNCTION_STATS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.1.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- 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) CommandRequest[int]¶
Add one or more geospatial items (longitude, latitude, name) to the index at key.
- Parameters:
- Returns:
The number of elements added; or, if
changeisTrue, the number changed.
Redis command documentation: CommandName.GEOADD
Compatibility:
condition: New in Redis version: 6.2.0change: New in Redis version: 6.2.0
- geodist(key: KeyT, member1: StringT, member2: StringT, unit: Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] | None = None) CommandRequest[float | None]¶
Return the distance between two members in the geospatial index.
- Parameters:
- Returns:
The distance in the requested unit, or
Noneif a member is missing.
Redis command documentation: CommandName.GEODIST
- geohash(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[AnyStr, ...]]¶
Return geohash strings for the given members in the geospatial index.
- Parameters:
- Returns:
A tuple of geohash strings (same order as members).
Redis command documentation: CommandName.GEOHASH
- geopos(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[GeoCoordinates | None, ...]]¶
Return longitude and latitude for the given members in the geospatial index.
- Parameters:
- Returns:
A tuple of
(lon, lat)pairs orNonefor missing members.
Redis command documentation: CommandName.GEOPOS
- 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index for members within radius of a center.
- Parameters:
key¶ – The key name.
longitude¶ – Center longitude.
latitude¶ – Center latitude.
radius¶ – Maximum distance from center.
unit¶ – M, KM, FT, or MI.
withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.order¶ – ASC or DESC by distance.
store¶ – Store results in this key (sorted set).
storedist¶ – Store results with distances in this key.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.Count of stored results if
storeorstoredistare provided
Redis command documentation: CommandName.GEORADIUS
Compatibility:
Caution
Deprecated in Redis version: 6.2.0 Use
geosearch()andgeosearchstore()with the radius argumentany_: New in Redis version: 6.2.0
- 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index for members within radius of an existing member.
- Parameters:
key¶ – The key name.
member¶ – Member to use as center.
radius¶ – Maximum distance from member.
unit¶ – M, KM, FT, or MI.
withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.order¶ – ASC or DESC by distance.
store¶ – Store results in this key (sorted set).
storedist¶ – Store results with distances in this key.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.Count of stored results if
storeorstoredistare provided
Redis command documentation: CommandName.GEORADIUSBYMEMBER
Caution
Deprecated in Redis version: 6.2.0 Use
geosearch()andgeosearchstore()with the radius and member arguments
- geosearch(key: KeyT, member: ValueT | None = None, longitude: int | float | None = None, latitude: int | float | None = None, radius: int | float | None = None, circle_unit: None | Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] = 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) CommandRequest[int | tuple[AnyStr | GeoSearchResult, ...]]¶
Query a geospatial index by center (member or lon/lat) and radius or bounding box.
- Parameters:
key¶ – The key name.
member¶ – Use this member as center (alternative to longitude/latitude).
longitude¶ – Center longitude (with latitude).
latitude¶ – Center latitude (with longitude).
radius¶ – Maximum distance; use with circle_unit.
circle_unit¶ – M, KM, FT, or MI for radius.
width¶ – Box width; use with height and box_unit.
height¶ – Box height; use with width and box_unit.
box_unit¶ – M, KM, FT, or MI for box.
order¶ – ASC or DESC by distance.
count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.withcoord¶ – If
True, include coordinates in results.withdist¶ – If
True, include distance in results.withhash¶ – If
True, include geohash in results.
- Returns:
Member names (default)
(name, dist, hash, coords)ifwith{coord,dist,hash}is provided.
Redis command documentation: CommandName.GEOSEARCH
Compatibility:
New in Redis version: 6.2.0
- 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: None | Literal[PureToken.M, PureToken.KM, PureToken.FT, PureToken.MI] = 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) CommandRequest[int]¶
Query a geospatial index and store the result in a sorted set at destination.
- Parameters:
destination¶ – Key where the result is stored.
source¶ – Source geospatial index key.
member¶ – Use this member as center (alternative to longitude/latitude).
longitude¶ – Center longitude (with latitude).
latitude¶ – Center latitude (with longitude).
radius¶ – Maximum distance; use with circle_unit.
circle_unit¶ – M, KM, FT, or MI for radius.
width¶ – Box width; use with height and box_unit.
height¶ – Box height; use with width and box_unit.
box_unit¶ – M, KM, FT, or MI for box.
order¶ – ASC or DESC by distance.
count¶ – Limit number of results.
any_¶ – If
True(with count), stop at first count matches.storedist¶ – If
True, store distances as scores.
- Returns:
The number of elements stored in the resulting set.
Redis command documentation: CommandName.GEOSEARCHSTORE
Compatibility:
New in Redis version: 6.2.0
- get(key: KeyT) CommandRequest[AnyStr | None]¶
Get the string value of a key.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key, or
Noneif the key does not exist.
Redis command documentation: CommandName.GET
Hint
Supports client side caching
- async get_library(name: StringT) Library¶
Fetch a pre registered library
- Parameters:
name¶ – name of the library
Added in version 3.1.0.
- getbit(key: KeyT, offset: int) CommandRequest[int]¶
Return the bit value at the given offset in the string value at key.
- Parameters:
- Returns:
0 or 1; 0 if key is missing or offset is beyond the string.
Redis command documentation: CommandName.GETBIT
- getdel(key: KeyT) CommandRequest[AnyStr | None]¶
Get the value of a key and delete the key.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key, or
Noneif the key does not exist. Raises an error if the key exists but is not a string.
Redis command documentation: CommandName.GETDEL
Compatibility:
New in Redis version: 6.2.0
- 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) CommandRequest[AnyStr | None]¶
Get the value of a key and optionally set or remove its expiration.
Similar to GET but supports expiry options. Time parameters may be
datetime.timedeltaordatetime.datetimeor integers.- Parameters:
key¶ – The key name.
ex¶ – Set key to expire after this many seconds (relative).
px¶ – Set key to expire after this many milliseconds (relative).
exat¶ – Set key to expire at this Unix timestamp in seconds (absolute).
pxat¶ – Set key to expire at this Unix timestamp in milliseconds (absolute).
persist¶ – If
True, remove the time-to-live from the key.
- Returns:
The value of the key, or
Noneif the key does not exist.
Redis command documentation: CommandName.GETEX
Compatibility:
New in Redis version: 6.2.0
- getrange(key: KeyT, start: int, end: int) CommandRequest¶
Return a substring of the string stored at a key.
Offsets are zero-based; negative offsets count from the end of the string. Both start and end are inclusive.
- Parameters:
- Returns:
The substring determined by the given offsets.
Redis command documentation: CommandName.GETRANGE
Hint
Supports client side caching
- getset(key: KeyT, value: ValueT) CommandRequest[AnyStr | None]¶
Set the string value of a key and return its old value
- Returns:
The previous value of the key, or
Noneif the key did not exist.
Redis command documentation: CommandName.GETSET
Caution
Deprecated in Redis version: 6.2.0 Use
set()with the get argument
- hdel(key: KeyT, fields: Parameters[StringT]) CommandRequest[int]¶
Delete one or more fields from a hash.
- Parameters:
- Returns:
The number of fields that were removed.
Redis command documentation: CommandName.HDEL
- hello(protover: int | None = None, username: StringT | None = None, password: StringT | None = None, setname: StringT | None = None) CommandRequest[dict[AnyStr, AnyStr]]¶
Perform a handshake with Redis (protocol version, auth, client name).
- Parameters:
- Returns:
A mapping of server properties (e.g. version, mode).
Redis command documentation: CommandName.HELLO
Compatibility:
New in Redis version: 6.0.0
Added in version 3.0.0.
- hexists(key: KeyT, field: StringT) CommandRequest[bool]¶
Return whether a field exists in a hash.
- Parameters:
- Returns:
Trueif the field exists,Falseotherwise.
Redis command documentation: CommandName.HEXISTS
Hint
Supports client side caching
- hexpire(key: KeyT, seconds: int | datetime.timedelta, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set a TTL in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HEXPIRE
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hexpireat(key: KeyT, unix_time_seconds: int | datetime.datetime, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set an absolute expiration Unix timestamp (seconds) for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HEXPIREAT
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hexpiretime(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the expiration Unix timestamp in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of Unix timestamps (-1 if no expiry, -2 if field missing).
Redis command documentation: CommandName.HEXPIRETIME
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hget(key: KeyT, field: StringT) CommandRequest[AnyStr | None]¶
Return the value of a field in a hash.
- Parameters:
- Returns:
The field value, or
Noneif the field or key does not exist.
Redis command documentation: CommandName.HGET
Hint
Supports client side caching
- hgetall(key: KeyT) CommandRequest[dict[AnyStr, AnyStr]]¶
Return all fields and values in a hash as a mapping.
- Parameters:
key¶ – The key name.
- Returns:
A mapping of field names to values.
Redis command documentation: CommandName.HGETALL
Hint
Supports client side caching
- hgetdel(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Get and delete the value of one or more fields of a given hash key. When the last field is deleted, the key will also be deleted.
- Parameters:
- Returns:
the values of the fields requested (Missing fields are returned as
None)
Redis command documentation: CommandName.HGETDEL
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hgetex(key: KeyT, fields: Parameters[StringT], ex: int | datetime.timedelta | None = None, px: int | datetime.timedelta | None = None, exat: int | datetime.datetime | None = None, pxat: int | datetime.datetime | None = None, persist: bool | None = None) CommandRequest[tuple[AnyStr | None, ...]]¶
Get the value of one or more fields of a given hash key and optionally set their expiration time or time-to-live (TTL).
- Parameters:
key¶ – The key of the hash
fields¶ – The fields to get values for
ex¶ – Set the expiry of the fields to
exsecondspx¶ – Set the expiry of the fields to
pxmillisecondsexat¶ – Set the expiry of the fields to the specified Unix time (seconds).
pxat¶ – Set the expiry of the fields to the specified Unix time (milliseconds).
persist¶ – Remove TTL from the fields.
- Returns:
the values of each of the fields requested (Missing fields are returned as
None)
Redis command documentation: CommandName.HGETEX
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hincrby(key: KeyT, field: StringT, increment: int) CommandRequest[int]¶
Increment the integer value of a hash field by the given amount.
- Parameters:
- Returns:
The value of the field after the increment.
Redis command documentation: CommandName.HINCRBY
- hincrbyfloat(key: KeyT, field: StringT, increment: int | float) CommandRequest[float]¶
Increment the float value of a hash field by the given amount.
- Parameters:
- Returns:
The value of the field after the increment.
Redis command documentation: CommandName.HINCRBYFLOAT
- hkeys(key: KeyT) CommandRequest[tuple[AnyStr, ...]]¶
Return all field names in a hash.
- Parameters:
key¶ – The key name.
- Returns:
A tuple of field names.
Redis command documentation: CommandName.HKEYS
Hint
Supports client side caching
- hlen(key: KeyT) CommandRequest[int]¶
Return the number of fields in a hash.
- Parameters:
key¶ – The key name.
- Returns:
The number of fields.
Redis command documentation: CommandName.HLEN
Hint
Supports client side caching
- hmget(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Return the values of multiple hash fields in one call.
- Parameters:
- Returns:
A tuple of values in the same order as fields.
Nonefor missing fields.
Redis command documentation: CommandName.HMGET
Hint
Supports client side caching
- hmset(key: KeyT, field_values: Mapping[MappingKeyT, ValueT]) CommandRequest[bool]¶
Set multiple field-value pairs in a hash.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.HMSET
Caution
Deprecated in Redis version: 4.0.0 Use
hset()with multiple field-value pairs
- hpersist(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Remove the expiration from one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that had TTL removed, 0 for each that did not.
Redis command documentation: CommandName.HPERSIST
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpire(key: KeyT, milliseconds: int | datetime.timedelta, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set a TTL in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HPEXPIRE
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpireat(key: KeyT, unix_time_milliseconds: int | datetime.datetime, fields: Parameters[StringT], condition: Literal[PureToken.GT, PureToken.LT, PureToken.NX, PureToken.XX] | None = None) CommandRequest[tuple[int, ...]]¶
Set an absolute expiration Unix timestamp (milliseconds) for one or more hash fields.
- Parameters:
- Returns:
A tuple of 1 for each field that was set, 0 for each that was not.
Redis command documentation: CommandName.HPEXPIREAT
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpexpiretime(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the expiration Unix timestamp in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of Unix timestamps in ms (-1 if no expiry, -2 if field missing).
Redis command documentation: CommandName.HPEXPIRETIME
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hpttl(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the TTL in milliseconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of TTLs in milliseconds (-1 if no expiry, -2 if field or key missing).
Redis command documentation: CommandName.HPTTL
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hrandfield(key: KeyT, *, count: int | None = None, withvalues: bool | None = None) CommandRequest[AnyStr | tuple[AnyStr, ...] | dict[AnyStr, AnyStr] | None]¶
Return one or more random fields from a hash, optionally with values.
- Parameters:
- Returns:
A single field, a tuple of fields, a dict (if withvalues), or
Noneif key is empty.
Redis command documentation: CommandName.HRANDFIELD
Compatibility:
New in Redis version: 6.2.0
- hscan(key: KeyT, cursor: int | None = None, match: StringT | None = None, count: int | None = None, novalues: bool | None = None) CommandRequest[tuple[int, dict[AnyStr, AnyStr] | tuple[AnyStr, ...]]]¶
Incrementally iterate over fields (and optionally values) in a hash.
- Parameters:
- Returns:
A tuple of
(next_cursor, mapping).If
novaluesis set, a tuple of(next_cursor, fields)
next_cursor0 means done.
Redis command documentation: CommandName.HSCAN
Compatibility:
novalues: New in Redis version: 7.4.0
- async hscan_iter(key: KeyT, match: StringT | None = None, count: int | None = None, novalues: Literal[True] | None = None) AsyncGenerator[tuple[AnyStr, AnyStr], None] | AsyncGenerator[AnyStr, None]¶
Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.
- hset(key: KeyT, field_values: Mapping[MappingKeyT, ValueT]) CommandRequest[int]¶
Set one or more field-value pairs in a hash.
- Parameters:
- Returns:
The number of fields that were added (new fields only).
Redis command documentation: CommandName.HSET
- hsetex(key: KeyT, field_values: Mapping[MappingKeyT, ValueT], condition: Literal[PureToken.FNX, PureToken.FXX] | 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) CommandRequest[bool]¶
Set the value of one or more fields of a given hash key, and optionally set their expiration time or time-to-live (TTL).
- Parameters:
key¶ – The key of the hash
field_values¶ – Mapping of fields and the values to set
condition¶ – If
FNXonly set the fields if none of them exist, ifFXXonly set the fields if all of them already existsex¶ – Set the expiry of the fields to
exsecondspx¶ – Set the expiry of the fields to
pxmillisecondsexat¶ – Set the expiry of the fields to the specified Unix time (seconds).
pxat¶ – Set the expiry of the fields to the specified Unix time (milliseconds).
keepttl¶ – Retain the TTL already associated with the fields.
- Returns:
Trueif all the fields were successfully set
Redis command documentation: CommandName.HSETEX
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- hsetnx(key: KeyT, field: StringT, value: ValueT) CommandRequest[bool]¶
Set a hash field only if it does not already exist.
- Parameters:
- Returns:
Trueif the field was set,Falseif it already existed.
Redis command documentation: CommandName.HSETNX
- hstrlen(key: KeyT, field: StringT) CommandRequest[int]¶
Return the length of the string value of a hash field.
- Parameters:
- Returns:
The length in bytes, or 0 if the field or key does not exist.
Redis command documentation: CommandName.HSTRLEN
Hint
Supports client side caching
- httl(key: KeyT, fields: Parameters[StringT]) CommandRequest[tuple[int, ...]]¶
Return the TTL in seconds for one or more hash fields.
- Parameters:
- Returns:
A tuple of TTLs in seconds (-1 if no expiry, -2 if field or key missing).
Redis command documentation: CommandName.HTTL
Compatibility:
New in Redis version: 7.4.0
Added in version 4.18.0.
- hvals(key: KeyT) CommandRequest[tuple[AnyStr, ...]]¶
Return all values in a hash.
- Parameters:
key¶ – The key name.
- Returns:
A tuple of values. Empty tuple if the key does not exist.
Redis command documentation: CommandName.HVALS
Hint
Supports client side caching
- 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"
- incr(key: KeyT) CommandRequest[int]¶
Increment the integer value of a key by one.
- Parameters:
key¶ – The key name.
- Returns:
The value of the key after the increment (1 if the key did not exist).
Redis command documentation: CommandName.INCR
- incrby(key: KeyT, increment: int) CommandRequest[int]¶
Increment the integer value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the increment (increment if key did not exist).
Redis command documentation: CommandName.INCRBY
- incrbyfloat(key: KeyT, increment: int | float) CommandRequest[float]¶
Increment the float value of a key by the given amount.
- Parameters:
- Returns:
The value of the key after the increment (increment if key did not exist).
Redis command documentation: CommandName.INCRBYFLOAT
- info(*sections: StringT) CommandRequest[dict[str, ResponseType]]¶
Return server information and statistics.
- Parameters:
sections¶ – Optional section names (e.g. server, memory, stats); default all.
- Returns:
Dict of section name to section data (parsed).
Redis command documentation: CommandName.INFO
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- keys(pattern: StringT = '*') CommandRequest[set[AnyStr]]¶
Return all key names matching the given glob pattern.
- Parameters:
pattern¶ – Glob pattern (e.g.
*,user:*).- Returns:
A set of matching key names.
Redis command documentation: CommandName.KEYS
Cluster note
The command will be routed to all primaries in the cluster and return the union of the results.
- lastsave() CommandRequest[datetime]¶
Return the time of the last successful background save to disk.
- Returns:
Datetime of last save.
Redis command documentation: CommandName.LASTSAVE
- latency_doctor() CommandRequest¶
Return a human-readable latency analysis report.
- Returns:
Report string.
Redis command documentation: CommandName.LATENCY_DOCTOR
Added in version 3.0.0.
- latency_graph(event: StringT) CommandRequest¶
Return an ASCII latency graph for the given event.
- Parameters:
event¶ – Event name (e.g. command name).
- Returns:
Graph string.
Redis command documentation: CommandName.LATENCY_GRAPH
Added in version 3.0.0.
- latency_histogram(*commands: StringT) CommandRequest[dict[AnyStr, dict[AnyStr, RedisValueT | dict[AnyStr, RedisValueT]]]]¶
Return the cumulative distribution of latencies for the given or all commands.
- Parameters:
commands¶ – Command names to include (empty = all).
- Returns:
Mapping of command to latency distribution info.
Redis command documentation: CommandName.LATENCY_HISTOGRAM
Compatibility:
New in Redis version: 7.0.0
Added in version 3.2.0.
- latency_history(event: StringT) CommandRequest[tuple[list[int], ...]]¶
Return timestamp-latency samples for the event.
- Parameters:
event¶ – Event name.
- Returns:
Tuple of (timestamp, latency) pairs.
Redis command documentation: CommandName.LATENCY_HISTORY
Added in version 3.0.0.
- latency_latest() CommandRequest[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: CommandName.LATENCY_LATEST
Added in version 3.0.0.
- latency_reset(*events: StringT) CommandRequest[int]¶
Reset latency data for one or more events.
- Returns:
the number of event time series that were reset.
Redis command documentation: CommandName.LATENCY_RESET
Added in version 3.0.0.
- lcs(key1: KeyT, key2: KeyT, *, len_: bool | None = None, idx: bool | None = None, minmatchlen: int | None = None, withmatchlen: bool | None = None) CommandRequest | CommandRequest[int] | CommandRequest[LCSResult]¶
Find the longest common substring between two string keys.
- Parameters:
- Returns:
The matched string (default), the length (if len_), or match positions and optionally lengths (if idx). Type depends on arguments.
Redis command documentation: CommandName.LCS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- lindex(key: KeyT, index: int) CommandRequest[AnyStr | None]¶
Return the element at index in the list.
- Parameters:
- Returns:
The element at that index, or
Noneif index is out of range.
Redis command documentation: CommandName.LINDEX
Hint
Supports client side caching
- linsert(key: KeyT, where: Literal[PureToken.AFTER, PureToken.BEFORE], pivot: ValueT, element: ValueT) CommandRequest[int]¶
Insert an element in the list before or after a pivot value.
- Parameters:
- Returns:
The length of the list after the insert, or -1 if pivot was not found.
Redis command documentation: CommandName.LINSERT
- llen(key: KeyT) CommandRequest[int]¶
Return the length of the list stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The length of the list (0 if key does not exist).
Redis command documentation: CommandName.LLEN
Hint
Supports client side caching
- lmove(source: KeyT, destination: KeyT, wherefrom: Literal[PureToken.LEFT, PureToken.RIGHT], whereto: Literal[PureToken.LEFT, PureToken.RIGHT]) CommandRequest[AnyStr | None]¶
Atomically pop an element from one list and push it to another.
- Parameters:
- Returns:
The element that was moved.
Redis command documentation: CommandName.LMOVE
Compatibility:
New in Redis version: 6.2.0
- lmpop(keys: Parameters[KeyT], where: Literal[PureToken.LEFT, PureToken.RIGHT], count: int | None = None) CommandRequest[list[AnyStr | list[AnyStr]] | None]¶
Pop elements from the first non-empty list among the given keys.
- Parameters:
- Returns:
Noneif all lists are empty; otherwise [key_name, [elements]].
Redis command documentation: CommandName.LMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- lolwut(version: int | None = None) CommandRequest[str]¶
Get the Redis version and a piece of generative computer art
Redis command documentation: CommandName.LOLWUT
- lpop(key: KeyT, count: int | None = None) CommandRequest[AnyStr | None] | CommandRequest[list[AnyStr] | None]¶
Remove and return the first element(s) from the list.
- Parameters:
- Returns:
The first element, or a list of elements if count is set;
Noneif key is empty or missing.
Redis command documentation: CommandName.LPOP
Compatibility:
count: New in Redis version: 6.2.0
- lpos(key: KeyT, element: ValueT, rank: int | None = None, count: int | None = None, maxlen: int | None = None) CommandRequest[int | None] | CommandRequest[list[int] | None]¶
Return the index of the first (or rank-th) occurrence of element in the list.
- Parameters:
- Returns:
A single index, or a list of indices if count is set;
Noneif no match.
Redis command documentation: CommandName.LPOS
Compatibility:
New in Redis version: 6.0.6
Hint
Supports client side caching
- lpush(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Prepend one or more elements to a list.
- Parameters:
- Returns:
The length of the list after the push.
Redis command documentation: CommandName.LPUSH
- lpushx(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Prepend elements to a list only if the list exists.
- Parameters:
- Returns:
The length of the list after the push (0 if key did not exist).
Redis command documentation: CommandName.LPUSHX
- lrange(key: KeyT, start: int, stop: int) CommandRequest[list[AnyStr]]¶
Return a range of elements from the list (inclusive of both ends).
- Parameters:
- Returns:
A list of elements in the specified range.
Redis command documentation: CommandName.LRANGE
Hint
Supports client side caching
- lrem(key: KeyT, count: int, element: ValueT) CommandRequest[int]¶
Remove occurrences of element from the list. Count controls direction and limit.
- Parameters:
- Returns:
The number of elements removed.
Redis command documentation: CommandName.LREM
- lset(key: KeyT, index: int, element: ValueT) CommandRequest[bool]¶
Set the list element at index to the given value.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.LSET
- ltrim(key: KeyT, start: int, stop: int) CommandRequest[bool]¶
Trim the list to the specified range (inclusive); remove elements outside the range.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.LTRIM
- memory_doctor() CommandRequest¶
Outputs memory problems report
Redis command documentation: CommandName.MEMORY_DOCTOR
Added in version 3.0.0.
- memory_malloc_stats() CommandRequest¶
Show allocator internal stats :return: the memory allocator’s internal statistics report
Redis command documentation: CommandName.MEMORY_MALLOC_STATS
Added in version 3.0.0.
- memory_purge() CommandRequest[bool]¶
Ask the allocator to release memory
Redis command documentation: CommandName.MEMORY_PURGE
Added in version 3.0.0.
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- memory_stats() CommandRequest[dict[AnyStr, ValueT]]¶
Show memory usage details :return: mapping of memory usage metrics and their values
Redis command documentation: CommandName.MEMORY_STATS
Added in version 3.0.0.
- memory_usage(key: KeyT, *, samples: int | None = None) CommandRequest[int | None]¶
Estimate the memory usage of a key
- Returns:
the memory usage in bytes, or
Nonewhen the key does not exist.
Redis command documentation: CommandName.MEMORY_USAGE
Added in version 3.0.0.
- mget(keys: Parameters[KeyT]) CommandRequest[tuple[AnyStr | None, ...]]¶
Get the values of multiple keys in a single call.
- Parameters:
keys¶ – One or more key names.
- Returns:
A tuple of values in the same order as keys;
Nonefor missing keys.
Redis command documentation: CommandName.MGET
Cluster note
The command will be routed to the nodes serving the keys in the command and return the concatenations of the results.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- 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) CommandRequest[bool]¶
Atomically transfer one or more keys from this instance to another Redis instance.
- Parameters:
host¶ – Host of the target instance.
port¶ – Port of the target instance.
destination_db¶ – Database index on the target.
timeout¶ – Maximum idle time for the connection in milliseconds.
keys¶ – One or more key names to migrate.
copy¶ – If
True, copy the key instead of moving it.replace¶ – If
True, replace existing keys on the target.auth¶ – Password for the target (legacy).
username¶ – Username for ACL auth on the target.
password¶ – Password for ACL auth on the target.
- Returns:
Trueon success indicates keys were found and transferred.
Redis command documentation: CommandName.MIGRATE
Added in version 3.0.0.
- module_list() CommandRequest[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
nameandver
Redis command documentation: CommandName.MODULE_LIST
Added in version 3.2.0.
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- module_load(path: StringT, *args: str | bytes | int | float) CommandRequest[bool]¶
Load a module
Redis command documentation: CommandName.MODULE_LOAD
Added in version 3.2.0.
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- module_loadex(path: StringT, configs: dict[StringT, ValueT] | None = None, args: Parameters[ValueT] | None = None) CommandRequest[bool]¶
Loads a module from a dynamic library at runtime with configuration directives.
Redis command documentation: CommandName.MODULE_LOADEX
Compatibility:
New in Redis version: 7.0.0
Added in version 3.4.0.
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- module_unload(name: StringT) CommandRequest[bool]¶
Unload a module by name.
- Parameters:
name¶ – Module name to unload.
- Returns:
Trueon success.
Redis command documentation: CommandName.MODULE_UNLOAD
Added in version 3.2.0.
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- move(key: KeyT, db: int) CommandRequest[bool]¶
Move a key from the currently selected database to the specified database.
- Parameters:
- Returns:
Trueif the key was moved,Falseif it already existed in the target db.
Redis command documentation: CommandName.MOVE
- mset(key_values: Mapping[KeyT, ValueT]) CommandRequest[bool]¶
Set multiple keys to their respective values in one operation.
- Parameters:
key_values¶ – Mapping of key names to string values.
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.MSET
Cluster note
The command will be routed to the nodes serving the keys in the command and return
Trueif all responses areTrue.To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- msetex(key_values: Mapping[KeyT, ValueT], *, condition: Literal[PureToken.NX, PureToken.XX] | 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) CommandRequest[bool]¶
Atomically set multiple string keys with an optional shared expiration.
- Parameters:
key_values¶ – Mapping of key names to string values.
condition¶ – Optional NX (only if not exists) or XX (only if exists).
ex¶ – Expire keys after this many seconds (relative).
px¶ – Expire keys after this many milliseconds (relative).
exat¶ – Expire keys at this Unix timestamp in seconds (absolute).
pxat¶ – Expire keys at this Unix timestamp in milliseconds (absolute).
keepttl¶ – If
True, retain existing TTL on keys that have one.
- Returns:
Trueif all keys were set.
Redis command documentation: CommandName.MSETEX
Compatibility:
New in Redis version: 8.4.0
- msetnx(key_values: Mapping[KeyT, ValueT]) CommandRequest[bool]¶
Set multiple keys to multiple values only if none of the keys exist.
- Parameters:
key_values¶ – Mapping of key names to string values.
- Returns:
Trueif all keys were set,Falseif any key already existed.
Redis command documentation: CommandName.MSETNX
- object_encoding(key: KeyT) CommandRequest[AnyStr | None]¶
Return the internal encoding for the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The encoding string (e.g. int, ziplist), or
Noneif the key does not exist.
Redis command documentation: CommandName.OBJECT_ENCODING
- object_freq(key: KeyT) CommandRequest[int]¶
Return the logarithmic access frequency counter for the object stored at key (LFU).
- Parameters:
key¶ – The key name.
- Returns:
The counter value.
Redis command documentation: CommandName.OBJECT_FREQ
- object_idletime(key: KeyT) CommandRequest[int]¶
Return the time in seconds since the last access to the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The idle time in seconds.
Redis command documentation: CommandName.OBJECT_IDLETIME
- object_refcount(key: KeyT) CommandRequest[int]¶
Return the reference count of the object stored at key.
- Parameters:
key¶ – The key name.
- Returns:
The number of references.
Redis command documentation: CommandName.OBJECT_REFCOUNT
- persist(key: KeyT) CommandRequest[bool]¶
Remove the expiration from a key so it no longer expires.
- Parameters:
key¶ – The key name.
- Returns:
Trueif the expiration was removed,Falseif the key had no expiry.
Redis command documentation: CommandName.PERSIST
- pexpire(key: KeyT, milliseconds: int | timedelta, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set a key’s time to live in milliseconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.PEXPIRE
Compatibility:
condition: New in Redis version: 7.0.0
- pexpireat(key: KeyT, unix_time_milliseconds: int | datetime, condition: Literal[PureToken.NX, PureToken.XX, PureToken.GT, PureToken.LT] | None = None) CommandRequest[bool]¶
Set the expiration for a key to an absolute Unix timestamp in milliseconds.
- Parameters:
- Returns:
Trueif the timeout was set,Falseotherwise.
Redis command documentation: CommandName.PEXPIREAT
Compatibility:
condition: New in Redis version: 7.0.0
- pexpiretime(key: KeyT) CommandRequest[datetime]¶
Return the expiration Unix timestamp for a key in milliseconds.
- Parameters:
key¶ – The key name.
- Returns:
Expiration as datetime (ms). -1 if no expiry, -2 if key does not exist.
Redis command documentation: CommandName.PEXPIRETIME
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- pfadd(key: KeyT, *elements: ValueT) CommandRequest[bool]¶
Add the specified elements to the HyperLogLog at key.
- Parameters:
- Returns:
Trueif at least one internal register was altered.
Redis command documentation: CommandName.PFADD
- pfcount(keys: Parameters[KeyT]) CommandRequest[int]¶
Return the approximated cardinality of the set(s) observed by the HyperLogLog(s) at key(s).
- Parameters:
keys¶ – One or more HyperLogLog key names.
- Returns:
The approximated number of unique elements.
Redis command documentation: CommandName.PFCOUNT
- pfmerge(destkey: KeyT, sourcekeys: Parameters[KeyT]) CommandRequest[bool]¶
Merge multiple HyperLogLogs into a single one at the destination key.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.PFMERGE
- ping(message: StringT | None = None) CommandRequest¶
Ping the server to test the connection.
- Parameters:
message¶ – Optional message; if provided, server echoes it instead of PONG.
- Returns:
PONGor the echoed message.
Redis command documentation: CommandName.PING
Cluster note
The command will be routed to all primaries in the cluster and return the first response if all responses are consistent.
- psetex(key: KeyT, milliseconds: int | timedelta, value: ValueT) CommandRequest[bool]¶
Set the value of a key with an expiration in milliseconds.
- Parameters:
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.PSETEX
- pttl(key: KeyT) CommandRequest[int]¶
Return the number of milliseconds until the key will expire.
- Parameters:
key¶ – The key name.
- Returns:
TTL in milliseconds. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.PTTL
- publish(channel: StringT, message: ValueT) CommandRequest[int]¶
Publish a message to a channel.
- Parameters:
- Returns:
Number of subscribers that received the message.
Redis command documentation: CommandName.PUBLISH
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- pubsub_channels(pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Return channel names that have at least one subscriber.
- Parameters:
pattern¶ – Optional glob pattern (default
*).- Returns:
Set of channel names.
Redis command documentation: CommandName.PUBSUB_CHANNELS
Cluster note
The command will be routed to all nodes in the cluster and return the union of the results.
- pubsub_numpat() CommandRequest[int]¶
Return the number of unique pattern subscriptions (PSUBSCRIBE) on this server.
- Returns:
Number of pattern subscriptions.
Redis command documentation: CommandName.PUBSUB_NUMPAT
- pubsub_numsub(*channels: StringT) CommandRequest[dict[AnyStr, int]]¶
Return the number of subscribers for each given channel.
- Parameters:
channels¶ – Channel names to query (empty = all with 0).
- Returns:
Mapping of channel name to subscriber count.
Redis command documentation: CommandName.PUBSUB_NUMSUB
Cluster note
The command will be routed to all nodes in the cluster and return the merged mapping.
- pubsub_shardchannels(pattern: StringT | None = None) CommandRequest[set[AnyStr]]¶
Return shard channel names that have at least one subscriber.
- Parameters:
pattern¶ – Optional glob pattern (default
*).- Returns:
Set of shard channel names.
Redis command documentation: CommandName.PUBSUB_SHARDCHANNELS
Compatibility:
New in Redis version: 7.0.0
Added in version 3.6.0.
Cluster note
The command will be routed to all nodes in the cluster and return the union of the results.
- pubsub_shardnumsub(*channels: StringT) CommandRequest[dict[AnyStr, int]]¶
Return the number of subscribers for each given shard channel.
- Parameters:
channels¶ – Shard channel names to query (empty = all with 0).
- Returns:
Mapping of shard channel name to subscriber count.
Redis command documentation: CommandName.PUBSUB_SHARDNUMSUB
Cluster note
The command will be routed to all nodes in the cluster and return the merged mapping.
- quit() CommandRequest[bool]¶
Close the connection to the server.
- Returns:
Trueon success.
Redis command documentation: CommandName.QUIT
Caution
Deprecated in Redis version: 7.1.240
- randomkey() CommandRequest[AnyStr | None]¶
Return a random key name from the currently selected database.
- Returns:
A key name, or
Nonewhen the database is empty.
Redis command documentation: CommandName.RANDOMKEY
Cluster note
The command will be routed to a random node in the cluster and return the response from the node.
- readonly() CommandRequest[bool]¶
Enable read queries for this connection to a cluster replica node.
- Returns:
Trueon success.
Redis command documentation: CommandName.READONLY
Added in version 3.2.0.
- readwrite() CommandRequest[bool]¶
Disable read-only mode; use this connection for read and write to the primary.
- Returns:
Trueon success.
Redis command documentation: CommandName.READWRITE
Added in version 3.2.0.
- async register_library(name: StringT, code: StringT, replace: bool = False) Library¶
Register a new library
- Parameters:
Added in version 3.1.0.
- register_script(script: RedisValueT) Script¶
Registers a Lua
script- Returns:
A
coredis.commands.script.Scriptinstance that is callable and hides the complexity of dealing with scripts, keys, and shas.
- rename(key: KeyT, newkey: KeyT) CommandRequest[bool]¶
Rename a key to a new name (overwrites newkey if it exists).
Redis command documentation: CommandName.RENAME
- renamenx(key: KeyT, newkey: KeyT) CommandRequest[bool]¶
Rename a key only if the new name does not already exist.
- Parameters:
- Returns:
Trueif the key was renamed,Falseif newkey already exists.
Redis command documentation: CommandName.RENAMENX
- replicaof(host: StringT | None = None, port: int | None = None) CommandRequest[bool]¶
Make the server a replica of the instance at host and port; no args to promote to master.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.REPLICAOF
Added in version 3.0.0.
- reset() CommandRequest[None]¶
Reset the connection (clear client state; server may disconnect).
- Returns:
None.
Redis command documentation: CommandName.RESET
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- 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) CommandRequest[bool]¶
Create a key from a serialized value (e.g. from dump).
- Parameters:
key¶ – The key name to create.
ttl¶ – TTL in milliseconds, or datetime for absolute expiry if absttl.
serialized_value¶ – The serialized value (bytes from dump).
replace¶ – If
True, overwrite existing key.absttl¶ – If
True, ttl is an absolute Unix timestamp in ms.idletime¶ – Optional idle time in seconds before eviction.
freq¶ – Optional access frequency for LFU eviction.
- Returns:
Trueon success.
Redis command documentation: CommandName.RESTORE
- role() CommandRequest[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: CommandName.ROLE
- rpop(key: KeyT, count: int | None = None) CommandRequest[AnyStr | None] | CommandRequest[list[AnyStr] | None]¶
Remove and return the last element(s) from the list.
- Parameters:
- Returns:
The last element, or a list if count is set;
Noneif key is empty or missing.
Redis command documentation: CommandName.RPOP
Compatibility:
count: New in Redis version: 6.2.0
- rpoplpush(source: KeyT, destination: KeyT) CommandRequest[AnyStr | None]¶
Atomically pop the last element from source and prepend it to destination.
- Parameters:
- Returns:
The element that was moved.
Redis command documentation: CommandName.RPOPLPUSH
Caution
Deprecated in Redis version: 6.2.0 Use
lmove()with the wherefrom and whereto arguments
- rpush(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Append one or more elements to a list.
- Parameters:
- Returns:
The length of the list after the push.
Redis command documentation: CommandName.RPUSH
- rpushx(key: KeyT, elements: Parameters[ValueT]) CommandRequest[int]¶
Append elements to a list only if the list exists.
- Parameters:
- Returns:
The length of the list after the push (0 if key did not exist).
Redis command documentation: CommandName.RPUSHX
- sadd(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Add one or more members to a set.
- Parameters:
- Returns:
The number of members that were added (excluding those already in the set).
Redis command documentation: CommandName.SADD
- save() CommandRequest[bool]¶
Tells the Redis server to save its data to disk, blocking until the save is complete
Redis command documentation: CommandName.SAVE
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- scan(cursor: int | None = 0, match: StringT | None = None, count: int | None = None, type_: StringT | None = None) CommandRequest[tuple[int, tuple[AnyStr, ...]]]¶
Incrementally iterate over the key space using a cursor.
- Parameters:
- Returns:
A tuple of
(next_cursor, tuple_of_keys).next_cursor0 means done.
Redis command documentation: CommandName.SCAN
Cluster note
The command will be routed to the explicitly passed slot when called with
route()and return the response from the node.
- scard(key: KeyT) CommandRequest[int]¶
Return the number of members in a set.
- Parameters:
key¶ – The key name.
- Returns:
The cardinality of the set (0 if key does not exist).
Redis command documentation: CommandName.SCARD
Hint
Supports client side caching
- script_debug(mode: Literal[PureToken.NO, PureToken.SYNC, PureToken.YES]) CommandRequest[bool]¶
Set the debug mode for executed scripts
- Raises:
Redis command documentation: CommandName.SCRIPT_DEBUG
Added in version 3.0.0.
- script_exists(sha1s: Parameters[StringT]) CommandRequest[tuple[bool, ...]]¶
Check whether the given scripts exist in the server script cache.
- Parameters:
sha1s¶ – One or more SHA1 digests of scripts.
- Returns:
Tuple of booleans, one per digest (
Trueif cached).
Redis command documentation: CommandName.SCRIPT_EXISTS
Cluster note
The command will be routed to all primaries in the cluster and return the logical AND of all responses.
- script_flush(flush_type: Literal[PureToken.ASYNC, PureToken.SYNC] | None = None) CommandRequest[bool]¶
Remove all scripts from the server script cache.
- Parameters:
flush_type¶ – ASYNC (default) or SYNC.
- Returns:
Trueon success.
Redis command documentation: CommandName.SCRIPT_FLUSH
Compatibility:
sync_type: New in Redis version: 6.2.0
Cluster note
The command will be routed to all nodes in the cluster and return
Trueif all responses areTrue.
- script_kill() CommandRequest[bool]¶
Terminate the currently running Lua script (if any).
- Returns:
Trueif a script was killed.
Redis command documentation: CommandName.SCRIPT_KILL
Cluster note
The command will be routed to all primaries in the cluster and return the first response that is not an error.
- script_load(script: StringT) CommandRequest¶
Load a Lua script into the server script cache.
- Parameters:
script¶ – The Lua script source code.
- Returns:
The SHA1 digest of the script.
Redis command documentation: CommandName.SCRIPT_LOAD
Cluster note
The command will be routed to all nodes in the cluster and return the first response if all responses are consistent.
- sdiff(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the difference of the first set and all successive sets (members in first but not in others).
- Parameters:
keys¶ – One or more set key names (first is the base set).
- Returns:
A set of members in the difference.
Redis command documentation: CommandName.SDIFF
- sdiffstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set difference and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SDIFFSTORE
- select(index: int) CommandRequest[bool]¶
Change the selected database for the current connection.
- Parameters:
index¶ – The database index (typically 0-15).
- Returns:
Trueon success.
Redis command documentation: CommandName.SELECT
Warning
Using
selectdirectly is not recommended. Use the db argument when initializing the client to ensure that all connections originating from this client use the desired database numberAdded in version 3.0.0.
- sentinel_config_get(name: RedisValueT) CommandRequest[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:
New in Redis version: 6.2.0
- sentinel_config_set(name: RedisValueT, value: RedisValueT) CommandRequest[bool]¶
Set the value of a global Sentinel configuration parameter
Compatibility:
New in Redis version: 6.2
- sentinel_failover(service_name: StringT) CommandRequest[bool]¶
Force a failover as if the master was not reachable, and without asking for agreement to other Sentinels
- sentinel_flushconfig() CommandRequest[bool]¶
Force Sentinel to rewrite its configuration on disk, including the current Sentinel state.
- sentinel_get_master_addr_by_name(service_name: StringT) CommandRequest[tuple[str, int] | None]¶
Returns a (host, port) pair for the given
service_name
- sentinel_infocache(*nodenames: StringT) CommandRequest[dict[AnyStr, dict[int, dict[str, ResponsePrimitive]]]]¶
Return cached INFO output from masters and replicas.
- sentinel_master(service_name: StringT) CommandRequest[dict[str, ResponsePrimitive]]¶
Returns a dictionary containing the specified masters state.
- sentinel_masters() CommandRequest[dict[str, dict[str, ResponsePrimitive]]]¶
Returns a list of dictionaries containing each master’s state.
- sentinel_monitor(name: RedisValueT, ip: RedisValueT, port: int, quorum: int) CommandRequest[bool]¶
Adds a new master to Sentinel to be monitored
- sentinel_myid() CommandRequest¶
Return the ID of the Sentinel instance Compatibility:
New in Redis version: 6.2.0
- sentinel_remove(name: RedisValueT) CommandRequest[bool]¶
Removes a master from Sentinel’s monitoring
- sentinel_replicas(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of replicas for
service_name
- sentinel_reset(pattern: StringT) CommandRequest[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.
- sentinel_sentinels(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of sentinels for
service_name
- sentinel_set(name: RedisValueT, option: RedisValueT, value: RedisValueT) CommandRequest[bool]¶
Sets Sentinel monitoring parameters for a given master
- sentinel_slaves(service_name: StringT) CommandRequest[tuple[dict[str, ResponsePrimitive], ...]]¶
Returns a list of slaves for paramref:service_name
- 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, ifeq: ValueT | None = None, ifne: ValueT | None = None, ifdeq: ValueT | None = None, ifdne: ValueT | None = None) CommandRequest[AnyStr | bool | None]¶
Set the string value of a key with optional condition and expiration.
- Parameters:
key¶ – The key name.
value¶ – The string value to set.
condition¶ – NX (set only if not exists) or XX (set only if exists).
get¶ – If
True, return the previous value (orNone); aborts if not a string.ex¶ – Expire after this many seconds (relative).
px¶ – Expire after this many milliseconds (relative).
exat¶ – Expire at this Unix timestamp in seconds (absolute).
pxat¶ – Expire at this Unix timestamp in milliseconds (absolute).
keepttl¶ – If
True, retain the existing TTL.ifeq¶ – Set only if current value equals this value.
ifne¶ – Set only if current value does not equal this value.
ifdeq¶ – Set only if current hash digest equals this value.
ifdne¶ – Set only if current hash digest does not equal this value.
- Returns:
True/Falseif the set operation succeeded unlessgetisTrue, in which case the previous value orNoneif the key didn’t exist.
Redis command documentation: CommandName.SET
Compatibility:
exat: New in Redis version: 6.2.0pxat: New in Redis version: 6.2.0get: New in Redis version: 6.2.0ifeq: New in Redis version: 8.4.0ifne: New in Redis version: 8.4.0ifdeq: New in Redis version: 8.4.0ifdne: New in Redis version: 8.4.0
- setbit(key: KeyT, offset: int, value: int) CommandRequest[int]¶
Set or clear the bit at the given offset in the string value at key.
- Parameters:
- Returns:
Previous bit value at that offset.
Redis command documentation: CommandName.SETBIT
- setex(key: KeyT, value: ValueT, seconds: int | timedelta) CommandRequest[bool]¶
Set the value of a key with an expiration in seconds.
- Parameters:
- Returns:
Always
Trueon success.
Redis command documentation: CommandName.SETEX
- setnx(key: KeyT, value: ValueT) CommandRequest[bool]¶
Set the value of a key only if the key does not exist.
- Parameters:
- Returns:
Trueif the key was set,Falseif it already existed.
Redis command documentation: CommandName.SETNX
- setrange(key: KeyT, offset: int, value: ValueT) CommandRequest[int]¶
Overwrite part of the string value at a key starting at the given offset.
If offset plus value length exceeds the current length, the string is extended. If offset is past the end, the gap is padded with zero bytes.
- Parameters:
- Returns:
The length of the string after the operation.
Redis command documentation: CommandName.SETRANGE
- shutdown(nosave_save: Literal[PureToken.NOSAVE, PureToken.SAVE] | None = None, *, now: bool | None = None, force: bool | None = None, abort: bool | None = None) CommandRequest[bool]¶
Stop the Redis server (optionally save, nosave, now, force, or abort).
- Parameters:
- Returns:
Trueon success (connection will close).
Redis command documentation: CommandName.SHUTDOWN
Compatibility:
now: New in Redis version: 7.0.0force: New in Redis version: 7.0.0abort: New in Redis version: 7.0.0
- sinter(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the intersection of all given sets.
- Parameters:
keys¶ – One or more set key names.
- Returns:
A set of members in the intersection.
Redis command documentation: CommandName.SINTER
- sintercard(keys: Parameters[KeyT], limit: int | None = None) CommandRequest[int]¶
Return the cardinality of the intersection of multiple sets.
- Parameters:
- Returns:
The number of elements in the resulting intersection.
Redis command documentation: CommandName.SINTERCARD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- sinterstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set intersection and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SINTERSTORE
- sismember(key: KeyT, member: ValueT) CommandRequest[bool]¶
Return whether the given value is a member of the set.
- Parameters:
- Returns:
Trueif member is in the set,Falseotherwise or if key does not exist.
Redis command documentation: CommandName.SISMEMBER
Hint
Supports client side caching
- slaveof(host: StringT | None = None, port: int | None = None) CommandRequest[bool]¶
Make the server a replica of the instance at host and port; no args to promote to master.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.SLAVEOF
Caution
Deprecated in Redis version: 5.0.0 Use
replicaof()
- slowlog_get(count: int | None = None) CommandRequest[tuple[SlowLogInfo, ...]]¶
Return entries from the slow query log.
- Parameters:
count¶ – Limit to this many most recent entries (optional).
- Returns:
Tuple of slowlog entry dicts (id, timestamp, duration, command, client, name).
Redis command documentation: CommandName.SLOWLOG_GET
- slowlog_len() CommandRequest[int]¶
Return the number of entries currently in the slow log.
- Returns:
The number of slow log entries.
Redis command documentation: CommandName.SLOWLOG_LEN
- slowlog_reset() CommandRequest[bool]¶
Remove all entries from the slow log.
- Returns:
Trueon success.
Redis command documentation: CommandName.SLOWLOG_RESET
- smembers(key: KeyT) CommandRequest[set[AnyStr]]¶
Return all members of a set.
- Parameters:
key¶ – The key name.
- Returns:
A set of all members; empty set if the key does not exist.
Redis command documentation: CommandName.SMEMBERS
Hint
Supports client side caching
- smismember(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[bool, ...]]¶
Return whether each given value is a member of the set.
- Parameters:
- Returns:
A tuple of booleans in the same order as members.
Redis command documentation: CommandName.SMISMEMBER
Compatibility:
New in Redis version: 6.2.0
Hint
Supports client side caching
- smove(source: KeyT, destination: KeyT, member: ValueT) CommandRequest[bool]¶
Move a member from one set to another (atomic).
- Parameters:
- Returns:
Trueif the member was moved,Falseif it was not in source.
Redis command documentation: CommandName.SMOVE
- 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) CommandRequest[tuple[AnyStr, ...] | int]¶
Sort elements in a list, set, or sorted set, optionally storing the result.
- Parameters:
key¶ – The key name.
gets¶ – Optional keys or patterns to retrieve external values (e.g. *->field).
offset¶ – Skip this many elements (use with count for LIMIT).
count¶ – Return this many elements (use with offset).
order¶ – ASC or DESC.
alpha¶ – If
True, sort lexicographically.store¶ – If set, store the result in this key instead of returning.
- Returns:
A tuple of sorted elements, or the number of stored elements if store is set.
Redis command documentation: CommandName.SORT
- 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) CommandRequest[tuple[AnyStr, ...]]¶
Sort the elements in a list, set or sorted set. Read-only variant of SORT.
- Returns:
sorted elements.
Redis command documentation: CommandName.SORT_RO
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- spop(key: KeyT, count: int | None = None) CommandRequest | CommandRequest[set[AnyStr] | None]¶
Remove and return one or more random members from the set.
- Parameters:
- Returns:
A single member, or a set if count is set;
Noneor empty if key is empty/missing.
Redis command documentation: CommandName.SPOP
- spublish(channel: StringT, message: ValueT) CommandRequest[int]¶
Publish a message to a shard channel.
- Parameters:
- Returns:
Number of shard subscribers that received the message (exact node only).
Redis command documentation: CommandName.SPUBLISH
Compatibility:
New in Redis version: 7.0.0
Added in version 3.6.0.
- srandmember(key: KeyT, count: int | None = None) CommandRequest[AnyStr | set[AnyStr]]¶
Return one or more random members from the set (without removing).
- Parameters:
- Returns:
A single member, or a set/tuple if count is set;
Noneor empty if key is empty.
Redis command documentation: CommandName.SRANDMEMBER
- srem(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Remove one or more members from the set.
- Parameters:
- Returns:
The number of members that were removed.
Redis command documentation: CommandName.SREM
- sscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) CommandRequest[tuple[int, set[AnyStr]]]¶
Incrementally iterate over members of a set using a cursor.
- Parameters:
- Returns:
A tuple of (next_cursor, set_of_members); next_cursor 0 means done.
Redis command documentation: CommandName.SSCAN
- 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.
- strlen(key: KeyT) CommandRequest[int]¶
Return the length of the string value stored at a key.
- Parameters:
key¶ – The key name.
- Returns:
The length of the string in bytes, or
0if the key does not exist.
Redis command documentation: CommandName.STRLEN
Hint
Supports client side caching
- substr(key: KeyT, start: int, end: int) CommandRequest¶
Return a substring of the string stored at a key.
- Parameters:
- Returns:
The substring in the given range.
Redis command documentation: CommandName.SUBSTR
Caution
Deprecated in Redis version: 2.0.0 Use
getrange()Hint
Supports client side caching
- sunion(keys: Parameters[KeyT]) CommandRequest[_Set[AnyStr]]¶
Return the union of all given sets.
- Parameters:
keys¶ – One or more set key names.
- Returns:
A set of all members in the union.
Redis command documentation: CommandName.SUNION
- sunionstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute set union and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting set.
Redis command documentation: CommandName.SUNIONSTORE
- swapdb(index1: int, index2: int) CommandRequest[bool]¶
Swaps two Redis databases
Redis command documentation: CommandName.SWAPDB
Added in version 3.0.0.
- time() CommandRequest[datetime]¶
Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).
Redis command documentation: CommandName.TIME
- property timeseries: TimeSeries¶
Property to access
TimeSeriescommands.Added in version 4.12.0.
- touch(keys: Parameters[KeyT]) CommandRequest[int]¶
Update the last access time of one or more keys (only existing keys are counted).
- Parameters:
keys¶ – One or more key names.
- Returns:
The number of keys that existed and were touched.
Redis command documentation: CommandName.TOUCH
Cluster note
The command will be routed to the nodes serving the keys in the command and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- ttl(key: KeyT) CommandRequest[int]¶
Return the time to live for a key in seconds.
- Parameters:
key¶ – The key name.
- Returns:
TTL in seconds. -1 if key has no expiry, -2 if key does not exist.
Redis command documentation: CommandName.TTL
- type(key: KeyT) CommandRequest[AnyStr | None]¶
Return the type of the value stored at key.
- Parameters:
key¶ – The key name.
- Returns:
One of string, list, set, zset, hash, stream, etc.;
Noneif key does not exist.
Redis command documentation: CommandName.TYPE
Hint
Supports client side caching
- unlink(keys: Parameters[KeyT]) CommandRequest[int]¶
Delete keys asynchronously in a background thread (non-blocking).
- Parameters:
keys¶ – One or more key names to unlink.
- Returns:
The number of keys that were unlinked.
Redis command documentation: CommandName.UNLINK
Cluster note
The command will be routed to the nodes serving the keys in the command and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slottoFalse
- vadd(key: KeyT, element: ValueT, values: Parameters[float | int] | bytes, reduce: int | None = None, cas: bool | None = None, quantization: Literal[PureToken.BIN, PureToken.NOQUANT, PureToken.Q8] | None = None, ef: int | None = None, attributes: JsonType | None = None, numlinks: int | None = None) CommandRequest[bool]¶
Add a new element into the vector set specified by key
- Parameters:
key¶ – The key containing the vector set
element¶ – The name of the element being added to the vector set
values¶ – either a byte representation of a 32-bit floating point (FP32) blob of values or a sequence of doubles representing the vector.
reduce¶ – dimensions to reduce the vector values to
cas¶ – whether to add using check-and-set
quantization¶ – The quantization type to use
ef¶ – exploration factor to use when connecting the element to the existing graph
attributes¶ – json attributes to associate with the element
numlinks¶ – maximum number of connections each node in the graph will have with other nodes.
- Returns:
Trueif the element was successfully added to the vector set
Redis command documentation: CommandName.VADD
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vcard(key: KeyT) CommandRequest[int]¶
Return the number of elements in a vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
The number of elements in the vector set
Redis command documentation: CommandName.VCARD
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vdim(key: KeyT) CommandRequest[int]¶
Return the dimension of vectors in the vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
The dimensions of the vectors in the vector set
Redis command documentation: CommandName.VDIM
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vemb(key: KeyT, element: StringT, raw: bool | None = None) CommandRequest[tuple[float, ...] | VectorData | None]¶
Return the vector associated with an element
- Parameters:
- Returns:
Tuple of floats for the vector; if raw is True, VectorData with metadata.
Redis command documentation: CommandName.VEMB
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vgetattr(key: KeyT, element: StringT) CommandRequest[JsonType]¶
Retrieve the JSON attributes of elements
- Parameters:
- Returns:
the attributes of the element or None if they don’t exist.
Redis command documentation: CommandName.VGETATTR
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vinfo(key: KeyT) CommandRequest[dict[AnyStr, AnyStr | int] | None]¶
Return information about a vector set
- Parameters:
key¶ – The key containing the vector set
- Returns:
mapping of attributes and values describing the vector set
Redis command documentation: CommandName.VINFO
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vismember(key: KeyT, element: StringT) CommandRequest[bool]¶
Check if an element exists in a vector set
Redis command documentation: CommandName.VISMEMBER
Compatibility:
New in Redis version: 8.2.0
Added in version 5.2.0.
- vlinks(key: KeyT, element: StringT, withscores: bool | None = None) CommandRequest[tuple[tuple[AnyStr, ...] | dict[AnyStr, float], ...] | None]¶
Return the neighbors of an element at each layer in the HNSW graph
- Parameters:
- Returns:
Tuple of layers, each a tuple of neighbours (or mapping to scores if withscores); last is lowest layer.
Redis command documentation: CommandName.VLINKS
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vrandmember(key: KeyT, count: int | None = None) CommandRequest[tuple[AnyStr | None, ...] | AnyStr | None]¶
Return one or multiple random members from a vector set
- Parameters:
- Returns:
A random element, or a tuple of elements if count is specified; negative count allows duplicates.
Redis command documentation: CommandName.VRANDMEMBER
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vrange(key: KeyT, start: StringT, end: StringT, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Retreives all elements inside a vector set (optionally, in small batches with the use of
count)- Parameters:
- Returns:
The elements in lexicographical order within the range
Redis command documentation: CommandName.VRANGE
Compatibility:
New in Redis version: 8.4.0
Added in version 6.0.0.
- vrem(key: KeyT, element: ValueT) CommandRequest[bool]¶
Remove an element from a vector set.
- Parameters:
- Returns:
Trueif the element was successfully deleted from the set
Redis command documentation: CommandName.VREM
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vsetattr(key: KeyT, element: StringT, attributes: JsonType) CommandRequest[bool]¶
Associate or remove the JSON attributes of elements
- Parameters:
- Returns:
Trueif the attributes were successfully set
Redis command documentation: CommandName.VSETATTR
Compatibility:
New in Redis version: 8.0.0
Added in version 5.0.0.
- vsim(key: KeyT, *, element: StringT | None = None, values: Parameters[float] | bytes | None = None, withscores: bool | None = None, withattribs: bool | None = None, count: int | None = None, epsilon: float | None = None, ef: int | None = None, filter: StringT | None = None, filter_ef: int | None = None, truth: bool | None = None, nothread: bool | None = None) CommandRequest[tuple[AnyStr, ...] | dict[AnyStr, float] | dict[AnyStr, JsonType] | dict[AnyStr, tuple[float, JsonType]]]¶
Return elements similar to a given vector or element
- Parameters:
key¶ – The key containing the vector set
element¶ – An existing element to find similar elements for
values¶ – either a byte representation of a 32-bit floating point (FP32) blob of values or a sequence of doubles representing the vector to use as the similarity reference.
withscores¶ – whether to return similarity scores for each result
withattribs¶ – whether to include attributes for for each result
count¶ – number of results to limit to
epsilon¶ – distance threshold; results with distance greater than this are excluded.
ef¶ – Search exploration factor
filter¶ – Expression to restrict matching elements
filter_ef¶ – limits the number of filtering attempts
truth¶ – forces an exact linear scan of all elements bypassing the HSNW graph
nothread¶ – execute the search in the main thread instead of a background thread
- Returns:
Matching elements; optionally with scores (if withscores) and/or attributes (if withattribs).
Redis command documentation: CommandName.VSIM
Compatibility:
New in Redis version: 8.0.0
withattribs: New in Redis version: 8.2epsilon: New in Redis version: 8.2
Added in version 5.0.0.
- wait(numreplicas: int, timeout: int) CommandRequest[int]¶
Block until write commands are replicated to at least the given number of replicas.
- Parameters:
- Returns:
The number of replicas that acknowledged the writes.
Redis command documentation: CommandName.WAIT
Warning
Using
waitdirectly is not recommended. Use theRedis.ensure_replication()orRedisCluster.ensure_replication()context managers to ensure a command is replicated to the number of replicas
- waitaof(numlocal: int, numreplicas: int, timeout: int) CommandRequest[tuple[int, ...]]¶
Block until write commands are synced to AOF on the local host and/or replicas.
- Parameters:
- Returns:
A tuple of (numlocal, numreplicas) that were synced.
Redis command documentation: CommandName.WAITAOF
Compatibility:
New in Redis version: 7.1.240
Warning
Using
waitaofdirectly is not recommended. Use theRedis.ensure_persistence()orRedisCluster.ensure_persistence()context managers to ensure a command is synced to the AOF of the number of local hosts or replicasAdded in version 4.12.0.
- xack(key: KeyT, group: StringT, identifiers: Parameters[ValueT]) CommandRequest[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: CommandName.XACK
- xackdel(key: KeyT, group: StringT, identifiers: Parameters[ValueT], condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[tuple[int, ...]]¶
Acknowledge and optionally delete one or more stream entries for a consumer group.
- Parameters:
- Returns:
Tuple of 1 for each entry that was acked/deleted, 0 for others.
Redis command documentation: CommandName.XACKDEL
Compatibility:
New in Redis version: 8.2.0
Added in version 5.2.0.
- xadd(key: KeyT, field_values: Mapping[MappingKeyT, ValueT], *, identifier: ValueT | None = None, nomkstream: bool | None = None, idmpauto: StringT | None = None, idmp: tuple[StringT, StringT] | None = None, trim_strategy: Literal[PureToken.MAXLEN, PureToken.MINID] | None = None, threshold: ValueT | None = None, trim_operator: Literal[PureToken.EQUAL, PureToken.APPROXIMATELY] | None = None, limit: int | None = None, condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[AnyStr | None]¶
Append a new entry to a stream.
- Parameters:
key¶ – The stream key.
field_values¶ – Field names and values for the entry.
identifier¶ – Entry ID, or
*for auto-generated.nomkstream¶ – If
True, do not create the stream if it does not exist.idmpauto¶ – Auto ID mode (e.g. node-id).
idmp¶ – Manual ID range (min, max).
trim_strategy¶ – MAXLEN or MINID for trimming.
threshold¶ – Limit for trim (max length or min id).
trim_operator¶ – EQUAL or APPROXIMATELY for trim.
limit¶ – Max entries to evict per trim (optional).
condition¶ – KEEPREF, DELREF, or ACKED for trim.
- Returns:
The entry ID (auto or specified), or
Noneif nomkstream and key does not exist.
Redis command documentation: CommandName.XADD
Compatibility:
nomkstream: New in Redis version: 6.2.0limit: New in Redis version: 6.2.0condition: New in Redis version: 8.2.0idmpauto: New in Redis version: 8.6.0idmp: New in Redis version: 8.6.0
- xautoclaim(key: KeyT, group: StringT, consumer: StringT, min_idle_time: int | timedelta, start: ValueT, count: int | None = None, justid: bool | None = None) CommandRequest[tuple[AnyStr, tuple[AnyStr, ...]] | tuple[AnyStr, tuple[StreamEntry, ...], tuple[AnyStr, ...]]]¶
Transfer ownership of pending stream entries that match the specified criteria to the consumer group specified.
- Parameters:
key¶ – The stream key.
group¶ – Consumer group name.
consumer¶ – Consumer name to assign messages to.
min_idle_time¶ – Only claim entries idle at least this long (ms or timedelta).
start¶ – Start scanning from this ID (e.g.
0-0).count¶ – Max number of entries to claim per call.
justid¶ – If
True, return only entry IDs.
- Returns:
k(next_start_id, claimed_entries) or (next_start_id, claimed_entries, deleted_ids).
Redis command documentation: CommandName.XAUTOCLAIM
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- xcfgset(key: KeyT, idmp_duration: int | timedelta | None = None, idmp_maxsize: int | None = None) CommandRequest[bool]¶
Set IDMP (Idempotent Message Processing) configuration for a stream.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XCFGSET
Compatibility:
New in Redis version: 8.6.0
- 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) CommandRequest[tuple[AnyStr, ...] | tuple[StreamEntry, ...]]¶
Claim (or acquire) ownership of pending messages for a consumer in a group.
- Parameters:
key¶ – The stream key.
group¶ – Consumer group name.
consumer¶ – Consumer name to assign messages to.
min_idle_time¶ – Only claim entries idle at least this long (ms or timedelta).
identifiers¶ – Entry IDs to claim.
idle¶ – Set idle time for claimed entries (ms or timedelta).
time¶ – Set last-delivery time for claimed entries.
retrycount¶ – Set retry count for claimed entries.
force¶ – If
True, claim even if another consumer has them.justid¶ – If
True, return only entry IDs.lastid¶ – Optional last ID for the consumer (streaming).
- Returns:
Tuple of claimed entry IDs, or tuple of stream entries (unless justid).
Redis command documentation: CommandName.XCLAIM
- xdel(key: KeyT, identifiers: Parameters[ValueT]) CommandRequest[int]¶
Remove the specified entries from a stream.
- Parameters:
- Returns:
Number of entries deleted.
Redis command documentation: CommandName.XDEL
- xdelex(key: KeyT, identifiers: Parameters[ValueT], condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[tuple[int, ...]]¶
Delete one or more entries from the stream with optional condition.
- Parameters:
- Returns:
Tuple of 1 for each deleted entry, 0 for skipped.
Redis command documentation: CommandName.XDELEX
Compatibility:
New in Redis version: 8.2
Added in version 5.2.0.
- xgroup_create(key: KeyT, groupname: StringT, identifier: ValueT | None = None, mkstream: bool | None = None, entriesread: int | None = None) CommandRequest[bool]¶
Create a consumer group for the stream.
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XGROUP_CREATE
Compatibility:
entriesread: New in Redis version: 7.0.0
- xgroup_createconsumer(key: KeyT, groupname: StringT, consumername: StringT) CommandRequest[bool]¶
Create a consumer in a consumer group.
- Parameters:
- Returns:
Trueif the consumer was created, False if it already existed.
Redis command documentation: CommandName.XGROUP_CREATECONSUMER
Compatibility:
New in Redis version: 6.2.0
Added in version 3.0.0.
- xgroup_delconsumer(key: KeyT, groupname: StringT, consumername: StringT) CommandRequest[int]¶
Delete a consumer from a consumer group.
- Parameters:
- Returns:
Number of pending messages the consumer had before deletion.
Redis command documentation: CommandName.XGROUP_DELCONSUMER
Added in version 3.0.0.
- xgroup_destroy(key: KeyT, groupname: StringT) CommandRequest[int]¶
Destroy a consumer group.
- Parameters:
- Returns:
Number of groups destroyed (1 or 0).
Redis command documentation: CommandName.XGROUP_DESTROY
- xgroup_setid(key: KeyT, groupname: StringT, identifier: ValueT | None = None, entriesread: int | None = None) CommandRequest[bool]¶
Set the consumer group’s last-delivered ID (e.g. to reprocess or skip).
- Parameters:
- Returns:
Trueon success.
Redis command documentation: CommandName.XGROUP_SETID
Compatibility:
entriesread: New in Redis version: 7.0.0
Added in version 3.0.0.
- xinfo_consumers(key: KeyT, groupname: StringT) CommandRequest[tuple[dict[AnyStr, AnyStr | int | None], ...]]¶
Return all consumers in a consumer group for the stream.
- Parameters:
- Returns:
Tuple of consumer info dicts (name, pending, idle, etc.).
Redis command documentation: CommandName.XINFO_CONSUMERS
- xinfo_groups(key: KeyT) CommandRequest[tuple[dict[AnyStr, AnyStr | int | None], ...]]¶
Return all consumer groups for the stream.
- Parameters:
key¶ – The stream key.
- Returns:
Tuple of group info dicts (name, consumers, pending, last-delivered-id, etc.).
Redis command documentation: CommandName.XINFO_GROUPS
- xinfo_stream(key: KeyT, full: bool | None = None, count: int | None = None) CommandRequest[StreamInfo]¶
Return information about the stream.
- Parameters:
key¶ – The stream key.
full¶ – If
True, include extended info (seecoredis.response.types.StreamInfo).count¶ – When full is true, limit number of entries in the result.
- Returns:
Stream info (length, groups, first/last entry, etc.; entries if full).
Redis command documentation: CommandName.XINFO_STREAM
- xlen(key: KeyT) CommandRequest[int]¶
Return the number of entries in a stream.
- Parameters:
key¶ – The stream key.
- Returns:
Number of entries in the stream.
Redis command documentation: CommandName.XLEN
- 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) CommandRequest[tuple[StreamPendingExt, ...] | StreamPending]¶
Return information about pending entries (fetched but not acknowledged) for a consumer group.
- Parameters:
- Returns:
Summary (total, min/max ids, consumers) or tuple of pending entry details.
Redis command documentation: CommandName.XPENDING
Compatibility:
idle: New in Redis version: 6.2.0
- xrange(key: KeyT, start: ValueT | None = None, end: ValueT | None = None, count: int | None = None) CommandRequest[tuple[StreamEntry, ...]]¶
Return a range of stream entries by ID interval.
- Parameters:
- Returns:
Tuple of stream entries in the range.
Redis command documentation: CommandName.XRANGE
- xread(streams: Mapping[MappingStringKeyT, ValueT], count: int | None = None, block: int | timedelta | None = None) CommandRequest[dict[AnyStr, tuple[StreamEntry, ...]] | None]¶
Read new entries from one or more streams with IDs greater than the given IDs.
- Parameters:
- Returns:
Mapping of stream key to tuple of entries;
Noneif block timeout is exceeded.
Redis command documentation: CommandName.XREAD
- xreadgroup(group: StringT, consumer: StringT, streams: Mapping[MappingStringKeyT, ValueT], count: int | None = None, block: int | timedelta | None = None, noack: bool | None = None) CommandRequest[dict[AnyStr, tuple[StreamEntry, ...]] | None]¶
Read entries from streams as a consumer in a group, with IDs greater than the given IDs.
- Parameters:
group¶ – Consumer group name.
consumer¶ – Consumer name.
streams¶ – Mapping of stream key to last-seen ID (use
>for new for this consumer).count¶ – Max entries to return per stream.
block¶ – Block up to this many milliseconds (or timedelta) for new data.
noack¶ – If
True, do not add messages to PEL (no XACK needed).
- Returns:
Mapping of stream key to tuple of entries;
Noneif block timeout is exceeded.
Redis command documentation: CommandName.XREADGROUP
- xrevrange(key: KeyT, end: ValueT | None = None, start: ValueT | None = None, count: int | None = None) CommandRequest[tuple[StreamEntry, ...]]¶
Return a range of stream entries by ID interval in reverse order.
- Parameters:
- Returns:
Tuple of stream entries in the range, high to low IDs.
Redis command documentation: CommandName.XREVRANGE
- 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, condition: Literal[PureToken.KEEPREF, PureToken.DELREF, PureToken.ACKED] | None = None) CommandRequest[int]¶
Trim the stream by evicting older entries.
- Parameters:
- Returns:
Number of entries removed.
Redis command documentation: CommandName.XTRIM
Compatibility:
limit: New in Redis version: 6.2.0condition: New in Redis version: 8.2.0
- 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) CommandRequest[int | float]¶
Add one or more members to a sorted set, or update their scores.
- Parameters:
key¶ – The key name.
member_scores¶ – Mapping of member names to scores.
condition¶ – NX (only add new) or XX (only update existing).
comparison¶ – GT (only if new score greater) or LT (only if new score less).
change¶ – If
True, return the number of elements changed (added or updated).increment¶ – If
True, add increment to existing score (like zincrby); return new score.
- Returns:
Number of elements added; or number changed if change; or new score if increment; or
Noneif aborted.
Redis command documentation: CommandName.ZADD
Compatibility:
comparison: New in Redis version: 6.2.0
- zcard(key: KeyT) CommandRequest[int]¶
Return the number of members in the sorted set.
- Parameters:
key¶ – The key name.
- Returns:
The cardinality (0 if key does not exist).
Redis command documentation: CommandName.ZCARD
- zcount(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Return the number of members in the sorted set with scores between min and max (inclusive).
- Parameters:
- Returns:
The number of members in the score range.
Redis command documentation: CommandName.ZCOUNT
- zdiff(keys: Parameters[KeyT], withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the difference of the first sorted set and all successive sets (members in first but not in others).
- Parameters:
- Returns:
Members (and optionally scores) in the difference.
Redis command documentation: CommandName.ZDIFF
Compatibility:
New in Redis version: 6.2.0
- zdiffstore(keys: Parameters[KeyT], destination: KeyT) CommandRequest[int]¶
Compute sorted set difference and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZDIFFSTORE
Compatibility:
New in Redis version: 6.2.0
- zincrby(key: KeyT, member: ValueT, increment: int) CommandRequest[float]¶
Increment the score of a member in the sorted set (creates the member with score 0 if missing).
- Parameters:
- Returns:
The new score of the member.
Redis command documentation: CommandName.ZINCRBY
- zinter(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the intersection of multiple sorted sets (aggregating scores by weights and aggregate rule).
- Parameters:
- Returns:
Members (and optionally scores) in the intersection.
Redis command documentation: CommandName.ZINTER
Compatibility:
New in Redis version: 6.2.0
- zintercard(keys: Parameters[KeyT], limit: int | None = None) CommandRequest[int]¶
Return the cardinality of the intersection of multiple sorted sets.
- Parameters:
- Returns:
The number of elements in the resulting intersection.
Redis command documentation: CommandName.ZINTERCARD
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- zinterstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.MAX, PureToken.MIN, PureToken.SUM] | None = None) CommandRequest[int]¶
Compute sorted set intersection and store the result in destination.
- Parameters:
- Returns:
The number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZINTERSTORE
- zlexcount(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Return the number of members in the sorted set between min and max (lexicographic order).
- Parameters:
- Returns:
The number of members in the range.
Redis command documentation: CommandName.ZLEXCOUNT
Hint
Supports client side caching
- zmpop(keys: Parameters[KeyT], where: Literal[PureToken.MAX, PureToken.MIN], count: int | None = None) CommandRequest[tuple[AnyStr, tuple[ScoredMember, ...]] | None]¶
Pop members with lowest or highest scores from the first non-empty sorted set.
- Parameters:
- Returns:
Noneif all sets are empty; otherwise (key_name, [(member, score), …]).
Redis command documentation: CommandName.ZMPOP
Compatibility:
New in Redis version: 7.0.0
Added in version 3.0.0.
- zmscore(key: KeyT, members: Parameters[ValueT]) CommandRequest[tuple[float | None, ...]]¶
Return the scores associated with the given members in the sorted set.
- Parameters:
- Returns:
A tuple of scores in the same order as members;
Nonefor missing members.
Redis command documentation: CommandName.ZMSCORE
Compatibility:
New in Redis version: 6.2.0
Hint
Supports client side caching
- zpopmax(key: KeyT, count: int | None = None) CommandRequest[ScoredMember | tuple[ScoredMember, ...] | None]¶
Remove and return the member(s) with the highest scores in the sorted set.
- Parameters:
- Returns:
A single (member, score) pair, or a tuple of pairs if count is set;
Noneif key is empty.
Redis command documentation: CommandName.ZPOPMAX
- zpopmin(key: KeyT, count: int | None = None) CommandRequest[ScoredMember | tuple[ScoredMember, ...] | None]¶
Remove and return members with the lowest scores in a sorted set
- Returns:
popped elements and scores.
Redis command documentation: CommandName.ZPOPMIN
- zrandmember(key: KeyT, count: int | None = None, withscores: bool | None = None) CommandRequest[AnyStr | tuple[AnyStr, ...] | tuple[ScoredMember, ...] | None]¶
Return one or more random members from the sorted set (without removing).
- Parameters:
- Returns:
A single member, a tuple of members, or (member, score) tuples;
Noneor empty if key is empty.
Redis command documentation: CommandName.ZRANDMEMBER
Compatibility:
New in Redis version: 6.2.0
- 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) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in the sorted set by rank, score, or lexicographic order.
- Parameters:
key¶ – The key name.
min_¶ – Minimum rank, score, or lex (depending on sortby).
max_¶ – Maximum rank, score, or lex (depending on sortby).
sortby¶ – BYSCORE or BYLEX.
rev¶ – If
True, reverse the order (high to low).offset¶ – Skip this many elements (use with count).
count¶ – Return this many elements (use with offset).
withscores¶ – If
True, include scores in the result.
- Returns:
Members (and optionally scores) in the specified range.
Redis command documentation: CommandName.ZRANGE
Compatibility:
sortby: New in Redis version: 6.2.0rev: New in Redis version: 6.2.0offset: New in Redis version: 6.2.0count: New in Redis version: 6.2.0
Hint
Supports client side caching
- zrangebylex(key: KeyT, min_: ValueT, max_: ValueT, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Return a range of members in a sorted set by lexicographical range.
- Parameters:
- Returns:
Tuple of members in the specified lex range.
Redis command documentation: CommandName.ZRANGEBYLEX
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the sortby=BYLEX argumentHint
Supports client side caching
- zrangebyscore(key: KeyT, min_: int | float, max_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in a sorted set by score.
- Parameters:
- Returns:
Tuple of members, or (member, score) tuples if withscores.
Redis command documentation: CommandName.ZRANGEBYSCORE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the sortby=BYSCORE argumentHint
Supports client side caching
- 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) CommandRequest[int]¶
Store a range of members from a sorted set into another key.
- Parameters:
dst¶ – Destination key for the stored range.
src¶ – Source sorted set key.
min_¶ – Start of range (score or lex depending on sortby).
max_¶ – End of range (score or lex depending on sortby).
sortby¶ – BYSCORE or BYLEX.
rev¶ – If
True, reverse order.offset¶ – Skip this many members (use with count).
count¶ – Store at most this many members (use with offset).
- Returns:
Number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZRANGESTORE
Compatibility:
New in Redis version: 6.2.0
- zrank(key: KeyT, member: ValueT, withscore: bool | None = None) CommandRequest[int | tuple[int, float] | None]¶
Return the rank (index) of the member in the sorted set (lowest score has rank 0).
- Parameters:
- Returns:
The rank, or (rank, score) if withscore;
Noneif member is not in the set.
Redis command documentation: CommandName.ZRANK
Compatibility:
withscore: New in Redis version: 7.1.240
Hint
Supports client side caching
- zrem(key: KeyT, members: Parameters[ValueT]) CommandRequest[int]¶
Remove one or more members from the sorted set.
- Parameters:
- Returns:
The number of members that were removed.
Redis command documentation: CommandName.ZREM
- zremrangebylex(key: KeyT, min_: ValueT, max_: ValueT) CommandRequest[int]¶
Remove all members in the sorted set between min and max (lexicographic order).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYLEX
- zremrangebyrank(key: KeyT, start: int, stop: int) CommandRequest[int]¶
Remove all members in the sorted set with rank between start and stop (inclusive).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYRANK
- zremrangebyscore(key: KeyT, min_: int | float, max_: int | float) CommandRequest[int]¶
Remove all members in the sorted set with scores between min and max (inclusive).
- Parameters:
- Returns:
The number of members removed.
Redis command documentation: CommandName.ZREMRANGEBYSCORE
- zrevrange(key: KeyT, start: int, stop: int, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members by index, highest scores first.
- Parameters:
- Returns:
Members (and optionally scores) in the specified range.
Redis command documentation: CommandName.ZREVRANGE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev argumentHint
Supports client side caching
- zrevrangebylex(key: KeyT, max_: ValueT, min_: ValueT, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr, ...]]¶
Return a range of members in a sorted set by lexicographical range, high to low.
- Parameters:
- Returns:
Tuple of members in the specified lex range.
Redis command documentation: CommandName.ZREVRANGEBYLEX
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev and sort=BYLEX argumentsHint
Supports client side caching
- zrevrangebyscore(key: KeyT, max_: int | float, min_: int | float, withscores: bool | None = None, offset: int | None = None, count: int | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return a range of members in a sorted set by score, high to low.
- Parameters:
- Returns:
Tuple of members, or (member, score) tuples if withscores.
Redis command documentation: CommandName.ZREVRANGEBYSCORE
Caution
Deprecated in Redis version: 6.2.0 Use
zrange()with the rev and sort=BYSCORE argumentsHint
Supports client side caching
- zrevrank(key: KeyT, member: ValueT, withscore: bool | None = None) CommandRequest[int | tuple[int, float] | None]¶
Return the rank of the member when the set is ordered high to low.
- Parameters:
- Returns:
The rank, or (rank, score) if withscore;
Noneif member is not in the set.
Redis command documentation: CommandName.ZREVRANK
Compatibility:
withscore: New in Redis version: 7.1.240
Hint
Supports client side caching
- zscan(key: KeyT, cursor: int | None = 0, match: StringT | None = None, count: int | None = None) CommandRequest[tuple[int, tuple[ScoredMember, ...]]]¶
Incrementally iterate over members and scores in the sorted set using a cursor.
- Parameters:
- Returns:
A tuple of (next_cursor, (member, score), …); next_cursor 0 means done.
Redis command documentation: CommandName.ZSCAN
- 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.
- zscore(key: KeyT, member: ValueT) CommandRequest[float | None]¶
Return the score associated with the member in the sorted set.
- Parameters:
- Returns:
The score, or
Noneif the member is not in the set.
Redis command documentation: CommandName.ZSCORE
Hint
Supports client side caching
- zunion(keys: Parameters[KeyT], weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None, withscores: bool | None = None) CommandRequest[tuple[AnyStr | ScoredMember, ...]]¶
Return the union of multiple sorted sets (aggregating scores by weights and aggregate rule).
- Parameters:
- Returns:
Members (and optionally scores) in the union.
Redis command documentation: CommandName.ZUNION
Compatibility:
New in Redis version: 6.2.0
- zunionstore(keys: Parameters[KeyT], destination: KeyT, weights: Parameters[int] | None = None, aggregate: Literal[PureToken.SUM, PureToken.MIN, PureToken.MAX] | None = None) CommandRequest[int]¶
Compute the union of sorted sets and store the result at destination.
- Parameters:
- Returns:
Number of elements in the resulting sorted set.
Redis command documentation: CommandName.ZUNIONSTORE
- pubsub(*, channels: Parameters[StringT] | None = None, channel_handlers: Mapping[StringT, SubscriptionCallback] | None = None, patterns: Parameters[StringT] | None = None, pattern_handlers: Mapping[StringT, SubscriptionCallback] | None = None, ignore_subscribe_messages: bool = False, retry_policy: RetryPolicy | None = CompositeRetryPolicy(ExponentialBackoffRetryPolicy((ConnectionError,), retries=None, base_delay=0.1, max_delay=16, jitter=True), ConstantRetryPolicy((TimeoutError,), retries=2, delay=0.1)), subscription_timeout: float = 1, max_idle_seconds: float = 15) ClusterPubSub[AnyStr][source]¶
Return a Pub/Sub instance that can be used to consume messages that get published to the subscribed channels or patterns.
- Parameters:
channels¶ – channels that the constructed Pubsub instance should automatically subscribe to
channel_handlers¶ – Mapping of channels to automatically subscribe to and the associated handlers that will be invoked when a message is received on the specific channel.
patterns¶ – patterns that the constructed Pubsub instance should automatically subscribe to
pattern_handlers¶ – Mapping of patterns to automatically subscribe to and the associated handlers that will be invoked when a message is received on channel matching the pattern.
ignore_subscribe_messages¶ – Whether to skip subscription acknowledgement messages
retry_policy¶ – An explicit retry policy to use in the subscriber.
subscription_timeout¶ – Maximum amount of time in seconds to wait for acknowledgement of subscriptions.
max_idle_seconds¶ – Maximum duration (in seconds) to tolerate no messages from the cluster before performing a keepalive check with a
PING.
Changed in version 6.0.0: All arguments are now keyword only
- sharded_pubsub(*, channels: Parameters[StringT] | None = None, channel_handlers: Mapping[StringT, SubscriptionCallback] | None = None, ignore_subscribe_messages: bool = False, read_from_replicas: bool = False, retry_policy: RetryPolicy | None = CompositeRetryPolicy(ExponentialBackoffRetryPolicy((ConnectionError,), retries=None, base_delay=0.1, max_delay=16, jitter=True), ConstantRetryPolicy((TimeoutError,), retries=2, delay=0.1)), subscription_timeout: float = 1, max_idle_seconds: float = 15) ShardedPubSub[AnyStr][source]¶
Return a Pub/Sub instance that can be used to consume messages from the subscribed channels in a redis cluster.
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:
channels¶ – channels that the constructed Pubsub instance should automatically subscribe to
channel_handlers¶ – Mapping of channels to automatically subscribe to and the associated handlers that will be invoked when a message is received on the specific channel.
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.
subscription_timeout¶ – Maximum amount of time in seconds to wait for acknowledgement of subscriptions.
max_idle_seconds¶ – Maximum duration (in seconds) to tolerate no messages from the cluster before performing a keepalive check with a
PING.
New in Redis version: 7.0.0
Changed in version 6.0.0: All arguments are now keyword only
Added in version 3.6.0.
- pipeline(transaction: bool = False, *, raise_on_error: bool = True, timeout: float | None = None) coredis.patterns.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.
raise_on_error¶ – Whether to raise errors upon executing the pipeline. If set to False errors will be accumulated and retrievable from the individual commands that had errors.
watches¶ – If
transactionis True these keys are watched for external changes during the transaction.timeout¶ – If specified this value will take precedence over
RedisCluster.stream_timeout
- lock(name: StringT, timeout: float | None = None, sleep: float = 0.1, blocking: bool = True, blocking_timeout: float | None = None) Lock[AnyStr][source]¶
Return a lock instance which can be used to guard resource access across multiple clients.
- Parameters:
name¶ – key for the lock
timeout¶ – indicates a maximum life for the lock. By default, it will remain locked until
release()is called.sleep¶ – indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.
blocking¶ – indicates whether calling
acquire()should block until the lock has been acquired or to fail immediately, causingacquire()to returnFalseand the lock not being acquired. Defaults toTrue.blocking_timeout¶ – indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of
Noneindicates continue trying forever.
- xconsumer(streams: Parameters[KeyT], *, buffer_size: int = 0, timeout: int | None = None, group: Literal[None] = None, consumer: Literal[None] = None, auto_create: bool = True, auto_acknowledge: bool = False, start_from_backlog: bool = False, **stream_parameters: StreamParameters) Consumer[AnyStr][source]¶
- xconsumer(streams: Parameters[KeyT], *, buffer_size: int = 0, timeout: int | None = None, group: StringT = None, consumer: StringT = None, auto_create: bool = True, auto_acknowledge: bool = False, start_from_backlog: bool = False, **stream_parameters: StreamParameters) GroupConsumer[AnyStr]
Create a stream consumer for one or more Redis streams.
Depending on whether
groupandconsumerare provided, this method creates either a standalone stream consumer or a member of a stream consumer group.If
groupandconsumerare not provided, a standalone stream consumer is created that starts reading from the latest entry of each stream provided instreams.The latest entry is determined by calling
xinfo_stream()and using thelast-entryattribute at the point of initializing the consumer instance or on first fetch (whichever comes first). If the stream(s) do not exist at the time of consumer creation, the consumer will simply start from the minimum identifier (0-0).If
groupandconsumerare provided, a member of a stream consumer group is created. The consumer has an identical interface ascoredis.patterns.streams.Consumer.- Parameters:
streams¶ – the stream identifiers to consume from
buffer_size¶ – Size of buffer (per stream) to maintain. This translates to the maximum number of stream entries that are fetched on each request to redis.
timeout¶ – Maximum amount of time in milliseconds to block for new entries to appear on the streams the consumer is reading from.
group¶ – The name of the group this consumer is part of
auto_create¶ – If True the group will be created upon initialization or first fetch if it doesn’t already exist.
auto_acknowledge¶ – If
Truethe stream entries fetched will be fetched without needing to be acknowledged withxack()to remove them from the pending entries list.start_from_backlog¶ – If
Truethe consumer will start by fetching any pending entries from the pending entry list before considering any new messages not seen by any other consumer in thegroupstream_parameters¶ –
Mapping of optional parameters to use by stream for the streams provided in
streams.Warning
Providing an
identifierinstream_parametershas a different meaning for a group consumer. If the value is any valid identifier other than>the consumer will only access the history of pending messages. That is, the set of messages that were delivered to this consumer (identified byconsumer) and never acknowledged.
Added in version 6.0.0.
- class Sentinel(sentinels: Iterable[TCPLocation | tuple[str, int]], min_other_sentinels: int = ..., sentinel_kwargs: dict[str, Any] | None = ..., decode_responses: Literal[False] = ..., cache: AbstractCache | None = None, type_adapter: TypeAdapter | None = ..., retry_policy: RetryPolicy = ..., **connection_kwargs: Any)[source]¶
- class Sentinel(sentinels: Iterable[TCPLocation | tuple[str, int]], min_other_sentinels: int = ..., sentinel_kwargs: dict[str, Any] | None = ..., decode_responses: Literal[True] = ..., cache: AbstractCache | None = None, type_adapter: TypeAdapter | None = None, retry_policy: RetryPolicy = ..., **connection_kwargs: Any)
Example use:
from coredis import Sentinel from coredis.connection import TCPLocation async def test(): async with Sentinel([TCPLocation('localhost', 26379)], stream_timeout=0.1) as sentinel: primary = sentinel.primary_for('my-instance', stream_timeout=0.1) replica = sentinel.replica_for('my-instance', stream_timeout=0.1) async with primary, replica: await primary.set('foo', 'bar') await replica.get('foo')
- Changes
Added in version 3.10.0: Accept
cacheparameter 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_kwargsis not specified,stream_timeout,socket_keepaliveanddecode_responsesoptions specified inconnection_kwargswill be used.cache¶ – If provided the cache will be shared between both primaries and replicas returned by this sentinel.
type_adapter¶ – The adapter to use for serializing / deserializing customs types when interacting with redis commands. If provided this adapter will be used for both primaries and replicas returned by this sentinel.
retry_policy¶ – The retry policy to use when interacting with the the primary and replica instances.
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
Redisfor all primary and replicas).
- async discover_primary(service_name: str) tuple[str, int][source]¶
Asks sentinel servers for the Redis primary’s location corresponding to the service labeled
service_name.- Returns:
A pair (location, port) or raises
PrimaryNotFoundErrorif 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: type[Redis[bytes]] = Redis[Any], connection_pool_class: type[SentinelConnectionPool] = SentinelConnectionPool, **kwargs: Any) Redis[bytes][source]¶
- primary_for(service_name: str, *, redis_class: type[Redis[str]] = Redis[Any], connection_pool_class: type[SentinelConnectionPool] = SentinelConnectionPool, **kwargs: Any) Redis[str]
Returns a redis client instance for the
service_nameprimary.A
coredis.sentinel.SentinelConnectionPoolclass is used to retrive the primary’s location before establishing a new connection.NOTE: If the primary’s location has changed, any cached connections to the old primary are closed.
By default clients will be a
Redisinstances. Specify a different class to theredis_classargument if you desire something different.The
connection_pool_classspecifies the connection pool to use. TheSentinelConnectionPoolwill be used by default.All other keyword arguments are merged with any
Sentinel.connection_kwargspassed 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: type[Redis[bytes]] = Redis[Any], connection_pool_class: type[SentinelConnectionPool] = SentinelConnectionPool, **kwargs: Any) Redis[bytes][source]¶
- replica_for(service_name: str, redis_class: type[Redis[str]] = Redis[Any], connection_pool_class: type[SentinelConnectionPool] = SentinelConnectionPool, **kwargs: Any) Redis[str]
Returns redis client instance for the
service_namereplica(s).A SentinelConnectionPool class is used to retrieve the replica’s location before establishing a new connection.
By default clients will be a redis.Redis instance. Specify a different class to the
redis_classargument if you desire something different.The
connection_pool_classspecifies the connection pool to use. The SentinelConnectionPool will be used by default.All other keyword arguments are merged with any
Sentinel.connection_kwargspassed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.