简体   繁体   English

Redis-存储用户喜欢

[英]redis - store user likes

I'm currently learning Redis, and I want to show to the user if he already liked a post or not, like on facebook. 我目前正在学习Redis,我想向用户展示他是否喜欢某个帖子,例如在Facebook上。

I was thinking of storing a list of users id, something like this: 我正在考虑存储用户ID列表,如下所示:

$redis.rpush('users_liked_post_#{post_id}', user_id)

$redis.lrange('users_liked_post_#{post_id}', 0, -1)

# [34, 23, 433, 432, 324]

And then check if the user id is in that list to tell if he already liked the post. 然后检查用户ID是否在该列表中,以判断他是否已喜欢该帖子。 But it's a O(n) speed, is there a better way ? 但这是O(n)速度,还有更好的方法吗?

Use a Set instead - it ensure no duplicates (ie a user can't like a post twice) and you can check existence quickly, ie (assuming redis-rb): 使用Set代替-它确保没有重复(即用户不能两次喜欢一个帖子),并且可以快速检查是否存在,即(假设redis-rb):

redis.sadd 'post:{#post_id}:likes', '{#user_id}'

Note that in order to do the reverse query, get the list of pages that a user liked, you'll need to keep another Set with the likes per each user, eg: 请注意,为了进行反向查询,获取用户喜欢的页面列表,您需要保留每个用户喜欢的另一个Set,例如:

redis.sadd 'user:{#user_id}:likes' '{#post_id}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM