[ACCEPTED]-redis performance, store json object as a string-redis

Accepted answer
Score: 22

You can use Redis hashes data structure to store 18 your JSON object fields and values. For 17 example your "users" set can still 16 be used as a list which stores all users 15 and your individual JSON object can be stored 14 into hash like this:

db.hmset("user:id", JSON.stringify(jsonObj));

Now you can get by key 13 all users or only specific one (from which 12 you get/set only specified fields/values). Also 11 these two questions are probably related to your 10 scenario.

EDIT: (sorry I didn't realize that we talked about this earlier)

Retrieving a record would then 9 be easier (I will then have to Parse it 8 with JSON).

This is true, but with hash data 7 structure you can get/set only the field/value 6 which you need to work with. Retrieving 5 entire JSON object can result in decrease 4 of performance (depends on how often you 3 do it) if you only want to change part of 2 the object (other thing is that you will 1 need to stringify/parse the object everytime).

Score: 8

One additional merit for JSON over hashes 11 is maintaining type. 123.3 becomes the string 10 "123.3" and depending on library Null/None can accidentally 9 be casted to "null".

Both are a bit tedious as 8 that will require writing a transformer 7 for extracting the strings and converting 6 them back to their expected types.

For 5 space/memory consumption considerations, I've 4 started leaning towards storing just the 3 values as a JSON list ["my_type_version", 123.5, null , ... ] so I didn't have 2 overhead of N * ( sum(len(concat(JSON key names))) which in my case was +60% of 1 Redis's used memory footprint.

Score: 6

bear in mind: Hashes cannot store nested 1 objects, JSON can do it.

Score: 4

Truthfully, either way works fine. The 11 way you store it is a design decision you 10 will need to make. It depends on how you 9 want to retrieve the user information, etc.

In 8 terms of performance, storing the JSON encoded 7 version of the user object will use less 6 memory and take less time for storage/retrieval. That 5 is, JSON parsing is probably faster than 4 retrieving each field from Redis. And, even 3 if not, it is probably more memory efficient. The 2 difference in performance is probably minimal 1 anyway.

More Related questions