Thursday 30 January 2020

Cassandra: Get Data from table as JSON


With SELECT and JSON keywords, you can get each row as JSON encoded map.

Example
SELECT JSON * FROM cassandratutorial.employee;
SELECT JSON id FROM cassandratutorial.employee;
SELECT JSON age, firstname FROM cassandratutorial.employee;

cqlsh> CREATE KEYSPACE cassandratutorial WITH REPLICATION = 
   ... { 
   ...   'class' : 'SimpleStrategy', 
   ...   'replication_factor' : 1 
   ... };
cqlsh> 
cqlsh> CREATE TABLE IF NOT EXISTS cassandratutorial.employee (
   ...   id INT PRIMARY KEY, 
   ...   firstName VARCHAR,
   ...   lastName VARCHAR,
   ...   age int
   ... );
cqlsh> 
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 1, "firstName" : "Krishna", "lastName" : "Gurram", "age" : 30}';
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 2, "firstName" : "Ram", "lastName" : "Gurram", "age" : 31}' ;
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 3, "firstName" : "Vijay", "lastName" : "Ponnam", "age" : 45}';
cqlsh> INSERT INTO cassandratutorial.employee JSON '{"id" : 4, "firstName" : "Chitra", "lastName" : "Rajan", "age" : 45}';
cqlsh> 
cqlsh> SELECT JSON * FROM cassandratutorial.employee;

 [json]
--------------------------------------------------------------------
 {"id": 1, "age": 30, "firstname": "Krishna", "lastname": "Gurram"}
     {"id": 2, "age": 31, "firstname": "Ram", "lastname": "Gurram"}
   {"id": 4, "age": 45, "firstname": "Chitra", "lastname": "Rajan"}
   {"id": 3, "age": 45, "firstname": "Vijay", "lastname": "Ponnam"}

(4 rows)
cqlsh> 
cqlsh> SELECT JSON id FROM cassandratutorial.employee;

 [json]
-----------
 {"id": 1}
 {"id": 2}
 {"id": 4}
 {"id": 3}

(4 rows)
cqlsh> 
cqlsh> SELECT JSON age, firstname FROM cassandratutorial.employee;

 [json]
-------------------------------------
 {"age": 30, "firstname": "Krishna"}
     {"age": 31, "firstname": "Ram"}
  {"age": 45, "firstname": "Chitra"}
   {"age": 45, "firstname": "Vijay"}

(4 rows)
cqlsh>





Previous                                                    Next                                                    Home

No comments:

Post a Comment