嗨,我创建了一个表来存储这样的数据
CREATE TABLE keyspace.test (
name text,
date text,
time double,
entry text,
details text,
PRIMARY KEY ((name, date), time)
) WITH CLUSTERING ORDER BY (time DESC);
并将数据插入表中。但是这样的查询给出了无序的结果。
SELECT * FROM keyspace.test where device_id name ='anand' and date in ('2017-04-01','2017-04-02','2017-04-03','2017-04-05') ;
我的 table 设计有什么问题吗。
最佳答案
我认为您误解了 cassandra 聚类键顺序。 Cassandra 在单个分区内使用集群键对数据进行排序。
这适用于您的案例 cassandra 排序数据,在单个名称和日期内使用聚类键时间。
示例:让我们插入一些数据
INSERT INTO test (name , date , time , entry ) VALUES ('anand', '2017-04-01', 1, 'a');
INSERT INTO test (name , date , time , entry ) VALUES ('anand', '2017-04-01', 2, 'b');
INSERT INTO test (name , date , time , entry ) VALUES ('anand', '2017-04-01', 3, 'c');
INSERT INTO test (name , date , time , entry ) VALUES ('anand', '2017-04-02', 0, 'nil');
INSERT INTO test (name , date , time , entry ) VALUES ('anand', '2017-04-02', 4, 'd');
如果我们根据您的查询选择数据:
SELECT * FROM test where name ='anand' and date in ('2017-04-01','2017-04-02','2017-04-03','2017-04-05') ;
输出 :
name | date | time | details | entry
-------+------------+------+---------+-------
anand | 2017-04-01 | 3 | null | c
anand | 2017-04-01 | 2 | null | b
anand | 2017-04-01 | 1 | null | a
anand | 2017-04-02 | 4 | null | d
anand | 2017-04-02 | 0 | null | nil
你可以看到那个时间
3,2,1
位于单个分区内 anand:2017-04-01
按 desc 和时间排序 4,0
在单个分区内 anand:2017-04-02
按 desc 排序。 Cassandra 不会负责不同分区之间的排序。这是文档:
In the table definition, a clustering column is a column that is part of the compound primary key definition, but not the first column, which is the position reserved for the partition key. Columns are clustered in multiple rows within a single partition. The clustering order is determined by the position of columns in the compound primary key definition.
来源:http://docs.datastax.com/en/cql/3.1/cql/ddl/ddl_compound_keys_c.html
顺便说一下,为什么您的数据字段是
text
类型和 time
字段是 double
类型 ?您可以使用
date
字段为 date
类型和 time
如 timestamp
类型。
关于Cassandra CLUSTERING ORDER BY 不起作用并显示正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43297856/