Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array of objects in Cassandra

In cassandra DB I am planning to store an array-of-object. What is the best way to do that. object mapping to Data mapping with model class in java.

Class Test{
   @Column(name = "id")
   int id,
   @Column(name = "name")
   String name,
   Address[] address

 class Address{
   String add1,
   String city,
   String state 
  }
}

Should I put all(id, name, add1, city, state) in one table by adding columns to same keyspace with add1, city, state also? or add new table for address Or any other options..

I have tried to add TYPE But throwing error as: "Error from server: code=2200 [Invalid query] message="A user type cannot contain non-frozen UDTs" From the error and type syntax I have used keyword 'frozen', but not luck. Altering table also gives similar Error something like : "mismatched input 'frozen' expecting EOF"

Also, What if I have to save column of type 'String[ ]' As it is not custom type like Address[]. it is of String or text.? Do we need to just add alter statement? if so how it looks like

like image 700
Nomad Avatar asked Mar 16 '18 18:03

Nomad


People also ask

How do you store objects in Cassandra?

For your case, first, you need to create a UDT(user defined type) in Cassandra. Create TYPE address( add1 text, city text, state text ); Then create a table including this UDT. Create table Test( id int, name text, address list<frozen<address>>, primary key(id) );

Does Cassandra support nested data?

One of the popular features of MongoDB is the ability to store arbitrarily nested objects and be able to index on any nested field. In this post I will show how to store nested objects in Cassandra using composite columns.

Which Cassandra collection is used to store a grouping of elements that do not have to be unique and can store the elements in a specific order?

1. SET: A Set is a collection data where we can store a group of elements such that a user can have multiple Email address then to stored such type of data we used set collection data type which returns sorted elements when querying.


1 Answers

For your case, first, you need to create a UDT(user defined type) in Cassandra.

Create TYPE address(
   add1 text,
   city text,
   state text
);

Then create a table including this UDT.

Create table Test(
   id int,
   name text,
   address list<frozen<address>>,
   primary key(id)
);

If you want to know more about UTD and the usages, visit following links:

  • Using a user-defined type
  • Collection type (List, Set, Map)

EDIT:

Also, What if I have to save column of type 'String[ ]' As it is not custom type like Address[]. it is of String or text.? Do we need to just add alter statement? if so how it looks like

Answer: Alter table test add stringarr list<text> Check this links to get more idea about cassandra data types: CQL data types

like image 90
MD Ruhul Amin Avatar answered Sep 20 '22 21:09

MD Ruhul Amin