Managing Keys and Expiration

1. Checking Key Existence

CommandReturns
EXISTS key [key ...]Count of existing keys (duplicates counted)
TYPE keynone if missing

2. Deleting Keys

CommandBehavior
DEL key [key ...]Synchronous delete
UNLINK key [key ...]Non-blocking; reclaim memory async
Note: Prefer UNLINK for big aggregates (lists/sets/hashes > 1k elements).

3. Getting Key Type

ReturnMeaning
stringString / number / binary
listLinked list (quicklist)
setUnordered unique set
zsetSorted set
hashField/value map
streamAppend-only log
ReJSON-RLJSON document (module)

4. Renaming Keys

CommandBehavior
RENAME src dstOverwrites dst; error if src missing
RENAMENX src dstOnly if dst does not exist

5. Setting Key Expiration

CommandUnitOptions
EXPIRE key seconds [NX|XX|GT|LT]secondsNX=only if no TTL, XX=only if TTL exists, GT/LT compare
EXPIREAT key unix-tsabsoluteSame flags
EXPIRETIME keysecondsAbsolute expiry timestamp

6. Setting Millisecond Expiration

PEXPIRE key 1500
PEXPIREAT key 1735689600000
PEXPIRETIME key
CommandResolution
PEXPIREMillisecond TTL
PEXPIREATAbsolute ms timestamp

7. Removing Expiration

CommandReturns
PERSIST key1 on success, 0 if no TTL or key missing

8. Getting Time to Live

CommandReturns
TTL keySeconds; -1 no TTL, -2 missing
PTTL keyMilliseconds

9. Finding Keys by Pattern

CommandUse
KEYS patternGlob match; O(N) AVOID PROD
SCAN cursor MATCH p COUNT n TYPE tIncremental, production safe

Example: Safe pattern scan

redis-cli --scan --pattern "session:*" --count 1000 | xargs redis-cli UNLINK

10. Getting Random Key

CommandDescription
RANDOMKEYReturns a random key from current DB or nil

11. Copying Keys

CommandOptions
COPY src dst [DB n] [REPLACE]Deep copy; preserves TTL; cross-DB supported 6.2+

12. Touching Keys

CommandEffect
TOUCH key [key ...]Updates last-access time (affects LRU/LFU) without reading value
OBJECT IDLETIME keyRead idle time without resetting it

13. Dumping and Restoring Keys

CommandDescription
DUMP keySerialize value to binary blob
RESTORE key ttl serialized [REPLACE] [IDLETIME s] [FREQ n]Recreate from dump
MIGRATE host port key|"" db ms [COPY] [REPLACE] [KEYS k1 k2]Cross-instance move