Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

2.

Keys

Sec. Behavior Practice and Study

Find keys matching a particular pattern (for instance, all keys starting with
"stats:user:") without potentially blocking the server for an unreasonable amount of
time. Know that KEYS should never be used in production for two reasons:
https://redis.io/
It can block the server for a long time, particularly when the keyspace is large. commands/keys
The response buffer that it builds can exhaust the server's memory. To avoid these
problems, use SCAN instead. https://redis.io/
2.1 commands/scan
Understand that both the KEYS and SCAN commands are O(N). However, KEYS
scans the entire key space before returning. SCAN looks at only a small portion of https://redis.io/
the keyspace on each call. If you just need to see how many keys are in the commands/info
database, using the INFO command:

INFO keyspace

Delete a single key both synchronously and asynchronously. DEL and UNLINK
https://redis.io/
both remove a key from the keyspace. With DEL, the memory taken up by the key commands/del
and its associated value is freed synchronously with the request. With UNLINK, the
2.2 memory is freed asynchronously, after the request completes. Thus, UNLINK
https://redis.io/
confers a slight performance advantage. Ensure that you know how to efficiently
commands/unlink
delete a large number of keys matching a specific pattern.

https://redis.io/
2.3 Check to see if a given key exists. commands/exists

Know how to set a time-to-live on a key. Know how to check the time-to-live on a
key. Know how to remove the TTL on a key. Note the following behavior of TTL:
2.4
The command returns -2 if the key does not exist.
The command returns -1 if the key exists but has no associated expire.
Otherwise, the command returns the time-to-live in seconds.

https://redis.io/
2.5 Understand how to remove all keys from a database. commands/flushdb

Understand which key names are valid. Know that keys support any binary
sequence, including an empty string. All of the following are valid keys:

😁
""
2.6
"!"
The literal text of the complete works of Shakespeare (Approximately 5.5 MB
uncompressed)

One implication of this is that keys are case-sensitive. The keys "Z" and "z" are
different.
KEYS pattern Available since 1.0.0.
Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key
names in the database and the given pattern have limited length. Returns all keys matching pattern.
While the time complexity for this operation is O(N), the constant times are fairly low. For example, Redis
running on an entry level laptop can scan a 1 million key database in 40 milliseconds.
Warning: consider KEYS as a command that should only be used in production environments with extreme care.
It may ruin performance when it is executed against large databases. This command is intended for debugging
and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application
code. If you're looking for a way to find keys in a subset of your keyspace, consider using SCAN or sets.
Supported glob-style patterns:
h?llo matches hello, hallo and hxllo
h*llo matches hllo and heeeello
h[ae]llo matches hello and hallo, but not hillo
h[^e]llo matches hallo, hbllo, ... but not hello
h[a-b]llo matches hallo and hbllo
Use \ to escape special characters if you want to match them verbatim.
Return value Array reply: list of keys matching pattern.
Examples
redis> MSET firstname Jack lastname Stuntman age 35
"OK"
redis> KEYS *name*
1) "firstname"
2) "lastname"
redis> KEYS a??
1) "age"
redis> KEYS *
1) "age"
2) "firstname"
3) "lastname"
redis>
DEL key [key …] Available since 1.0.0. Time complexity: O(N) where N is the number of keys that will be
removed. When a key to remove holds a value other than a string, the individual complexity for this key is O(M)
where M is the number of elements in the list, set, sorted set or hash. Removing a single key that holds a string
value is O(1).
Removes the specified keys. A key is ignored if it does not exist.
Return value Integer reply: The number of keys that were removed.
Examples
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> DEL key1 key2 key3
(integer) 2
redis>
UNLINK key [key …] Available since 4.0.0.
Time complexity: O(1) for each key removed regardless of its size. Then the command does O(N) work in a
different thread in order to reclaim memory, where N is the number of allocations the deleted objects where
composed of.
This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not
exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking,
while DEL is. This is where the command name comes from: the command just unlinks the keys from the
keyspace. The actual removal will happen later asynchronously.
Return value Integer reply: The number of keys that were unlinked.
Examples
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> UNLINK key1 key2 key3
(integer) 2
redis>
EXISTS key [key …] Available since 1.0.0.
Time complexity: O(N) where N is the number of keys to check.
Returns if key exists.
Since Redis 3.0.3 it is possible to specify multiple keys instead of a single one. In such a case, it returns the total
number of keys existing. Note that returning 1 or 0 for a single key is just a special case of the variadic usage, so
the command is completely backward compatible.
The user should be aware that if the same existing key is mentioned in the arguments multiple times, it will be
counted multiple times. So if somekey exists, EXISTS somekey somekey will return 2.
Return value Integer reply, specifically:
1 if the key exists.
0 if the key does not exist.
Since Redis 3.0.3 the command accepts a variable number of keys and the return value is generalized:
The number of keys existing among the ones specified as arguments. Keys mentioned multiple times and
existing are counted multiple times.
Examples
redis> SET key1 "Hello"
"OK"
redis> EXISTS key1
(integer) 1
redis> EXISTS nosuchkey
(integer) 0
redis> SET key2 "World"
"OK"
redis> EXISTS key1 key2 nosuchkey
(integer) 2
redis>
FLUSHDB [ASYNC|SYNC] Available since 1.0.0.
Time complexity: O(N) where N is the number of keys in the selected database
Delete all the keys of the currently selected DB. This command never fails.
By default, FLUSHDB will synchronously flush all keys from the database. Starting with Redis 6.2, setting the
lazyfree-lazy-user-flush configuration directive to "yes" changes the default flush mode to asynchronous.
It is possible to use one of the following modifiers to dictate the flushing mode explicitly:
ASYNC: flushes the database asynchronously
SYNC: flushes the database synchronously
Note: an asynchronous FLUSHDB command only deletes keys that were present at the time the command was
invoked. Keys created during an asynchronous flush will be unaffected.
Return value Simple string reply
INFO [section] Available since 1.0.0.
The INFO command returns information and statistics about the server in a format that is simple to parse by
computers and easy to read by humans.
The optional parameter can be used to select a specific section of information:
server: General information about the Redis server
clients: Client connections section
memory: Memory consumption related information
persistence: RDB and AOF related information
stats: General statistics
replication: Master/replica replication information
cpu: CPU consumption statistics
commandstats: Redis command statistics
cluster: Redis Cluster section
modules: Modules section
keyspace: Database related statistics
modules: Module related sections
errorstats: Redis error statistics
It can also take the following values:
all: Return all sections (excluding module generated ones)
default: Return only the default set of sections
everything: Includes all and modules
When no parameter is provided, the default option is assumed.
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] Available since 2.8.0.
Time complexity: O(1) for every call. O(N) for a complete iteration, including enough command calls for the
cursor to return back to 0. N is the number of elements inside the collection.
The SCAN command and the closely related commands SSCAN, HSCAN and ZSCAN are used in order to
incrementally iterate over a collection of elements.
SCAN iterates the set of keys in the currently selected Redis database.
SSCAN iterates elements of Sets types.
HSCAN iterates fields of Hash types and their associated values.
ZSCAN iterates elements of Sorted Set types and their associated scores.
Since these commands allow for incremental iteration, returning only a small number of elements per call, they
can be used in production without the downside of commands like KEYS or SMEMBERS that may block the
server for a long time (even several seconds) when called against big collections of keys or elements.
However while blocking commands like SMEMBERS are able to provide all the elements that are part of a Set
in a given moment, The SCAN family of commands only offer limited guarantees about the returned elements
since the collection that we incrementally iterate can change during the iteration process.
Note that SCAN, SSCAN, HSCAN and ZSCAN all work very similarly, so this documentation covers all the
four commands. However an obvious difference is that in the case of SSCAN, HSCAN and ZSCAN the first
argument is the name of the key holding the Set, Hash or Sorted Set value. The SCAN command does not need
any key name argument as it iterates keys in the current database, so the iterated object is the database itself.
SCAN basic usage
SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated
cursor that the user needs to use as the cursor argument in the next call.
An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0. The
following is an example of SCAN iteration:
redis 127.0.0.1:6379> scan 0
1) "17"
2) 1) "key:12"
2) "key:8"
3) "key:4"
4) "key:14"
...
9) "key:3"
10) "key:7"
11) "key:1"
redis 127.0.0.1:6379> scan 17
1) "0"
2) 1) "key:5"
2) "key:18"
3) "key:0"
4) "key:2"
5) "key:19"
6) "key:13"
7) "key:6"
8) "key:9"
9) "key:11"
In the example above, the first call uses zero as a cursor, to start the iteration. The second call uses the cursor
returned by the previous call as the first element of the reply, that is, 17.
As you can see the SCAN return value is an array of two values: the first value is the new cursor to use in the
next call, the second value is an array of elements.
Since in the second call the returned cursor is 0, the server signaled to the caller that the iteration finished, and
the collection was completely explored. Starting an iteration with a cursor value of 0, and calling SCAN until the
returned cursor is 0 again is called a full iteration.
The COUNT option
While SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible
to empirically adjust the behavior of SCAN using the COUNT option. Basically with COUNT the user specified
the amount of work that should be done at every call in order to retrieve elements from the collection. This is just
a hint for the implementation, however generally speaking this is what you could expect most of the times from
the implementation.
The default COUNT value is 10.
When iterating the key space, or a Set, Hash or Sorted Set that is big enough to be represented by a hash table,
assuming no MATCH option is used, the server will usually return count or a bit more than count elements per
call. Please check the why SCAN may return all the elements at once section later in this document.
When iterating Sets encoded as intsets (small sets composed of just integers), or Hashes and Sorted Sets
encoded as ziplists (small hashes and sets composed of small individual values), usually all the elements are
returned in the first SCAN call regardless of the COUNT value.
Important: there is no need to use the same COUNT value for every iteration. The caller is free to change the
count from one iteration to the other as required, as long as the cursor passed in the next call is the one obtained
in the previous call to the command.
The MATCH option
It is possible to only iterate elements matching a given glob-style pattern, similarly to the behavior of the KEYS
command that takes a pattern as only argument.
To do so, just append the MATCH <pattern> arguments at the end of the SCAN command (it works with all the
SCAN family commands).
The TYPE option

As of version 6.0 you can use this option to ask SCAN to only return objects that match a given type,
allowing you to iterate through the database looking for keys of a specific type. The TYPE option is
only available on the whole-database SCAN, not HSCAN or ZSCAN etc.
The type argument is the same string name that the TYPE command returns. Note a quirk where
some Redis types, such as GeoHashes, HyperLogLogs, Bitmaps, and Bitfields, may internally be
implemented using other Redis types, such as a string or zset, so can't be distinguished from other keys
of that same type by SCAN.

You might also like