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
Option 1:
Using
key: value
pair.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
androles
.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.
Time complexity:
O(N)
. WhereN
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.
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 theUser_1
.