TExcelTAD
Home › Redis › Redis Key Management

Redis Key Management

So far we have created keys. This lesson covers the commands that work on keys whatever their type: checking that they exist, deleting and renaming them, finding out their type, and listing them safely in a large database.

EXISTS and DEL

EXISTS returns how many of the given keys exist. DEL deletes keys and returns how many it actually removed. Both accept several keys at once.

redis · try it yourself
SET user:1 Ada
SET user:2 Linus
EXISTS user:1
EXISTS user:1 user:2 user:3
DEL user:1 user:3
EXISTS user:1
redis> SET user:1 Ada
OK
redis> SET user:2 Linus
OK
redis> EXISTS user:1
(integer) 1
redis> EXISTS user:1 user:2 user:3
(integer) 2
redis> DEL user:1 user:3
(integer) 1
redis> EXISTS user:1
(integer) 0

If you pass the same key twice to EXISTS, it is counted twice. DEL of a missing key is not an error; it simply counts as 0.

Tip: Deleting a huge collection with DEL can block the server for a moment while the memory is freed. UNLINK has the same reply but frees the memory in a background thread. Prefer UNLINK for big keys.

TYPE

TYPE tells you what kind of value a key holds, or none if it does not exist. Commands for one type refuse keys of another type with a WRONGTYPE error:

redis · try it yourself
SET counter 10
RPUSH queue job1 job2
SADD tags redis nosql
HSET user:7 name Grace
ZADD board 50 ada
TYPE counter
TYPE queue
TYPE tags
TYPE user:7
TYPE board
TYPE nothing
LPUSH counter 1
redis> SET counter 10
OK
redis> RPUSH queue job1 job2
(integer) 2
redis> SADD tags redis nosql
(integer) 2
redis> HSET user:7 name Grace
(integer) 1
redis> ZADD board 50 ada
(integer) 1
redis> TYPE counter
string
redis> TYPE queue
list
redis> TYPE tags
set
redis> TYPE user:7
hash
redis> TYPE board
zset
redis> TYPE nothing
none
redis> LPUSH counter 1
(error) WRONGTYPE Operation against a key holding the wrong kind of value

RENAME and COPY

RENAME moves a value to a new key name, overwriting the target if it exists. RENAMENX only renames when the new name is free. COPY duplicates a value (add REPLACE to overwrite an existing destination).

redis · try it yourself
SET draft:1 "Hello"
SET post:1 "Old post"
RENAMENX draft:1 post:1
RENAME draft:1 post:1
GET post:1
EXISTS draft:1
COPY post:1 backup:post:1
GET backup:post:1
RENAME missing whatever
redis> SET draft:1 "Hello"
OK
redis> SET post:1 "Old post"
OK
redis> RENAMENX draft:1 post:1
(integer) 0
redis> RENAME draft:1 post:1
OK
redis> GET post:1
"Hello"
redis> EXISTS draft:1
(integer) 0
redis> COPY post:1 backup:post:1
(integer) 1
redis> GET backup:post:1
"Hello"
redis> RENAME missing whatever
(error) ERR no such key

Finding keys: KEYS versus SCAN

KEYS pattern returns every key matching a glob-style pattern (* any characters, ? one character, [abc] a set). It is convenient on a tiny development database, but on a production server with millions of keys it scans everything in one go and blocks all other clients until it finishes.

SCAN walks the keyspace incrementally. Each call returns a cursor and a batch of keys; you pass the cursor to the next call and stop when it comes back as 0. MATCH filters by pattern and COUNT hints how much work to do per call.

redis · try it yourself
MSET user:1 Ada user:2 Linus user:3 Grace order:1 x
HSET product:9 name Mug
KEYS order:*
KEYS prod*
SCAN 0 MATCH order:* COUNT 100
SCAN 0 TYPE hash COUNT 100
DBSIZE
redis> MSET user:1 Ada user:2 Linus user:3 Grace order:1 x
OK
redis> HSET product:9 name Mug
(integer) 1
redis> KEYS order:*
1) "order:1"
redis> KEYS prod*
1) "product:9"
redis> SCAN 0 MATCH order:* COUNT 100
1) "0"
2) 1) "order:1"
redis> SCAN 0 TYPE hash COUNT 100
1) "0"
2) 1) "product:9"
redis> DBSIZE
(integer) 5

The examples here match one key each on purpose: when several keys match, the order in which KEYS and SCAN return them depends on the server's internal hash table and changes from one server start to the next. On this small database a single SCAN call covers everything, so the cursor that comes back is already 0.

On a large database you would loop until the cursor returns to 0:

python
# redis-py: iterate over all user keys without blocking the server
for key in r.scan_iter(match="user:*", count=500):
    print(key)

Things to know about SCAN:

Fact Consequence
The order of keys is not sorted Do not rely on it; sort in your program if needed
A key may be returned more than once Deduplicate if it matters
COUNT is a hint, not a limit A call can return more or fewer keys
Keys added during the scan may or may not appear Keys present for the whole scan always appear

The collection types have their own cursors: SSCAN for sets, HSCAN for hashes and ZSCAN for sorted sets.

Inspecting a key

OBJECT ENCODING shows how Redis stores a value internally, and MEMORY USAGE estimates its size in bytes. They are useful when tuning memory (see the Memory lesson):

redis · try it yourself
SET small 42
SET word hello
RPUSH short:list a b c
OBJECT ENCODING small
OBJECT ENCODING word
OBJECT ENCODING short:list
redis> SET small 42
OK
redis> SET word hello
OK
redis> RPUSH short:list a b c
(integer) 3
redis> OBJECT ENCODING small
"int"
redis> OBJECT ENCODING word
"embstr"
redis> OBJECT ENCODING short:list
"listpack"

Small integers use the int encoding, short strings are embstr (the string is stored in the same memory block as its header), and small lists, hashes and sets are packed into a listpack. Redis converts to bigger, faster structures automatically when a value grows.

Clearing a database

FLUSHDB deletes every key in the current database and FLUSHALL deletes every key in every database. They are great for tests and dangerous anywhere else; production servers often disable them with ACLs or rename-command.

redis · try it yourself
MSET a 1 b 2 c 3
DBSIZE
FLUSHDB
DBSIZE
redis> MSET a 1 b 2 c 3
OK
redis> DBSIZE
(integer) 3
redis> FLUSHDB
OK
redis> DBSIZE
(integer) 0

Test yourself

Which command should you use to list matching keys on a busy production server?

  1. KEYS *
  2. SCAN with MATCH
  3. FLUSHDB
  4. TYPE

When is a SCAN iteration finished?

  1. When a call returns no keys
  2. When the returned cursor is 0
  3. After COUNT keys
  4. After exactly 10 calls

What does TYPE return for a key that does not exist?

  1. (nil)
  2. none
  3. string
  4. (error)