I was doing a project that used redis and I found the data types to be kinda confusing. So, I wrote a blog post about the data types of redis.
string
So this data type is pretty straightforward. You can store strings in redis. For example, like this:
redis.set("fruit", "apple")
The fruit
will be the key
while apple
would be the value
.
list
The list data type can store an ordered collection of strings. These are some features of the list data type:
- ordered: Redis lists are ordered by the sequence in which they are added
- duplication: lists can contain duplicate elements
- You can insert, remove, or range query a redis list
For example, I can set a value by specifying the index:
// assuming that there's already a key named "fruit"
redis.lset("fruit", 0, "apple")
set
Simply put, set is an unordered collection of unique strings. Here are some key features of the set data type:
- unordered: Redis sets are unordered
- unique (duplication X): Redis sets don't allow the storing of duplicated values. Adding an already-existing element to a Redis set will have no effect
Here's how I can add an element in a Redis set:
redis.sadd("fruit", "apple")
redis.sadd("fruit", "apple") // this won't have any effect
sorted set
Sorted sets are sets with the added feature of being sorted. We can also increment or decrement the score
value:
redis.zadd("fruit", {incr: true}, {
member: "apple",
score: 1
})
Note that the score value get incremented depending on the score value!
hash
Hashes is where we can store object data. I was pretty familiar with this one:
await redis.hset("fruit", {
id: 1,
name: "apple",
likeCount: 20
})
I'll add more when I dive deeper into Redis :D