使用Phantom Scala DSL在Cassandra中创建模式

时间:2016-02-29 04:47:30

标签: scala phantom-dsl

我写了这段代码

case class User(id: Int, gender: String, age: Int, occupation: String, zipCode: String)

object Defaults {
  val hosts = Seq("172.17.0.9")
  val Connector = ContactPoints(hosts).keySpace("Movies")
}

class MyDatabase(val keyspace: KeySpaceDef) extends com.websudos.phantom.db.DatabaseImpl(keyspace) {
  object users extends Users with keyspace.Connector
}

object MyDatabase extends MyDatabase(Defaults.Connector)
class Users extends CassandraTable[Users, User] {
  object id extends IntColumn(this) with PartitionKey[Int]
  object age extends IntColumn(this) with Index[Int]
  object gender extends StringColumn(this) with Index[String]
  object occupation extends StringColumn(this) with Index[String]
  object zipCode extends StringColumn(this) with Index[String]

  def fromRow(row: Row) : User = {
    User(
      row(id),
      row(gender),
      row(age),
      row(occupation),
      row(zipCode)
    )
  }
}

object Users extends Users with RootConnector {
  def store(user: User) : Future[ResultSet] = {
    insert
      .value(_.id, user.id)
      .value(_.gender, user.gender)
      .value(_.age, user.age)
      .value(_.occupation, user.occupation)
      .value(_.zipCode, user.zipCode)
      .consistencyLevel_=(ConsistencyLevel.ALL)
      .future()
  }

  def getById(id: Int) : Future[Option[User]] = {
    select.where(_.id eqs id).one()
  }
}

但是当我编译它时,我得到一个错误。

Object creation impossible, since member session: Session in 
com.websudos.phantom.connectors.RootConnector is not defined; member space: 
KeySpace in com.websudos.phantom.connectors.RootConnector is not defined.

我也看到了其他错误

[error] /Users/U/MyProjects/src/main/scala-2.11/com/abhi/MovieLensDataPreperation.scala:180: com.websudos.phantom.dsl.Row does not take parameters
[error]       row(id),
[error]          ^
[error] /Users/U/MyProjects/src/main/scala-2.11/com/abhi/MovieLensDataPreperation.scala:181: com.websudos.phantom.dsl.Row does not take parameters
[error]       row(gender),
[error]          ^
[error] /Users/U/MyProjects/src/main/scala-2.11/com/abhi/MovieLensDataPreperation.scala:182: com.websudos.phantom.dsl.Row does not take parameters
[error]       row(age),
[error]          ^
[error] /Users/U/MyProjects/src/main/scala-2.11/com/abhi/MovieLensDataPreperation.scala:183: com.websudos.phantom.dsl.Row does not take parameters
[error]       row(occupation),
[error]          ^
[error] /Users/U/MyProjects/src/main/scala-2.11/com/abhi/MovieLensDataPreperation.scala:184: com.websudos.phantom.dsl.Row does not take parameters
[error]       row(zipCode)
[error]          ^
[error] 5 errors found
[error] (compile:compileIncremental) Compilation failed

1 个答案:

答案 0 :(得分:1)

由于您已将ID,性别,年龄等定义为列,因此您应该从行中提取值,如下所示:

def fromRow(row: Row) : User = {
  User(
    id(row),
    gender(row),
    age(row),
    occupation(row),
    zipCode(row)
  )
}