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:
OK
If a specified key already exists, it is replaced with a new value. Consider the example below:
OK
127.0.0.1:6379> get key1
"value2"
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:
OK
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.
(nil)
To get how a long has before being dropped, use the TTL command as:
(integer) 27
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:
OK
The example above inserts five key-value pairs in one command.
To get multiple values, you can use the MGET command as shown:
1) "value1"
2) "value2"
3) "value3"
4) "value4"
5) "value5"
This should return the corresponding value for the existing key.
Conclusion
This article taught us to insert key-value pairs using the SET and MSET commands.
We hope you enjoyed the tutorial.