How do you nest a UDT inside another UDT in Cassandra?

710 Views Asked by At

I have created the following user defined types (UDT) in cassandra :

CREATE TYPE keyspace.location (
    latitude text,
    longitude text,
    accuracy text,
    address text
);

CREATE TYPE keyspace.person (
    name text,
    contact_no text,
    alternate_contact text
);

and I want to use these to create another UDT

CREATE TYPE keyspace.pinpoint(
    user <person>,
    location <location>
);
2

There are 2 best solutions below

0
Erick Ramirez On BEST ANSWER

You can nest UDTs by simply specifying your UDT as the type within another UDT in this manner:

CREATE TYPE keyspace.pinpoint (
    user person,
    location location
);

You don't enclose them in <> brackets because those are used for collections.

As a side note, I personally wouldn't nest UDTs unless you have no other option. UDTs are not as flexible as native columns. Inserting or updating data in a nested UDT can get very complicated and hard to maintain.

Whenever possible, try to use generic table definitions. For example instead of defining the type pinpoint, try to use a table with native column types and clustered rows. Cheers!

0
Alex Ott On

You need to declare these nested UDTs as frozen<UDTName>, like:

CREATE TYPE keyspace.pinpoint(
    user frozen<person>,
    location frozen<location>
);

But this means that you won't be able to update their individual fields - you'll able only update the whole field, with complete UDT instance, for example, complete user or location.