MOVE

Introduction and Use Case(s)

The MOVE command in Redis is used to transfer a key from the current database to a specified destination database. This is particularly useful for organizing data across different databases within the same Redis instance, allowing for separation of concerns or staged processing.

Typical use cases include:

  • Migrating keys between different databases for load balancing.
  • Staging data in intermediate databases before moving it to a production database.

Syntax

  1. MOVE key db

Parameter Explanations

  • key: The key to be moved. This must exist in the current database for the operation to succeed.
  • db: The target database number where the key should be moved. It must be an integer and refer to an existing Redis database.

Return Values

  • (integer) 1: Indicates that the key was successfully moved to the target database.
  • (integer) 0: Indicates failure, either because the key does not exist in the current database or it already exists in the target database.

Code Examples

  1. dragonfly> SET mykey "Hello"
  2. OK
  3. dragonfly> MOVE mykey 1
  4. (integer) 1
  5. dragonfly> EXISTS mykey
  6. (integer) 0
  7. dragonfly> SELECT 1
  8. OK
  9. dragonfly> EXISTS mykey
  10. (integer) 1
  11. dragonfly> GET mykey
  12. "Hello"
  13. dragonfly> MOVE mykey 0
  14. (integer) 1
  15. dragonfly> SELECT 0
  16. OK
  17. dragonfly> GET mykey
  18. "Hello"

Best Practices

  • Ensure that the target database is ready to receive the key to avoid accidentally overwriting data.
  • Regularly verify the existence of keys in both source and target databases after performing the move operation.

Common Mistakes

  • Attempting to move a non-existent key, which results in no action while returning (integer) 0.
  • Overwriting an existing key in the target database. The MOVE command will fail if the key already exists in the target database, so check for key existence beforehand if needed.

FAQs

What happens if the key already exists in the target database?

If the key already exists in the destination database, the MOVE command will not overwrite it and will return (integer) 0.

Can I move multiple keys at once using the MOVE command?

No, the MOVE command only supports moving one key at a time. To move multiple keys, you need to call the MOVE command separately for each key.