无法将集合的值映射到模型中

时间:2018-07-11 06:25:34

标签: 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}}

查询表时,我尝试从TagPartitions开始创建ResultSet,但是我的代码未编译。问题似乎是我从该行提取Set的方式:

 TagPartitions(row.getString("tag"),row.getSet[TagPartitionsInfo]("partition_info",TagPartitionsInfo.getClass))

错误是Cannot resolve symbol getSet

我也尝试过row.getSet("partition_info",TagPartitionsInfo.getClass),但随后看到错误Type mismatch, expected Set[TagPartitionsInfo], actual util.Set[Any]

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

这有效。在使用UDT时,我必须使用UDTTypeUDTValueUDT转换为模型

  val tag = row.getString("tag")
val partitionInfoType:UserType = session.getCluster().getMetadata.getKeyspace("codingjedi").getUserType("tag_partitions")

//create value
//the logic below assumes that there is only one element in the set
val partitionsInfo = 
row.getSet("partition_info",partitionInfoType.newValue().getClass)

println("tag is "+tag +" and partition info converted to UDTValue: "+partitionsInfo)
val udtValueScalaSet:Set[UDTValue] = partitionsInfo.asScala.toSet

//convert Set[UDTValue] = Set[TagPartitionsInfo]
val partitionInfoSet:Set[TagPartitionsInfo] = udtValueScalaSet.map(partition=>TagPartitionsInfo(partition.getLong("year"),partition.getLong("month")))
 return TagPartitions(tag,partitionInfoSet)