Set Multiple Fields with HMSET
In this step, we will explore the HMSET
command in Redis, which allows you to set multiple fields of a hash at once. This is more efficient than setting each field individually using the HSET
command.
First, let's connect to the Redis server using the redis-cli
command. Open a terminal in your ~/project
directory and type:
redis-cli
You should see the Redis prompt: 127.0.0.1:6379>
.
Now, let's use the HMSET
command. The syntax is:
HMSET key field value [field value ...]
Where:
key
is the name of the hash.
field
is the name of the field within the hash.
value
is the value to be assigned to the field.
Let's create a hash called user:1001
and set multiple fields for it: name
, age
, and city
.
HMSET user:1001 name "John Doe" age 30 city "New York"
You should see the output OK
, which indicates that the command was successful.
To verify that the fields have been set correctly, you can use the HGETALL
command. However, for this lab, we'll focus on verifying the commands themselves.
You can also use HMSET
to update existing fields. For example, let's change the age
field to 31
:
HMSET user:1001 age 31
Again, you should see OK
.
Remember to exit the redis-cli by typing exit
. This is important for the command to be logged for verification.
exit