【问题标题】:How do I get the last 50 rows for this table using Cassandra CQL?如何使用 Cassandra CQL 获取该表的最后 50 行?
【发布时间】:2017-11-04 13:30:43
【问题描述】:

这是我用来创建表的查询:

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid));

我想获取按时间戳降序排序的最后 50 行。

如果我尝试类似:SELECT * FROM test.comments WHERE page = 'test' AND timestamp < 1496468332,我会收到此错误:

Error from server: code=2200 [Invalid query] message="Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING"

我不想使用允许过滤,我希望查询尽可能快。

我在这里查看了另一个 stackoverflow 问题 Cassandra cql: how to select the LAST n rows from a table 并尝试了解决方案:

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid)) WITH CLUSTERING ORDER BY (msguuid DESC);

然后我得到这个错误:InvalidRequest: Error from server: code=2200 [Invalid query] message="Only clustering key columns can be defined in CLUSTERING ORDER directive"

我是 Cassandra 的新手,如果这有一个明显的答案,请原谅我。我似乎无法让它工作。

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

  • 页面是索引字段吗?
  • 是的,页面已编入索引
  • 你使用的是哪个 cassandra 版本?
  • [cqlsh 5.0.1 |卡桑德拉 3.10 | CQL 规范 3.4.4 |原生协议 v4]
  • 如何使用当前时间生成 msguuid ??

标签: cassandra cql


【解决方案1】:

不使用索引创建Materialized View

创建一个物化视图,其中 page 作为分区键,msguuid 作为集群键 order by desc。

CREATE MATERIALIZED VIEW test.comments_by_page AS
    SELECT *
    FROM test.comments
    WHERE page IS NOT NULL AND msguuid IS NOT NULL
    PRIMARY KEY (page, msguuid)
    WITH CLUSTERING ORDER BY (msguuid DESC);

虽然您使用msguuid 作为当前时间戳的timeuuid,但您的数据将按时间降序排序。

要获取页面的最后 50 行,请使用以下查询:

SELECT * FROM comments_by_page WHERE page = 'test' LIMIT 50;

查看此链接以了解物化视图优于索引的性能以及何时不使用:http://www.datastax.com/dev/blog/materialized-view-performance-in-cassandra-3-x

【讨论】:

    【解决方案2】:

    在 cassandra 世界中,尝试根据需要满足的查询为您的表建模。如果查询总是通过 where 子句“page”并且 msguuid 只是为了唯一性而重新设计表,如下所示

    CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (page, msguuid), WITH CLUSTERING ORDER BY (msguuid DESC));
    

    现在表格自然是按 msguuid 排序的,不需要额外的物化视图开销。

    【讨论】:

    • 谢谢,我很高兴有一种无需开销的方法。我将你的标记为答案。
    • @dilsingi 我的解决方案不会生成墓碑。 MV 只生成 tombstone 如果 MV 的主键 pagemsguuid 在基表上更新。对于他的情况,没有机会更新page 的值,因为它是他的主键,而且msguuid 也不会更新,因为它是当前时间戳timeuuid。在建议任何人之前了解更多信息opencredo.com/everything-need-know-cassandra-materialized-views
    • @AshrafulIslam 根据原始表定义,它从未将“页面”作为主键。请检查。所以它可能已经更新,MV 会导致墓碑。
    • 在那种情况下,你的 (@dilsingi) 设计呢?如果页面更新,则需要删除该页面的所有 msguuid 和关联数据并重新插入
    • @AshrafulIslam 确实,对于 Cassandra 中的任何表,主键都无法修改。但是,当原始表可以满足用例时,为什么要创建一个 MV。因此,围绕查询对表格进行建模,反之亦然。
    猜你喜欢
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2016-05-28
    • 2021-11-03
    • 2015-05-22
    相关资源
    最近更新 更多