【问题标题】:getting result in the same order it was added in the table以添加到表中的相同顺序获取结果
【发布时间】:2015-08-26 13:47:09
【问题描述】:

我有这张桌子

CREATE TABLE tag_by_user (
userId uuid,
tagId uuid,
colId timeuuid,
tagLabel text,
PRIMARY KEY (userId, tagId,colId)
);

这是我的数据

insert into tag_by_user(userId,tagId,colId,tagLabel) values(4978f728-0f96-11e5-a6c0-1697f925ec7b
,b0b328fa-0f96-11e5-a6c0-1697f925ec7b,now(),'html');
insert into tag_by_user(userId,tagId,colId,tagLabel) values(4978f728-0f96-11e5-a6c0-1697f925ec7b
,b0b330d4-0f96-11e5-a6c0-1697f925ec7b,now(),'java');
insert into tag_by_user(userId,tagId,colId,tagLabel) values(4978f728-0f96-11e5-a6c0-1697f925ec7b
,c0f22450-0f96-11e5-a6c0-1697f925ec7b,now(),'javascript');
insert into tag_by_user(userId,tagId,colId,tagLabel) values(4978f728-0f96-11e5-a6c0-1697f925ec7b
,c0f226b2-0f96-11e5-a6c0-1697f925ec7b,now(),'scala pro');
insert into tag_by_user(userId,tagId,colId,tagLabel) values(4978f728-0f96-11e5-a6c0-1697f925ec7b
,c0f22ab8-0f96-11e5-a6c0-1697f925ec7b,now(),'c++');

现在我想按照添加到行的相同顺序获取给定用户的标签(即按添加时间的升序,这里是colId

cqlsh:ks_demo> select taglabel from tag_by_user where userid= 77c4d46c-0f96-11e5-a6c0-1697f925ec7b  order by colid;

它给出了这个错误

Bad Request: Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY

我必须在架构或查询cqlsh 4.1.1 | Cassandra 2.0.8中进行哪些更改

【问题讨论】:

    标签: cassandra cql


    【解决方案1】:

    您只需要在 PRIMARY KEY 中保留 userId 和 colId:

    CREATE TABLE tag_by_user (
    userId uuid,
    colId timeuuid,
    tagId uuid,
    tagLabel text,
    PRIMARY KEY (userId, colId)
    );
    

    然后使用

    SELECT * FROM tag_by_user WHERE userId={yourUserId}
    

    按时间升序获取给定用户的标签。

    如果您需要避免重复的标签,那么您可以在 tagId 上创建一个索引,并使用它来找出给定用户的标签是否已经存在并处理它。虽然一旦插入数据就不能修改colId

    【讨论】:

    • 这个架构能否回答select * from tag_by_user where userId =123 and tagId=xyz
    • @Manish 是的,您需要为此在tagId 创建一个索引。是的。
    【解决方案2】:

    正如消息所示,要使用 order by,您应该遵循与 PRIMARY KEY 中相同的顺序。

    CREATE TABLE tag_by_user (
        userid uuid,
        colid timeuuid,
        tagid uuid,
        taglabel text,
        PRIMARY KEY (userid, colid, tagid)
    );
    
    select taglabel from tag_by_user where userid = 4978f728-0f96-11e5-a6c0-1697f925ec7b  order by colid;
    
     taglabel
    ------------
           html
           java
     javascript
      scala pro
            c++
    

    【讨论】:

    • 这个架构能否回答select * from tag_by_user where userId =123 and tagId=xyz
    • 不,为此您需要使用 PRIMARY KEY (userid,tagid) 创建另一个表
    • 基本上我想在插入之前检查标签的重复。那么在同一个架构中是否可能?
    • 在这种情况下,arystan 的解决方案会起作用,只是在使用索引时要小心,参考:docs.datastax.com/en/cql/3.1/cql/ddl/ddl_when_use_index_c.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多