Search code examples
databasecassandracqluser-defined-types

Inserting data into user defined type in Cassandra


I am having trouble inserting JSON and updating data to my Cassandra table.

I have a table with the following structure:

CREATE TYPE keyspace.connected_hw (
    connected_element text,
    support_list frozen<list<text>>
);

CREATE TABLE keyspace.sample_table (
    id text,
    name text,
    connected_items frozen<keyspace.connected_hw>
)

My insert script looks like this :

INSERT INTO keyspace.sample_table JSON '
  {
    "id": "12345",
    "name": "object 1",
    "connected_items": [
      {
        "connected_element": "56789",
        "support_list": ""
      }
    ]
  }

'

After I run this, I get the following error :

Error decoding JSON value for connected_items: Expected a map, but got a ArrayList :

I tried to insert the other fields without the 'connected_items" list first, then updating it afterwards :

INSERT INTO keyspace.sample_table JSON '
  {
    "id": "12345",
    "name": "object 1",
  }

'

This works until I try to update 'connected_items' with

UPDATE keyspace.sample_table
SET connected_items = [{connected_element:'56789',support_list:['type1','type2']}] 
where id='12345'

After running this I get the following error :

InvalidQueryException: Invalid list literal for connected_items of type frozen<connected_hw>

Solution

  • You are declaring connected_items as type connected_hw but you are inserting value as list of 'connected_hw ' and also support_list is a list of text not just text

    You Either change your insert/update format like below :

    INSERT INTO sample_table JSON '{"id": "12345", "name": "object 1", "connected_items": { "connected_element": "56789", "support_list": ["a","b"] } }' ;
    

    And

    UPDATE sample_table SET connected_items = {connected_element:'56789',support_list:['type1','type2']}  where id='12345' ;
    

    Or Change the type of connected_items to list of connected_hw

    ALTER TABLE sample_table DROP connected_items ;
    ALTER TABLE sample_table ADD connected_items list<frozen <connected_hw>>;