Managing Keys and Expiration
1. Checking Key Existence
| Command | Returns |
EXISTS key [key ...] | Count of existing keys (duplicates counted) |
TYPE key | none if missing |
2. Deleting Keys
| Command | Behavior |
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
| Return | Meaning |
string | String / number / binary |
list | Linked list (quicklist) |
set | Unordered unique set |
zset | Sorted set |
hash | Field/value map |
stream | Append-only log |
ReJSON-RL | JSON document (module) |
4. Renaming Keys
| Command | Behavior |
RENAME src dst | Overwrites dst; error if src missing |
RENAMENX src dst | Only if dst does not exist |
5. Setting Key Expiration
| Command | Unit | Options |
EXPIRE key seconds [NX|XX|GT|LT] | seconds | NX=only if no TTL, XX=only if TTL exists, GT/LT compare |
EXPIREAT key unix-ts | absolute | Same flags |
EXPIRETIME key | seconds | Absolute expiry timestamp |
6. Setting Millisecond Expiration
PEXPIRE key 1500
PEXPIREAT key 1735689600000
PEXPIRETIME key
| Command | Resolution |
PEXPIRE | Millisecond TTL |
PEXPIREAT | Absolute ms timestamp |
7. Removing Expiration
| Command | Returns |
PERSIST key | 1 on success, 0 if no TTL or key missing |
8. Getting Time to Live
| Command | Returns |
TTL key | Seconds; -1 no TTL, -2 missing |
PTTL key | Milliseconds |
9. Finding Keys by Pattern
| Command | Use |
KEYS pattern | Glob match; O(N) AVOID PROD |
SCAN cursor MATCH p COUNT n TYPE t | Incremental, production safe |
Example: Safe pattern scan
redis-cli --scan --pattern "session:*" --count 1000 | xargs redis-cli UNLINK
10. Getting Random Key
| Command | Description |
RANDOMKEY | Returns a random key from current DB or nil |
11. Copying Keys
| Command | Options |
COPY src dst [DB n] [REPLACE] | Deep copy; preserves TTL; cross-DB supported 6.2+ |
12. Touching Keys
| Command | Effect |
TOUCH key [key ...] | Updates last-access time (affects LRU/LFU) without reading value |
OBJECT IDLETIME key | Read idle time without resetting it |
13. Dumping and Restoring Keys
| Command | Description |
DUMP key | Serialize 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 |