w3resource

Redis Keys: RENAMENX

Redis RENAMENX Command

Redis RENAMENX command is used to change the name of a key to newkey if the new key does not exist. It returns an error under the same conditions as RENAME.

Here are some common uses and scenarios for the "RENAMENX" command:

  • Safe Renaming: Rename a key atomically only if the new key name does not already exist.
  • Avoid Overwriting: Prevent accidental overwriting of existing keys during renaming.
  • Transactional Operations: Execute renaming operations safely in a multi-client environment.
  • Data Integrity: Ensure data integrity by avoiding unintended key replacements.

Syntax:

RENAMENX OLD_KEY_NAME NEW_KEY_NAME

Available since

1.0.0.

Return Value

Integer reply, specifically :

  • 1, if the key is renamed to the new key.
  • 0, if a new key already exists.

Return Value Type

Integer

Example - 1: Redis RENAMENX

First, create some keys in redis and set some values in it.

127.0.0.1:6379> SET key "Apple"
OK
127.0.0.1:6379> SET key1 "Banana"
OK
127.0.0.1:6379> RENAMENX key key1
(integer) 0
127.0.0.1:6379> GET key1
"Banana"

Example - 2: Redis RENAMENX

Now rename the key key1 to Python.

127.0.0.1:6379> MSET key "PHP" key1 "JavaScript"
OK
127.0.0.1:6379> RENAMENX key key1
(integer) 0
127.0.0.1:6379> RENAMENX key Python
(integer) 1

Previous: RENAME
Next: RESTORE



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/redis/redis-renamenx-key-newkey.php