Ostreva
Ostreva

Reputation: 13

Cassandra select all keys from map

I am trying to select keys from the courses map in the student table below

CREATE TABLE student (
   studentid TEXT,
   courses map<TEXT, TEXT>,
   PRIMARY KEY (studentid)      
);

With this data inserted

UPDATE student SET courses = courses + { 'bio101': 'Intro to Bio'} where studentid='xyz' ;
UPDATE student SET courses = courses + { 'bio102': 'Advanced Bio'} where studentid='xyz' ;
UPDATE student SET courses = courses + { 'chem101': 'Intro to Chem'} where studentid='xyz' ;

I would like to select only the keys in the courses map. So

courseId
--------
'bio101'
'bio102'
'chem101'

I've tried variations of

select courses from student where studentid='xyz';

but I can't seem to select just that column.

Upvotes: 1

Views: 453

Answers (1)

Aleh Birulia
Aleh Birulia

Reputation: 352

You can try to use UDF for this.

CREATE OR REPLACE FUNCTION keys (input Map<Text, Text>) 
RETURNS NULL ON NULL INPUT 
RETURNS Set<Text> 
LANGUAGE java AS 'return input.keySet();';

You have to enable UDF because it disabled by default. Find enable_user_defined_functions in cassandra.yaml and replace false with true. Restart your Cassandra.

Change a little your query.

select keys(courses) from student where studentid='xyz';

Upvotes: 2

Related Questions