【问题标题】:Cassandra DataModel QueryCassandra 数据模型查询
【发布时间】:2014-01-13 06:33:30
【问题描述】:

我是 Cassandra 的新手,并尝试了解数据模型。所以我知道如果“bob”跟随“james”,如何插入。我也知道如何查询以获取所有关注“bob”的人的列表,并且我知道如何查询以获取“bob”关注者的列表。

我的问题是,鉴于以下情况,如果我想知道“bob”是否跟随“james”,查询会是什么样子? (是或否)

这是正确的查询吗?

SELECT * FROM followers WHERE username="bob" AND following="james" 

我是否需要在 FOLLOWING 上设置第二个索引才能执行上述查询?

    -- User storage
CREATE TABLE users (username text PRIMARY KEY, password text);

-- 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)
);

【问题讨论】:

    标签: nosql cassandra cql


    【解决方案1】:

    在这种情况下不需要二级索引。您始终可以使用 cqlsh shell 测试这样的快速想法。

    cqlsh> use ks;
    cqlsh:ks> CREATE TABLE followers (
          ...     username  text,
          ...     following text,
          ...     PRIMARY KEY(username, following)
          ... );
    cqlsh:ks> INSERT INTO followers (username, following ) VALUES ( 'bob', 'james' );
    cqlsh:ks> SELECT * FROM followers WHERE username='bob' and following='james';
    
     username | following
    ----------+-----------
          bob |     james
    

    您不必创建二级索引(如果您想大规模执行此类查询也不应该)的原因是因为“following”被指定为集群键。这意味着“关注”描述了分区中数据的布局,这意味着我们可以非常快速地过滤“关注”。

    顺便说一句,如果频繁执行的查询需要二级索引(允许过滤),这表明您应该重新考虑您的数据模型。

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 2012-07-09
      • 2018-04-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多