cassandra的instagram时间线数据模型

时间:2015-01-23 19:26:04

标签: cassandra schema data-modeling nosql

我希望像instagram一样设计时间轴(Home),但大多数采样如"twissandra-j"使用了以下模式:

     -- Users user is following
CREATE TABLE following (
    username text,
    followed text,
    PRIMARY KEY(username, followed)
);

-- Users who follow user
CREATE TABLE followers (
    username  text,
    following text,
    PRIMARY KEY(username, following)
);

-- Materialized view of tweets created by user
CREATE TABLE userline (
    tweetid  timeuuid,
    username text,
    body     text,
    PRIMARY KEY(username, tweetid)
);

-- Materialized view of tweets created by user, and users she follows
CREATE TABLE timeline (
    username  text,
    tweetid   timeuuid,
    posted_by text,
    body      text,
    PRIMARY KEY(username, tweetid)
);

在此设计中,每插入一个新帖子,为每个关注者在时间轴中插入新记录。如果一个用户有10k的关注者,1000个用户使用了应用程序,程序就会失败,有更好的方法吗?

// Insert the tweet into follower timelines
    for (String follower : getFollowers(username)) {
        execute("INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
                follower,
                id.toString(),
                username,
                body);

1 个答案:

答案 0 :(得分:0)

我想,这2个解决方案/建议中的一个可以提供帮助:

1) - 第一个建议,例如以1000个插入语句的批处理模式插入到TIMELINE中。

execute("
  BEGIN BATCH
    INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')", follower, id.toString(), username, body);
    INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')", follower, id.toString(), username, body);
    INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')", follower, id.toString(), username, body);
    ...
    // n statements
APPLY BATCH");
  • 批处理多个语句可以节省客户端/服务器与服务器协调器/副本之间的网络交换。

  • 还有一件事,默认情况下批次是原子的(在Cassandra 1.2及更高版本中)。在Cassandra批处理操作的上下文中,atomic表示如果任何批处理成功,则所有批处理都将成功,否则为none。

2) - 第二个建议,在异步模式下实现插入到TIMELINE中(前端有成功的回调函数):

当然,也许你可以将两者结合起来。