Since Redis is a key-value store that lets us associate values with a key, it does not use the Data Manipulation Language (DML) and query syntax as relational databases. So how to we write, read, update, and delete data in Redis? This tutorial will cover how to write, read, update, and delete keys using the redis-cli as well as Navicat for Redis.
Reading Data
We can use the GET command to ask Redis for the string value of a key:
GET key
Here's an example in Navicat for Redis that fetches the value for the key "auth service" shown below:
As expected, it returns its value of "auth0":
However, if we try to fetch the value for "indiana_jones_episodes", we get an error "WRONGTYPE Operation against a key holding the wrong kind of value". That's because its value is a zset. Since Redis supports 6 data types, you need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value(s):
- if value is of type string -> GET
<key>
- if value is of type hash -> HGET or HMGET or HGETALL
<key>
- if value is of type lists -> lrange
<key> <start> <end>
- if value is of type sets -> smembers
<key>
- if value is of type sorted sets -> ZRANGEBYSCORE
<key> <min> <max>
- if value is of type stream -> xread count
<count>
streams<key>
<ID>
.
So, to retrieve the values for "indiana_jones_episodes", we can use ZRANGEBYSCORE and include the min and max arguments as follows:
That returns the first three values of the sorted set.
Writing and Updating Data
In Redis, the SET key Value
command works for both setting the initial value as well as for updates.
Of course, in Navicat, both keys and values can be modified at any time using the Editor:
Deleting Data
In Redis, we can use the DEL command to delete a key, along with all of its associated values. It's syntax is:
DEL key
For example, the following command would delete the "auth service" key:
DEL "auth service"
Be careful; Redis does not ask you to confirm the operation!
In Navicat, we can delete a key by selecting it in the table and then clicking the Delete [-] button. A dialog will ask us to confirm before proceeding with the delete, in case we happened to click it by accident!
Conclusion
In this tutorial, we learned how to write, read, update, and delete keys using the redis-cli as well as Navicat for Redis. Next time, we'll learn some more commands for working with data using redis-cli commands, along with how to accomplish the same thing using Navicat.
Interested in giving Navicat for Redis a try. Download it here. The trial version is fully functional for 14 days.