Reputation:
Say I have an ability for users to friend each other and I have a widget which displays a users friends.
Would Redis be used here to store the relationships via the user.id?
1,2
1,5
4,1
3,1
1.friends -> 2, 3, 4, 5
But, then I'd need to fetch details for those friends. Am I right to assume this would done using a query "id IN(2,3,4,5)"?
Upvotes: 0
Views: 222
Reputation: 10923
You can definitely use redis to represent this data. One strategy would be to use a hash for each users details, keyed by user id (e.g. user:1 => {'name': 'foo', 'email': '[email protected]'}
) and a set of user ids for relationships (e.g. user:1:friends => (2, 3, 4, 5)
) You are correct that you would then need to do an hgetall user:<ID>
for each user in the friends set to get that user's info. HGETALL is O(N) where N is the number of fields; for something like a user object where the number of fields will be small and (relatively) fixed, HGETALL is effectively O(1), so the additional lookup there isn't terribly expensive. You can also use redis pipelines to batch those lookups and minimize network expense.
Upvotes: 2