27

Lets say I have an object (User) which consists of a few properties (ID, Name, Surename, Age). Which way is better to store this object in redis?

  • store each property value in dedicated key, for example user:{id}:id, user:{id}:name, user:{id}:surename, user:{id}:age
  • store whole User object as JSON string in one key, for example user:{id}:json (value of the key will be something like this: {"ID": 123, "Name": "Johny", "Surename": "Bravo", "Age": 22})
yojimbo87
  • 65,684
  • 25
  • 123
  • 131

3 Answers3

21

According to these two sources probably the optimal solution would be to use hashes because of memory consumption when using dedicated keys and long string in scenario with JSON as key value.

yojimbo87
  • 65,684
  • 25
  • 123
  • 131
  • Hm, there seem to be many options when storing arrays of Objects: (1) store each property in a dedicated key (i.e. SET user:{id}:name "Fred"), (2) store the entire object as JSON string in a single key (i.e. SET user:{id} '{"name":"Fred"}'); or (3) store each Object as a JSON string in a Redis hash (i.e. HMSET users {id} '{"name":"Fred"}'). Sure, there are advantages and disadvantages to each, but what is the most CPU time/memory efficient? – BMiner Sep 24 '13 at 19:18
  • Also, another way (4) is to store each Object's properties in a Redis hash (i.e. `HMSET user:{id} name "Fred"`). – BMiner Sep 24 '13 at 19:31
  • 1
    I'd love to see this answer revised to consider all four (or perhaps more) approaches and the CPU vs. memory efficiency of each. :) Of course, I suppose it depends on how the system plans to query these data later. Not to mention... there are other advantages / disadvantages besides memory efficiency / speed. What about "best practices?" – BMiner Sep 24 '13 at 19:32
1

From official Redis

Use hashes when possible

Small hashes are encoded in a very small space

When you haven't to much fields in it.

Every time an hash will exceed the number of elements or element size specified it will be converted into a real hash table, and the memory saving will be lost.

Aurel
  • 3,682
  • 1
  • 19
  • 22
0

From my tests using hash takes much smaller space, but that is about the only reason. If you have a lot of data consider using hash. Otherwise you might as well use JSON since it's easy to serialize and deserialize it to objects if you so wish, and handle in general.

Erik Bergstedt
  • 912
  • 10
  • 27