Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the defined behavior of this cassandra query with nonaggregate columns?

Suppose I had this table.

CREATE TABLE keyspace.user_event (
   user_name varchar,
   user_email varchar,
   event_type int,
   event_time timestamp,
   a varchar,
   b varchar,
   c varchar
   PRIMARY KEY ((user_name, user_email), event_type, event_time)
) WITH CLUSTERING ORDER BY (event_type ASC, event_time DESC);

I am interested in finding the most recent user_event for every unique event_type given a user_name an user_email and a subset of event_types. A composed query would look like this, as an example.

SELECT user_name, 
       user_email, 
       event_type, 
       max(event_time) AS event_time, 
       a, 
       b, 
       c 
FROM   user_event 
WHERE  user_name = 'user_name3' 
       AND user_email = 'user_email3' 
       AND event_type IN ( 301, 219, 206, 226 ) 
GROUP  BY event_type; 

Will this cassandra query behave the way I'd expect it to? If not, how might I reformulate the query? I want columns a, b, and c to match with the max row returned with the aggregate, max(event_time).

Now, as per https://docs.datastax.com/en/dse/5.1/cql/cql/cql_reference/cqlAggregates.html, cassandra will default to the first row of a non aggregate column. Because I specified the partition key in full, I am expecting a single partition to get searched, and therefore the ordering of the clustering keys to be consistent within that partition.

With local testing on a few rows, I haven't been able to break the query yet, but I want to ensure that I am not missing any unexpected behavior.

An an example, suppose we had the following data.

|user_email |user_name  |event_type|a  |b  |c  |event_time               |
|-----------|-----------|----------|---|---|---|-------------------------|
|user_email2| user_name2|219       |a1 |b1 |c1 | 2019-10-01 18:50:25.653Z|
|user_email3| user_name3|219       |a2 |b2 |c2 | 2019-10-01 18:50:25.665Z|
|user_email3| user_name3|226       |a3 |b3 |c3 | 2019-10-01 21:37:05.663Z|
|user_email3| user_name3|301       |a4 |b4 |c4 | 2019-10-01 18:50:35.658Z|
|user_email3| user_name3|301       |a5 |b5 |c5 | 2019-10-01 18:50:25.660Z|
|user_email3| user_name3|301       |a6 |b6 |c6 | 2019-10-01 18:50:25.656Z|
|user_email1| user_name1|206       |a7 |b7 |c7 | 2019-10-01 18:50:25.604Z|

The expected output for the above query would be.

event_type |    a,b,c   |
-----------|------------|
226        | a3, b3, c3 |  
219        | a2, b2, c2 |
301        | a4, b4, c4 |
like image 754
onesiumus Avatar asked Oct 01 '19 20:10

onesiumus


1 Answers

Add the following to the script above:

    SELECT DISTINCT(event_type) as event_type;

    ORDER BY event_type, event_time DESC;
like image 187
Ashish Patel Avatar answered Oct 18 '22 22:10

Ashish Patel