In Redis, the SMOVE
command moves a member of a set from one key to another. In other words, the member is removed from the source set and added to the destination set.
If the destination set doesn’t already exist, it’s created and the member is moved to it. If the source set doesn’t exist, no operation is performed, and an integer reply of 0
is returned.
Syntax
The syntax goes like this:
SMOVE source destination member
So this means that we specify the source key, the member to move, and the destination key when calling the command.
Example
Suppose we create the following set:
SADD todo Bob Kate Jim Ash
We can use SMEMBERS
to see all the members of the set:
SMEMBERS todo
Result:
1) "Kate" 2) "Ash" 3) "Jim" 4) "Bob"
Now let’s use the SMOVE
command to move one of those members to a new key:
SMOVE todo done Jim
Result:
(integer) 1
We get an integer reply of 1
, which means that one member was moved to the destination set.
Let’s check the source set again:
SMEMBERS todo
Result:
1) "Kate" 2) "Ash" 3) "Bob"
We can see that Jim
is no longer in the source set.
Let’s check the destination set:
SMEMBERS done
Result:
1) "Jim"
The member is now in the destination set.
When I ran SMOVE
above, the destination set didn’t exist. Therefore, it was created and the member was moved to it.
When we say that it was moved, it was removed from the source set and added to the destination set.
Non-Existent Source Key
Specifying a source key that doesn’t exist results in no operation being performed, and an integer reply of 0
being returned:
SMOVE oops done Kate
Result:
(integer) 0
Non-Existent Member
It’s the same when specifying a member that doesn’t exist. No operation is performed, and an integer reply of 0
is returned:
SMOVE todo done Eduardo
Result:
(integer) 0
Passing the Wrong Number of Arguments
Passing the wrong number of arguments results in an error:
SMOVE todo done Kate Ash
Result:
(error) ERR wrong number of arguments for 'smove' command
The error tells us what we did wrong.
We get the same error if we call the command without any arguments:
SMOVE
Result:
(error) ERR wrong number of arguments for 'smove' command
SMOVE
is Atomic
The SMOVE
operation is atomic, which means that at any point in time, the member will always appear to other clients as a member of either the source set or the destination set.