Search code examples
redisredisson

Redis - Option for storing multiple objects


What is best practice in redis when we need to store multiple objects of same category?

Currently I store the whole object as json string.

For ex: Books.

{
   title:...,
   author:...
}

Option 1:

set book:1 book1
set book:2 book2
set book:3 book3

usage: get book:1 will give me the book object.

Option 2: hash

hset book 1 book1
hset book 2 book2
hset book 3 book3

usage: hget book 1 will give me the whole book object

Is there any huge difference in terms of performance or usage etc? Please share if you think of any other approach!


Solution

  • String vs Hash for storing JSON objects

    Most of the relevant operations for Hashes and Strings are equivalent to each other in time complexity(GET/HGET/MGET/HMGET/SET/HSET). The only downside of using strings(GET/SET) is if you're concerned about being able to scan over the entire set of books as the SCAN and KEYS commands operate over the entire keyspace (every key in Redis) - even if your pattern was books:*, Redis would still need to iterate over all the keys. Whereas HSCAN and HGETALL operate only over the hash. In other words, if you're storing a lot of stuff in Redis, and you want to be able to iterate over all your books, a HASH can save you some time.

    Storing JSON in Redis

    You asked a question in the comments whether storing JSON is bad practice, there's definitely nothing wrong with it, and it's very common, the only downside of using JSON is that you can only GET/SET the entire string, and each time you pull the data out of Redis your app has to marshall the data from JSON and Serialize it back to JSON whenever you want to ship an update to the database. If that's a concern, it can be overcome with the RedisJson Module, but that's a whole separate topic.