Redis

Redis MSET

Redis is a free and open-source in-memory database. It is a NoSQL database that stores data in a key-value pair. This means that a value is mapped to a specific unique key.

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:

SET key value

An example is as shown:

127.0.0.1:6379> SET key1 value1

OK

If a specified key already exists, it is replaced with a new value. Consider the example below:

127.0.0.1:6379> SET key1 value2

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:

SET key value EX expiry_duration_in_seconds

Take a look at the example below:

127.0.0.1:6379> SET key2 value2 EX 30

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.

127.0.0.1:6379> GET key2

(nil)

To get how a long has before being dropped, use the TTL command as:

127.0.0.1:6379> TTL key2

(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:

MSET key1 value1 key2 value2…keyN valueN

Consider the example inserts below:

127.0.0.1:6379> MSET key1 value1 key2 value2 key3 value3 key4 value4 key5 value5

OK

The example above inserts five key-value pairs in one command.

To get multiple values, you can use the MGET command as shown:

127.0.0.1:6379> MGET key1 key2 key3 key4 key5

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list