如何在Cassandra Datastax驱动程序中将Java集合转换为Scala

时间:2018-07-10 05:58:55

标签: scala cassandra datastax-java-driver

我的Cassandra表的模式是

id uuid PRIMARY KEY,
description text,
messages list<text>,
image list<blob>,
primary text,
tags set<text>,
title text,
more text

我能够从表中检索ResultSet,但是我不知道如何将其映射到模型中。我想将行建模为Scala class

case class Data (id: Option[UUID],
                              description: String,
                              messages: List[String],
                              image: Array[Byte], 
                              first: String,
                              tags: Set[String],
                              title: String,
                              more:String)

我知道函数Row.getString("column name")可以将text转换为String,但是我不知道该如何转换list<text>list<blob>和{ {1}}到set<text>中。

1 个答案:

答案 0 :(得分:1)

要从resultSet中提取集合并将其转换为scala集合,可以定义如下函数:-

 def convertToScalaSet(row: Row, columnName: String): Set[String] = 
  {

    val mayBeSet = Option(row.getSet(columnName, "String".getClass).toSet[String])

    mayBeSet match {
      case Some(set) if set.size > 0 => set
      case _ => Set[String]() //this case will cover both the possibilities of set being empty or none value
    }
  }

在类似的行上,您可以创建一个将转换为scala列表的函数

  def convertToScalaList(row: Row, columnName: String): List[String] = 
  {

    val mayBeList = Option(row.getList(columnName, "String".getClass).toList)

    mayBeList match {
      case Some(list) if list.size > 0 => list
      case _ => List[String]() //this case will cover both the possibilities of list being empty or none value
    }
  }  

然后,您可以在代码中按如下方式调用这些方法

  val row = resultSet.one()
  convertToScalaSet(row,"tags")
  convertToScalaList(row,"messages")