skip to Main Content

I’m building a simple web application where I need to store user information when logged in.

The information that I need to store is in json format like:

User:{'name': 'John', roles:[1,2,3]}

I was thinking in storing the information with a combination of user + {user_id} like:

User_1: {'name': 'John', roles=[1,2,3]}

I needed to know if this is a good practice (thinking in retrieving the information fast) or if there is another alternative.

2

Answers


  1. Option 1:

    Using key: value pair.

    "User_1": "name: John, roles=[1,2,3]"
    

    Time complexity: O(1).

    [x] But after getting the data from Redis you have to parse it again.

    Option 2:

    Using separate keys for name and roles.

    "User_1_name": "John", 
    "User_1_roles": [1,2,3]
    

    Time complexity: O(1) per request. In total for your example case it’s constant.

    [x] Extra call for same user.

    Option 3:

    Using hash.

    user_1: {
        "name": "John", 
        "roles": [1, 2, 3]
    }
    

    Time complexity: O(N). Where N is the number of fields in hash. But for your example case it’s constant.

    In my opinion using a hash will be the best option.

    Login or Signup to reply.
  2. I guess your question is about the key, not value.

    It’s good practice to save user with user+id key.
    And if you have another identify attribute for your user(Email for example), you’ll need to map all users to their email.

    So each user will have these keys in Redis:

    User_1: {'name': 'John', roles:[1,2,3], 'email': '[email protected]'}

    [email protected]_id: 1

    When you needed to find user by email, you can get the user id by reading the [email protected]_id(which it’s value is equal to user’s id 1), then get the User_1.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search