且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在cassandra中使用order by子句

更新时间:2023-12-03 17:45:16

DataStax推荐了一种面向查询的数据建模方法,其中结果按查询时所需的顺序存储。此顺序由[复合]主键的分区键和第一个聚簇列确定。 DataStax文档上的 ORDER BY 解释了这一点:


查询复合主键和排序结果ORDER BY子句
可以只选择一列。该列必须是复合PRIMARY KEY中的第二个
列。这也适用于
在主键中多于两个列组件的表。订单可以是以升序或降序执行$ ​​b $ b,以ASC或DESC关键字指定的默认升序和



在ORDER BY子句,请使用实际名称而不是别名将
引用到列。



例如,将
设置为播放列表,主键,插入
示例数据,并使用此查询获取有关特定
播放列表的信息,由song_order排序。从Cassandra 1.2开始,你不需要
在select表达式中包含ORDER BY列。




您还可以使用Apache Cassandra在线课程( DataStax Ac * ademy 。我相信第3节提供了一个关于 ORDER BY 子句的模块。


When creating table in cassandra, we can give clustering keys with ordering like below.

Create table user(partitionkey int, id int, name varchar, age int, address text, 
   insrt_ts timestamp,
 Primary key(partitionkey, name, insrt_ts, id)
 with clustering order by (name asc, insrt_ts desc, id asc);

when we insert data into that table, As per cassandra documentation records are sorted based on clustering keys.

When i retrieve records with CQL1 and CQL2, I am getting in the same sorted order.

CQL1:

Select * from user where partitionkey=101;

CQL2:

Select * from user where partitionkey=101 order by name, insrt desc, id;

what is the difference between CQL1 and CQL2?

DataStax recommends a query-oriented data modeling approach, where the results are stored in the order in which they are required at query-time. This order is determined by both the partition key and first clustering column of a [compound] primary key. The DataStax doc on the ORDER BY clause explains this:

Querying compound primary keys and sorting results ORDER BY clauses can select a single column only. That column has to be the second column in a compound PRIMARY KEY. This also applies to tables with more than two column components in the primary key. Ordering can be done in ascending or descending order, default ascending, and specified with the ASC or DESC keywords.

In the ORDER BY clause, refer to a column using the actual name, not the aliases.

For example, set up the playlists table, which uses a compound primary key, insert the example data, and use this query to get information about a particular playlist, ordered by song_order. As of Cassandra 1.2, you do not need to include the ORDER BY column in the select expression.

So basically you can really only alter it by asking for ASCending or DESCending order.

You also might want to check out the (free) Java development with Apache Cassandra online class at DataStax Ac*ademy. I believe session 3 offers a module on the ORDER BY clause.