我有一个topic_followers表,其架构如下
id, user_id, topic_id, creation_date, modified_date
我想从这个表生成一个哈希,其中user_id为关键字,以及此用户关注的topic_ids数组作为值。目前,我正在尝试使用以下代码来实现:
topic_followers = TopicFollower.select("user_id, topic_id")
topic_follower_hash = {}
topic_followers.each do |topic_follower|
topic_follower_hash[topic_follower.user_id] = topic_follower_hash[topic_follower.user_id] || []
topic_follower_hash[topic_follower.user_id] << topic_follower.topic_id
end
问题是,这是一张大桌子,我担心它会炸掉我的记忆。我搜索了一下,一些文章建议使用find_in_batches。我不认为它符合我的需要,因为用户关注的某些主题可能不在当前批次中。想知道解决这类问题的推荐做法是什么?
您正在寻找的实际上是聚合。
group_by user_id
inset all topic_id inside an array
您的最终回复将如下所示:
[{"id": "user_id", "topic_ids": ["topic_id1", ...]}...]
然后使用单个循环将此哈希数组转换为单个哈希。
有关Postgre中聚合的参考,请使用:Aggregation in Postgre