How to setup Cassandra Phantom driver for Scala


Phantom is a high performance Scala DSL for Apache Cassandra and now the leading tool for integrating Cassandra in the Scala Eco-system. So, if you are planning on using Cassandra with Scala, phantom is the weapon of choice.

It has slowly but surely grown to become an established Scala framework and through its high focus on:

  • Scala type system to mimic CQL and translate them to type safe queries.
  • Translates Cassandra restrictions to compile time errors.
  • Ease of use and quality coding.
  • Reducing code and boilerplate by at least 90%.
  • One can map and flatMap their way to glory with extremely simple one liners.
  • Simple interface for accessing data and also creating column families while still being based on the datastax driver.

This is great as it means that your code remains very readable, but you are also still free to use any advanced features which may not have found their way into the library yet.

Phantom offers support for both Scala 2.10 and 2.11.

Getting started with Phantom:

  • Integrate phantom in your project by adding below resolvers and dependencies:
resolvers ++= Seq(
  Resolver.bintrayRepo("websudos", "oss-releases"),
  "Sonatype releases"                at "https://oss.sonatype.org/content/repositories/releases"
)
libraryDependencies ++= {
  val phantomV = "1.16.0"
  Seq(
    "com.websudos"        %%  "phantom-dsl"               % phantomV,
    "com.websudos"        %%  "phantom-testkit"           % phantomV,
    "com.websudos"        %%  "phantom-connectors"        % phantomV,
     )
}
  • Connect to a Cassandra cluster by adding below configurations:
cassandra {
  port: 9042

  hosts: [
    "127.0.0.1"
  ]

  keyspace: "KEYSPACE"
}
object CassandraConnectionUri {

  private val cassandraConfig = ConfigFactory.load.getConfig("cassandra")
  val port = cassandraConfig.getInt("port")
  val hosts = cassandraConfig.getStringList("hosts").toList
  val keyspace = cassandraConfig.getString("keyspace")
} 

trait CassandraProvider extends SessionProvider {

  val config = ConfigFactory.load()
  implicit val space: KeySpace = Connector.keyspace

  val cluster = Connector.cluster

  override implicit lazy val session: Session = Connector.session
}

object Connector {

  val keyspace: KeySpace = KeySpace(CassandraConnectionUri.keyspace)
  
  val cluster = new Cluster.Builder().
    addContactPoints(CassandraConnectionUri.hosts.toArray: _*).
    withPort(CassandraConnectionUri.port).
    withQueryOptions(new QueryOptions().build

  val session: Session = cluster.connect

}
  • Create table and map case class:
CREATE TABLE IF NOT EXISTS EMPLOYEE (
 id int,
 email String,
 name String,
 age: Int,
 PRIMARY KEY (id)
);

Let’s assume we are modeling the CQL schema for a case class that looks like this:

case class Employee(
 id: Long,
 email: String,
 name: String,
 age: Int
)
  • Here’s how the Phantom DSL equivalent looks like:
import scala.concurrent.Future
import com.websudos.phantom.dsl._

class Employees extends CassandraTable[Employees, Employee] {

  object id extends LongColumn(this) with PartitionKey[Long]
  object email extends StringColumn(this)
  object name extends StringColumn(this)
  object age extends IntColumn(this)

  def fromRow(row: Row): Employee = {
    Employee(
      id(row),
      email(row),
      name(row),
      age(row)
    )
  }
}

class EmployeeRepository @Inject()(emp: Employees) extends CassandraProvider {

  def store(emp: Employee): Future[ResultSet] = {
    insert.value(_.id, emp.id).value(_.email, emp.email)
      .value(_.name, emp.name)
      .value(_.age, emp.age)
      .consistencyLevel_=(ConsistencyLevel.ALL)
      .future()
  }

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

}

This is how you can integrate Phantom driver for Cassandra in your Scala projects.

Hope you liked it!!

This entry was posted in Cassandra, Scala and tagged , , , , , . Bookmark the permalink.

5 Responses to How to setup Cassandra Phantom driver for Scala

  1. Flavian says:

    As the framework author, I’d like to suggest a few small improvements. The CassandraProvider traits you’ve implemented are not optimal and introduce a lot of race conditions. Phantom already has a powerful mechanism to help you with that.
    For anyone looking for a proper tutorial, try this instead: http://outworkers.com/blog/post/a-series-on-phantom-part-1-getting-started-with-phantom

  2. Flavian says:

    This tutorial is not adequate, and our license explicitly prohibits publishing educational material on phantom without our written consent, specifically to prevent misinterpretations of the phantom API from spreading.

    We would be most grateful in your cooperation to update this post accordingly, we would happily help you get it right.

    Regards.

  3. It’s a pleasure to receive updates from you. I would like to learn and improve the content here.
    Please let us know your suggestions !!

  4. Flavian says:

    Hi,

    Thank you for your reply.

    Have a look here for details on how to connect to Cassandra using phantom, a lot of the primitives you are trying to build are already implemented with much more features and available by default in phantom.

    Hope this helps!

    Regards.

  5. Pingback: How to setup Cassandra Phantom driver for Scala – prashantgoel6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s