【问题标题】:Clustering Order using timeuuid CQL使用 timeuuid CQL 的聚类顺序
【发布时间】:2023-03-03 06:12:22
【问题描述】:

我的用例

我想按时间戳 DESC 排序结果。但我不希望时间戳成为主键中的第二列,因为这会占用我的查询能力

例如

create table demo(oid int,cid int,ts timeuuid,PRIMARY KEY (oid,cid,ts)) WITH CLUSTERING ORDER BY (ts DESC);

需要查询:

I want the result for all the below queries to be in DESC order of timestamp

select * from demo where oid = 100;
select * from demo where oid = 100 and cid = 10;
select * from demo where oid = 100 and cid = 100 and ts > minTimeuuid('something');

我正在尝试使用 CQL 中的 CLUSTERING ORDER 创建此表并收到此错误

cqlsh:v> create table demo(oid int,cid int,ts timeuuid,PRIMARY KEY (oid,cid,ts))     WITH CLUSTERING ORDER BY (ts desc);
Bad Request: Missing CLUSTERING ORDER for column cid

在本文档中,它提到我们可以有多个键用于集群排序。有人知道怎么做吗?

Go here Datastax doc

【问题讨论】:

    标签: cassandra cql cql3


    【解决方案1】:
    CREATE TABLE example ( a int, b int, c int, d int, PRIMARY KEY (a,b,c)) WITH CLUSTERING ORDER BY (b DESC , c ASC ) ;
    

    多列排序的正确语法。


    对于您的特定应用程序,您实际上是在尝试从截然不同的查询类型中获取结果。在 Cassandra 中,最好将每个表塑造成对特定查询的响应。

    例如(不太了解您的应用程序)

    select * from demo where oid = 100 and cid = 100 and ts > minTimeuuid('something');
    select * from demo where oid = 100 and cid = 10;
    

    可能会更好地使用类似的表结构

    create table demo_oct(oid int,cid int,ts timeuuid, body, other ...., PRIMARY KEY ((oid,cid),ts)) WITH CLUSTERING ORDER BY (ts DESC);
    

    这样,一对 oid 和 cid 数据的每组时间序列都将驻留在它自己的分区中,并且易于检索。这是因为我使用的是由 oid 和 cid 组成的分区键。这就是为什么键中有一组额外的括号。聚类键 ts 确保数据按您想要的顺序排列。

    但正如您所注意到的,您不能在此表上执行 select * from table oid == 10,因为这需要扫描整个数据库(因为分区结构)

    对于类似的查询

    select * from demo where oid = 100;

    您需要第二张表(同样不知道您的特定应用程序)

    create table demo_ot(oid int,cid int,ts timeuuid, body, other ...., PRIMARY KEY (oid,ts)) WITH CLUSTERING ORDER BY (ts DESC);
    

    该表将每个 OID 的时间序列保存在单个分区中,从而实现极快的切片。这里的分区键只是 OID,而 ts 仍然是集群键。

    在应用程序端,您将同时插入这两个表。

    More info on Datamodeling

    【讨论】:

    • 只有代码的答案很少,如果有的话,考虑好的、高质量的答案。请尝试通过提供解释和/或相关链接来详细说明为什么是可接受的答案。
    • @RussS 这个很棒的解释。所以本质上我们是为了查询性能和灵活性而浪费存储空间,对吧?
    • Cassandra 的经验法则是写入成本低。因此,牺牲存储空间并按照您的查询需要塑造您的数据 :)
    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 2013-08-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2018-06-11
    相关资源
    最近更新 更多