【问题标题】:How to design a performant friends of friends database table如何设计一个高性能的朋友的朋友数据库表
【发布时间】:2016-09-14 11:54:46
【问题描述】:

我目前在一个名为http://www.clubsofa.org 的网站上工作,其概念是人们可以在谷歌地图上进行朋友的朋友搜索,目的是让他们与二级朋友联系旅行时。 目前的设置是 PostgreSQL,有一个名为 friends 的表,其中存储了两个唯一的用户 ID(其中友谊只存储一次,例如人 a,人 b 声明 a 是 b 的朋友,b 是 a 的朋友)。当查询朋友的朋友时,我会得到当前用户的所有朋友,然后搜索他们所有的朋友,但这需要很长时间,因为它运行的 AWS ec2 实例上的用户很少。 我尝试过的另一种方法是以两种方式存储朋友关系,然后在第一列上建立索引,但是速度稍慢。 我考虑设置它的一种方法是将一个人的朋友作为 JSON 对象存储在他们的 user_details 条目中,然后懒惰地更新它,但还没有开始测试它。

有什么好的方法可以设置吗?

【问题讨论】:

  • 如果您使用 Postgres,则以 SQLish 方式存储好友,作为好友表,每个好友对应一列。
  • 我目前已经掌握了它,而且速度非常慢。没有更高效的方法吗?
  • "它非常慢" - 向我们展示您当前的表定义(如create table 语句)您正在使用和阅读的查询:wiki.postgresql.org/wiki/SlowQueryQuestions

标签: sql database postgresql database-design relational-database


【解决方案1】:

您可以通过在表格上放置一个视图来更轻松地查询存储友谊的“一个方向”的表格...

create view all_friendships
as
select friend_from,
       friend_to
from   friendships
union all
select friend_to,
       friend_from
from   friendships;

通过 (friend_from,friend_to) 和 (friend_to,friend_from) 的唯一索引,这应该易于维护和查询。

所以交朋友的朋友是:

select distinct
       f2.friend_to
from   all_friendships f1 join
       all_friendships f2 on (f2.friend_from = f1.friend_to)
where  f1.friend_from = 12345 and
       f2.friend_to != 12345;

【讨论】:

  • 谢谢!这是一个非常好的主意,我没有想过这样做
猜你喜欢
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-10
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多