Sign In
Sign In

How to Manage Redis Keys and Databases

How to Manage Redis Keys and Databases
Hostman Team
Technical writer
Redis
06.11.2024
Reading time: 9 min

Redis is a NoSQL, open-source database management system that stores data in memory as key-value pairs, where each key is a unique identifier for its associated values. A single Redis instance can host multiple databases, each capable of storing various data types.

Advantages of Redis

  • High processing speed: It can handle up to 110,000 SET and 81,000 GET operations per second.
  • Support for advanced data types: Besides strings, Redis databases can include lists, sets (including sorted sets), and hashes.
  • Atomicity: Operations are atomic, so each client receives consistent data regardless of the number of simultaneous requests.
  • Versatility: Redis is effective for caching, message queuing, and storing short-term information (e.g., during web sessions).
  • Ease of setup and use: Redis’s simplicity makes it popular for development with Python, PHP, Java, and more.

In this article, we’ll cover some basic commands for managing keys and databases in Redis. Each example is independent and does not need to be executed in sequence, so they can be reviewed individually.

We’ll execute all commands on a server running Ubuntu 22.04 with Redis version 7.0.12, using the redis-cli utility. However, these commands are compatible with other interfaces (such as Redli) and with cloud-based Redis databases.

Redis Data Types

Before diving into commands, let's look at the data types Redis supports. Redis keys are binary-coded strings with a maximum length of 512 MB, serving as identifiers for the associated values.

String

Strings are simple byte sequences with no restrictions on special characters, so they can hold nearly any content: text, integers, floating-point numbers, images, videos, and other media files, with a maximum size of 512 MB.

Example:

redis 127.0.0.1:6379> SET name "educative
OK 
redis 127.0.0.1:6379> GET name 
"educative"

In this example, name is the key, and educative is the string value stored in the database.

List

Lists in Redis are ordered sequences of strings, sorted in insertion order. The system can efficiently handle lists with both small (500) and large (50,000) volumes of interconnected entries, making it ideal for processing large datasets.

Example of creating lists:

LPUSH mylist x   # list is now "x"
LPUSH mylist y   # list is now "y","x"
RPUSH mylist z   # list is now "y","x","z" (using RPUSH this time)

Set

Sets are similar to lists but unordered, and duplicates are not allowed. This storage method is useful when uniqueness is important but sequence order does not matter.

Sorted Set

Sorted sets allow users to choose the sorting criteria. If two elements have the same score, Redis will order them lexicographically. Each element is associated with a score, determining the set's ordering.

Hash

The hash data type stores field-value pairs. A Redis hash can contain millions of objects within a compact structure, making it suitable for use cases involving large numbers of entries or accounts in a single database.

Example usage:

HMSET user:1000 username antirez password P1pp0 age 34
HGETALL user:1000
HSET user:1000 password 12345
HGETALL user:1000

Managing Redis Databases

By default, Redis includes 16 isolated databases, each numbered from 0 to 15, with isolation ensuring that commands affect only the selected database, not others. By default, Redis connects to database 0. You can switch databases using the SELECT command after connecting. For instance, to switch to database 10:

select 10

The selected database will then be indicated in the console prompt like this:

127.0.0.1:6379[10]˃

If you’re working in the default database 0, the prompt won’t show a database number:

127.0.0.1:6379˃

Copying Data Between Databases

The swapdb command allows you to swap data between two databases, fully replacing the contents of the target database with those of the source database. For example, to swap databases 1 and 2:

swapdb 1 2

If the operation is successful, Redis will display OK. Changes are applied immediately.

Moving Keys Between Redis Instances

The migrate command transfers a key from one Redis instance to another, removing it from the source instance. This command includes the following parameters in order:

  1. The target database’s host or IP address

  2. The target database’s port number

  3. The name of the key to be transferred

  4. The target database number (0–15)

  5. A timeout in milliseconds (maximum idle time allowed)

For example:

migrate 123.45.4.134 6379 key_1 6 8000

You can add one of the following options to the end of the migrate command:

  • COPY: Retains the key in the source database while copying it to the target database.
  • REPLACE: If the key already exists in the target database, it will be overwritten by the migrating key.
  • KEYS: Instead of specifying a single key, you can provide a pattern after keys to transfer all matching keys, following patterns as outlined in the documentation. This enables bulk data transfers that match the specified pattern.

Managing Keys

Below are examples of several basic Redis commands for working with keys.

To rename a key, use rename:

rename old_key_name new_key_name

The randomkey command is used to return a random key from the database:

randomkey

The output will display the key.

The type command allows you to output the data type. The output will indicate one of the possible options: string, list, hash, set, zset, stream, or none — if such a key does not exist in the database.

type key_name

The move command transfers a key between databases within a single Redis instance (unlike migrate, which moves them to a different Redis instance). The command includes the key name and the target database file. For example, we will transfer data to database 6:

move key_name 6

Upon successful execution, the output will show OK.

Deleting Keys

To delete one or more keys, use del:

del key_name_1 key_name_2

If successful, the output will show (integer) 1. If something goes wrong, you will see (integer) 0.

The unlink command is functionally similar to del but has some nuances. del temporarily blocks the client to free the memory occupied by a key. If this takes very little time (in the case of a small object), the blocking will likely go unnoticed. However, if the key is associated with a large number of objects, the deletion will take a considerable amount of time. During that time, any other operations will be impossible.

Unlike del, the unlink command will first assess the cost of freeing the memory occupied by the key. If the costs are insignificant, unlink will behave like del, temporarily blocking the client. If the memory release requires significant resources, the deletion will occur asynchronously: unlink works in the background and gradually frees memory without blocking the client:

unlink key_name

In most cases, it is preferable to use unlink, as the ability to delete keys asynchronously and reduce errors due to blocking is a significant advantage.

One of the following commands — flushdb or flushall — is used for bulk deletion of keys. Be very careful; this procedure occurs with no possibility of recovery (applicable to one or several databases).

To delete all keys in the current database, use:

flushdb

To remove all keys across all databases on the Redis platform, use:

flushall

Both commands have an asynchronous deletion mode; add the async option to enable this. In this case, they will behave like unlink, gradually cleaning up memory in the background while other operations continue.

Backup

To create a backup of the current Redis database, you can use:

save

As a result, a snapshot of the current information is exported to a .rdb file.

It is important to note that save blocks all other clients accessing the database during its execution. Therefore, the official documentation recommends running the save command only in a testing environment.

Instead, it is suggested to use bgsave. This command informs Redis to create a fork of the database: the parent process will continue to serve clients, while the child process will unload the database backup. If changes are made during the execution of the bgsave command, they will not be included in the snapshot.

bgsave

You can also configure automatic regular snapshots that will occur when a certain number of changes have been made to the database. This creates a "save point." By default, the following settings for save points are specified in the redis.conf configuration file:

/etc/redis/redis.conf
...
save 900 1
save 300 10
save 60 10000
...
dbfilename "nextfile.rdb"
...

According to this configuration, Redis will dump a snapshot of the database to the file specified in the dbfilename line at intervals of 900 seconds if at least 1 key has changed; 300 seconds if 10 or more keys have changed; and every 60 seconds if 10,000 or more keys have changed.

Another command for creating a backup is shutdown. It will block every client connected to the database, perform a save, and close the connection. It is important to consider that this command will operate similarly to save, meaning:

  • A snapshot will be created only if a save point is configured.

  • During the blocking of clients while the shutdown command is executed, the necessary data may become unavailable to users or applications. It should be used only in a testing environment and when you are fully confident that you can safely block all server clients.

shutdown

If a save point is not configured but you want to create a snapshot, add save to the command:

shutdown save

You can also bypass creating a backup if a save point is configured, but you need to turn off the server without saving. For this, use:

shutdown nosave

Additionally, the shutdown command resets changes in the append-only file (the content does not change, and all new data is added to the end) before shutting down, if the AOF (Append Only File) function is enabled. This logs all write operations to the storage in a .aof file.

The AOF and RDB modes can be enabled simultaneously, and using both methods is an effective backup strategy. The append-only file will gradually grow significantly. It is recommended to enable file rewriting considering certain variables. These settings should be specified within the redis.conf file.

Another method for rewriting the append-only file is to execute the command:

bgrewriteaof

This will create a concise list of commands needed to roll back the database to its current state. bgrewriteaof operates in the background, but other background processes must be fully completed before it can be executed.

Redis
06.11.2024
Reading time: 9 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us