Move a Key Between Databases with MOVE
In this step, you will learn how to move a key from one Redis database to another using the MOVE command. Redis supports multiple logical databases within a single instance. By default, there are 16 databases, numbered from 0 to 15. The MOVE command allows you to transfer a key from the currently selected database to another.
First, ensure you are connected to the Redis server using the Redis command-line interface (redis-cli). Open a terminal in your ~/project directory and type the following command:
redis-cli
You should see the Redis prompt: 127.0.0.1:6379>. By default, you are connected to database 0.
We already have a key named mykey with the value myvalue in database 0 from the previous step. Let's verify this:
GET mykey
You should see the output: "myvalue".
Now, let's move the key mykey from database 0 to database 1 using the MOVE command:
MOVE mykey 1
You should see the output: (integer) 1, which means the key was successfully moved.
To verify that the key has been moved, try to get the value of the key mykey in database 0:
GET mykey
You should see the output: (nil), which means the key no longer exists in database 0.
Now, switch to database 1 using the SELECT command:
SELECT 1
You should see the output: OK.
Now, try to get the value of the key mykey in database 1:
GET mykey
You should see the output: "myvalue", which confirms that the key has been successfully moved to database 1.
Finally, let's move the key mykey back to database 0 for the next steps. First, switch back to database 0:
SELECT 0
You should see the output: OK.
Now, move the key mykey from database 1 to database 0:
MOVE mykey 0
You should see the output: (error) ERR source and destination objects are the same.
This error occurs because you SELECT 0 and then MOVE mykey 0 in the same session. The MOVE command is not allowed to move a key to the same database it is currently in.
To move a key to a different database, you need to select the destination database first and then use the MOVE command.
For example, first select database 1:
SELECT 1
You should see the output: OK.
Now, move the key mykey from database 1 to database 0:
MOVE mykey 0
You should see the output: (integer) 1, which means the key was successfully moved.
Now, switch back to database 0:
SELECT 0
Verify the key is back in database 0:
GET mykey
You should see the output: "myvalue".
Remember to exit the redis-cli by typing exit or pressing Ctrl+D. This ensures that your commands are properly logged.
exit
You have now successfully moved a key between Redis databases using the MOVE command.