Search code examples
cassandracql3cassandra-2.0datastax

composite column keys & composite row keys


I'm trying to understand the concept of Composite Column key & Composite Row Key but unable to get it. I think it's used for getting a range of values but can't we use timestamp column as cluster key for this purpose ? What is the use case, advantages, disadvantages & implementation. Please explain using CQL 3.

Composite Column key: https://i.sstatic.net/qLboK.png

Composite Row Key: https://i.sstatic.net/xA6Hz.png


Solution

  • Maybe you confuse both terms which refers how cassandra stores compounds primary keys. I'll explain how composite keys works and how is stored physically easily with Cassandra 2.0 and CQL3.

    Cassandra stores all the logical rows with the same partition key as a single physical wide row. Partition key is divided in (partition_key, clustering_key).

    • partition_key: Identifies the row in Cassandra. All registers with the same partition_key will go to the same machine and will be store together. You can compound a partition_key.
    • clustering_key: keep the data with the same partition_key ordered. You can set multiple clustering keys separated by commas.

    Imagine you have a table purchase with this definition:

    CREATE TABLE purchase(
      user text,
      item text,
      time timestamp,
      PRIMARY KEY ((user, item), time)
    );
    

    And this data

    john  car  09/01/14...
    john  car 09/05/13...
    john  house 09/07/11...
    penny laptop  09/08/08...
    penny laptop 09/03/11...
    rachel tv 09/01/09...
    

    Cassandar will store that data

    john || car  || 09/05/13 - 09/01/14
    john || house || 09/07/11
    penny || laptop || 09/08/08 - 09/03/11
    rachel || tv || 09/01/09
    

    If you want to retrieve cars that john bought you can assure that two registers are stored together and ordered by time.

    For querys you always have to set partition key fields ( = ) and you can if you want compare order of clustering keys with ( < or > ).

    Examples:

    • select * from purchase where user='penny' and item='laptop'. Return 2 registers.
    • select * from purchase where user='john' and item='car' where date 01/01/14. Return 1 register.

    Hope it helps.