In Cassandra a table is known as column-family, column-families consists of rows and columns as in any relational Database. Cassandra tables can have a single or compound primary key, in this article we will see how to create a table in Cassandra with single primary key and compound primary key.

To create a table one must have a keyspace existed in Cassandra, use keyspace in which the table has to be created.

cqlsh> use tbNext;
cqlsh:tbNext>

1) Create a column family or table in Cassandra with single primary key

To create a table in Cassandra with single primary key, one must follow the syntax written below:

CREATE TABLE users (
user_name varchar,
password varchar,
gender varchar,
session_token varchar,
state varchar,
birth_year bigint,
PRIMARY KEY (user_name));

Now to test if the table is created or not, supply following command:

cqlsh:tbNext> describe tables;

and you will see a tablen users created in tables list. How to see table structure in Cassandra To see a table structure, use following command:

cqlsh:tbNext> describe table users;

And you will see table structure as follows:

CREATE TABLE users (
user_name text,
birth_year bigint,
gender text,
password text,
session_token text,
state text,
PRIMARY KEY ((user_name))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};

2) Create a column family or table in Cassandra with compound primary key

A compound primary key is used, when we need to query the data on the basis of more than one column. Here is an example of creating a table in Cassandra with compound primary key:

CREATE TABLE student(
stuID int,
deptID int,
first_name varchar,
last_name varchar,
PRIMARY KEY (stuID , deptID));

You can see the structure of this created table with following command:

cqlsh:tbNext> describe table student;

Here primary key os made of stuID and deptID, stuID is the partitioned key that helps in replicating data rows on different nodes of the cluster. While all remaining keys of primary key composition acts as the clustering mechanism and ensures that data is stored in accending order. In this article we came to know, how to create a table or column family in Cassandra and what is single primary key and compound primary key column families.
  • By Techburps.com
  • Mar 22, 2015
  • Cassandra