redis performance, store json object as a string

前端 未结 4 400
夕颜
夕颜 2021-01-31 04:13

I need to save a User model, something like:

{ \"nickname\": \"alan\",
  \"email\": ...,
  \"password\":...,
  ...} // and a couple of other fields
相关标签:
4条回答
  • 2021-01-31 04:43

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

    0 讨论(0)
  • 2021-01-31 05:00

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

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

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

    0 讨论(0)
  • 2021-01-31 05:02

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

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

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

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

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

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

    0 讨论(0)
  • 2021-01-31 05:09

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

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

    0 讨论(0)
提交回复
热议问题