Latest Post

Wednesday, 21 December 2016

How to Use Lists Collections Data Type in Cassandra Database

Lists Collections Data Type
A list is a collection of non-unique values where elements are ordered by there position in the list. 
You can define and insert a list with below syntax.

Syntax: - LIST '<' cql_type '>'

Example:-
cqlsh:payroll> CREATE TABLE plays (
           ...     id text PRIMARY KEY,
           ...     game text,
           ...     players int,
           ...     scores list<int> // A list of integers
           ... );
cqlsh:payroll>
cqlsh:payroll> INSERT INTO plays (id, game, players, scores)
           ...            VALUES ('123-abcd', 'tennis', 2, [25, 10,18]);
cqlsh:payroll> Select * from plays;

 id       | game   | players | scores
----------+--------+---------+--------------
 123-abcd | tennis |       2 | [25, 10, 18]

(1 rows)
cqlsh:payroll>// Replace the existing list entirely
cqlsh:payroll> UPDATE plays SET scores = [ 3, 9, 4] WHERE id = '123-abcd';
cqlsh:payroll> select * from plays;

 id       | game   | players | scores
----------+--------+---------+--------------
 123-abcd | tennis |       2 | [3, 9, 4]
 

(3 rows)

Appending and prepending values to a list:
cqlsh:payroll> select * from plays;

 id       | game   | players | scores
----------+--------+---------+--------------
 123-abcd | tennis |       2 | [25, 10, 18]

(1 rows)
cqlsh:payroll> UPDATE plays SET players = 5, scores = scores + [ 14, 21 ] WHERE id = '123-abcd';
cqlsh:payroll> UPDATE plays SET players = 6, scores = [ 3 ] + scores WHERE id = '123-abcd';
cqlsh:payroll> select * from plays;

 id       | game   | players | scores
----------+--------+---------+-------------------------
 123-abcd | tennis |       6 | [3, 25, 10, 18, 14, 21]

(1 rows)

Setting the value at a particular position in the list:
cqlsh:payroll> UPDATE plays SET scores[1] = 7 WHERE id = '123-abcd';
cqlsh:payroll> Select * from plays;

 id       | game   | players | scores
----------+--------+---------+------------------------
 123-abcd | tennis |       6 | [3, 7, 10, 18, 14, 21]

(1 rows)
Removing an element by its position in the list:
cqlsh:payroll> DELETE scores[1] FROM plays WHERE id = '123-abcd';
cqlsh:payroll> Select * from plays ;

 id       | game   | players | scores
----------+--------+---------+---------------------
 123-abcd | tennis |       6 | [3, 10, 18, 14, 21]

(1 rows)

Government Jobs