GETSET
The GETSET
command in DiceDB is a powerful atomic operation that combines the functionality of GET
and SET
commands. It retrieves the current value of a key and simultaneously sets a new value for that key. This command is particularly useful when you need to update a value and also need to know the previous value in a single atomic operation.
Syntax
Parameters
Parameter | Description | Type | Required |
---|---|---|---|
key | The key whose value you want to retrieve and set. | String | Yes |
value | The new value to set for the specified key. | String | Yes |
Return values
Condition | Return Value |
---|---|
The old value stored at the specifiied key | A string value |
The key does not exist | nil |
Behaviour
When the GETSET
command is executed, the following sequence of actions occurs:
- The current value of the specified key is retrieved.
- The specified key is updated with the new value.
- If the specified key had an existing
TTL
, it is reset. - The old value is returned to the client.
This operation is atomic, meaning that no other commands can be executed on the key between the get and set operations.
Errors
The GETSET
command can raise errors in the following scenarios:
Wrong Type Error
: If the key exists but is not a string, DiceDB will return an error.- Error Message:
(error) ERROR WRONGTYPE Operation against a key holding the wrong kind of value
- Error Message:
Syntax Error
: If the command is not provided with exactly two arguments (key and value), DiceDB will return a syntax error.- Error Message:
(error) ERROR wrong number of arguments for 'getset' command
- Error Message:
Examples
Basic Example
- The initial value of
mykey
is set to “Hello”. - The
GETSET
command retrieves the current value “Hello” and sets the new value “World”. - The old value “Hello” is returned.
Example with Non-Existent Key
- The key
newkey
does not exist. - The
GETSET
command sets the value ofnewkey
to “NewValue”. - Since the key did not exist before,
nil
is returned.
Example with Key having pre-existing TTL
- The
newkey
used in theGETSET
command had an existingTTL
set to expire in 60 seconds - When
GETSET
is executed on the mentioned key, it updates the value and resets theTTL
on the key. - Hence, the
TTL
onnewkey
postGETSET
returns-1
, suggesting that the key exists without anyTTL
configured
Wrong Type
- The key
mylist
is a list, not a string. - The
GETSET
command cannot operate on a list and returns aWRONGTYPE
error.
Syntax Error
- The
GETSET
command requires exactly two arguments: a key and a value. - Since only one argument is provided, DiceDB returns a syntax error.