Getting Started with ScalaSession

Using a ScalaSession follows the same general rules as creating the Java driver’s Session.

import com.datastax.driver.core.Cluster

val cluster = Cluster.builder.addContactPoint("localhost").build()

Characteristics

  • PreparedStatement caching
  • acts on a single keyspace
  • can optionally create a keyspace on instantiation
  • can pick up Java Session implicitly
  • provides an execute, which blocks for the result, and executeAsync, which returns a Future of the result

The ScalaSession itself is a class that you must keep around, much like you would a Cassandra Java Session. This is because the ScalaSession caches PreparedStatements from every executed command, so if you are calling the same command multiple times, it will use an existing PreparedStatement instead of generating a new statement every time.

scala> import com.datastax.driver.core.Session, com.weather.scalacass.ScalaSession
import com.datastax.driver.core.Session
import com.weather.scalacass.ScalaSession

scala> implicit val session: Session = cluster.connect()
session: com.datastax.driver.core.Session = com.datastax.driver.core.SessionManager@7396e0f8

scala> val sSession: ScalaSession = ScalaSession("mykeyspace") // picks up session implicitly
sSession: com.weather.scalacass.ScalaSession = ScalaSession(mykeyspace)

If the keyspace has not been created yet (for instance, during testing), you can create it using createKeyspace and passing in parameters included after the WITH statement:

scala> val createStatement = sSession.createKeyspace("replication = {'class':'SimpleStrategy', 'replication_factor' : 3}")
createStatement: com.weather.scalacass.scsession.SCCreateKeyspaceStatement = SCCreateKeyspaceStatement(CREATE KEYSPACE mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3})

scala> createStatement.execute()
res0: com.weather.scalacass.Result[com.datastax.driver.core.ResultSet] = Right(ResultSet[ exhausted: true, Columns[]])

Additionally, you can specify IF NOT EXISTS using the ifNotExists builder

scala> val createStatementIfNotExists = createStatement.ifNotExists
createStatementIfNotExists: com.weather.scalacass.scsession.SCCreateKeyspaceStatement = SCCreateKeyspaceStatement(CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3})

scala> val result = createStatementIfNotExists.execute()
result: com.weather.scalacass.Result[com.datastax.driver.core.ResultSet] = Right(ResultSet[ exhausted: true, Columns[]])

Finally, you can drop the keyspace if you are done using it, although this will render the ScalaSession unusable

scala> sSession.dropKeyspace.execute()
res1: com.weather.scalacass.Result[com.datastax.driver.core.ResultSet] = Right(ResultSet[ exhausted: true, Columns[]])