Learning how to work with key-value pairs is very important. This tutorial will discuss inserting single or multiple key-value pairs using the SET or MSET commands.
Redis Set Command
The Redis SET command adds a provide key value to a database. The syntax is as shown below:
An example is as shown:
If a specified key already exists, it is replaced with a new value. Consider the example below:
127.0.0.1:6379> get key1
In this case, the value of key1 gets replaced with value2.
You can also set a key with an expiration value using the EX parameter. Sample sytax is shown:
Take a look at the example below:
After the expiration duration is elapsed, Redis will delete the key from the database. If you attempt to get the value, Redis will return nil.
To get how a long has before being dropped, use the TTL command as:
Redis MSET Command
The MSET command is very similar to the Redis command, except it inserts multiple key-value pairs.
The syntax is shown below:
Consider the example inserts below:
The example above inserts five key-value pairs in one command.
To get multiple values, you can use the MGET command as shown:
This should return the corresponding value for the existing key.
This article taught us to insert key-value pairs using the SET and MSET commands.
We hope you enjoyed the tutorial.