by László Wágner, Nexsis Mobile
In my previous article I summarized what the 5 basic steps are for Key-value store database design. Those were:
This is one of the most common usages of key-value store database. We have an identifier and we would like to attach some attributes in order to describe it more deeply. For this we can use hash object and we can set up more fields at ones.
HMSET "Singer:Madonna" id 9 name "Madonna" desc "Singer"
Now we have a hash object called "Singer:Madonna" and it has 3 attributes id, name and desc. To get back values of attributes you can use hget or hgetall.
HGET "Singer:Madonna" id -----> result will be 9
The beauty of the hash object is you are not limited to the number of attributes. You can add another attribute anytime and old ones will be untouched. You don’t need to do any object modification just set up the new value.
HSET "Singer:Madonna" residence “New York”
Sometimes it is very time consuming to calculate distinct values of large tables without indexes. In Redis we can use SET object and SADD command for this purpose. When you call SADD command the necessary processing will be done quickly. That means you don’t need to wait for any check or calculation when you query the distinct data from the SET.
SADD Singers “Madonna” “Adele” “Eminem” “Madonna” “Madonna”
Result will be for Singers:
In more complex cases you can store distinct values with ranks on ordered sets. One scenario can be when you would like to know the first couple of elements of a list. Sorted set does the trick for you first it keeps only distinct values, second you can modify the order of the elements by changing the rank of certain value using ZINCRBY command.
ZREVRANGE “Best:Singers” 0 9 WITHSCORES
Since Redis is an in-memory database it is used for cache or message broker quite frequently. When you design you application you may need this kind of feature. You may need to store commands that have to be launched later or you have to feed other application with data you collected earlier. To fulfil this requirement you can use lists. You can easily implement FIFO, LIFO, Heap with the proper usage of certain variant of POP and PUSH command.
For example FIFO implementation can be like this:
insert data: RPUSH fifo “first” “second” “third”
get data: LPOP fifo ----- > “first”