无法将具有用户定义类型的Scala集存储在Cassandra中

时间:2018-07-11 10:06:16

标签: cassandra datastax-java-driver

我有以下型号

case class TagPartitionsInfo (
                               year:Int,
                               month:Int
                             )

case class TagPartitions(tag:String,
                         partition_info:Set[TagPartitionsInfo])

Cassandra表中的数据存储如下:

tag        | partition_info
------------+--------------------------------------------------
 javascript | {{year: 2018, month: 1}, {year: 2018, month: 2}}

在表格中插入数据时,出现以下错误

Value 1 of type class scala.collection.convert.Wrappers$SetWrapper does not correspond to any CQL3 type

在表中插入数据的代码是

def insertValues(tableName:String, model:TagPartitions):Insert = {
    QueryBuilder.insertInto(tableName).value("tag",model.tag)
      .value("partition_info",setAsJavaSet(model.partition_info))
      .ifNotExists(); 
  }

我在做什么错?在控制台中,我可以看到以下打印输出,显示我的数据正确inserting in table partitions_of_a_tag with partition key List(tag) and values TagPartitions(testtag,Set(TagPartitionsInfo(2018,6)))

表架构为

CREATE TABLE codingjedi.partitions_of_a_tag (
    tag text PRIMARY KEY,
    partition_info set<frozen<tag_partitions>>
)

tag_partitionsUDT类型的

{
   year bigint,
    month bigint
);

1 个答案:

答案 0 :(得分:0)

问题不是Set,而是UDTCassandra不知道如何存储UDT值。我的模型具有UDT的形状,但是我必须根据以下模型专门创建UDT

//get the definition of udt
 val partitionInfoType:UserType = session.getCluster().getMetadata.getKeyspace("myks").getUserType("tag_partitions")

//create udt value from model 
    //the logic below assumes that there is only one element in the set
    val partitionsInfo:UDTValue = partitionInfoType.newValue()
        .setLong("year",model.partition_info.head.year)
        .setLong("month",model.partition_info.head.month)


    QueryBuilder.insertInto(tableName).value("tag",model.tag)
      .value("partition_info",setAsJavaSet(Set(partitionsInfo)))