Reputation: 1683
I have a 2D array to store in redis and I see two solutions: storing it as a JSON string or storing one hash per line. Which way is better?
Upvotes: 4
Views: 8885
Reputation: 4638
I was faced with the same question when designing an application. I opted on the side of simplicity. I'm going to assume your 2d array of data represents a database row. I would JSON encode it and store it using SET
. This allows me to use MGET
and MSET
when I want to handle multiple objects using one redis command. If this data gets updated in my database, I DEL
the key. To me this is easier than trying to update a redis hash.
Hashes in redis has its advantages. They will usually take up less memory because of "ziplist" encoding redis uses. You can avoid serialization as well, which could be pretty significant for some apps.
Here's a sample use case for a hash for me. Let's say I want a look up a username given a user id. I would do HGET user.usernames 1234
. This would give me the username for user id 1234. If there is a miss, I will query the DB and set it and since that data never changes, I never expire the hash. It allows a quick look up for a common piece of data rather than pulling the entire user, unserialize, and return needed field.
For a prospective massive lookup table, I use the algorithm as purposed here: http://redis.io/topics/memory-optimization It uses multiple hashes as if there were one and utilizes ziplist encoding to save memory.
Whichever method you choose, just stay consistent.
Upvotes: 4
Reputation: 29536
You can store each element in its own key. Just name keys so that the names contain the element's indices, and maybe the dimensions of the array as well.
Upvotes: 1
Reputation: 2130
How about using Redis lists? There isn't support for lists of lists, but you could either store one row per list entry, or build a list of keys referencing other lists.
Upvotes: 1