Jagveer Singh
Jagveer Singh

Reputation: 584

Connecting cassandra cluster through scala

I am new in both scala and cassandra . I know the connectivity of cassandra with java using hector . But I don't know how to connect cassandra through scala. I want a simple example for this.

Upvotes: 0

Views: 6265

Answers (4)

Atais
Atais

Reputation: 11285

Datastax Driver 3 Scala Integration

I have found some articles (example) and Maga library showing how you could integrate Java Driver better with Scala and it did not look hard.

The result is my own library that you can find on GitHub: https://github.com/atais/scassandra

It allows for seamless integration in Scala for both CQL queries and manipulating the ListenableFuture without mapping it into scala.Future.

implicit protected val session: com.datastax.driver.core.Session
implicit protected val executor: java.util.concurrent.Executor

val selectCQL: ListenableFuture[PreparedStatement] = cql"SELECT * FROM $table WHERE key = ?"
val result: ListenableFuture[ResultSet] = execute(selectCQL, "my-key")

result.map(rs => rs.one())
      .map(...)

Enjoy :)

Upvotes: 0

Magomed Abdurakhmanov
Magomed Abdurakhmanov

Reputation: 1934

I've been working on Scala wrapper of Java Driver to minimize boilerplate code. You could find it here: https://github.com/InnovaCo/binders-cassandra

Here is an example of class that works with some Cassandra DB:

class Db(session: com.datastax.driver.core.Session) {

  implicit val cache = new SessionQueryCache[PlainConverter](session)

  // class for binding input/output parameters
  case class User(userId: Int, name: String)

  def insertUser(user: User): Future[Unit] = cql"insert into users(userid, name) values (?, ?)".bind(user).execute

  // returns Future[Iterator[User]]
  def selectAllUsers: Future[Iterator[User]] = cql"select * from users".all[User]

  // if no user is found will throw NoRowsSelectedException
  def selectUser(userId: Int) = cql"select * from users where userId = $userId".one[User]

  // if no user is found will return None, otherwise Some(User)
  def selectUserIfFound(userId: Int) = cql"select * from users where userId = $userId".oneOption[User]
}

To use library in your playframework project, add this line to the build.sbt file:

libraryDependencies += "eu.inn" %% "binders-cassandra" % "0.2.0"

Upvotes: 2

ferk86
ferk86

Reputation: 2345

I am using the datastax java driver. It's development is still active on github. I looked at Hector earlier but it seemed dying. The doc here's helpful: http://www.datastax.com/documentation/developer/java-driver/1.0/webhelp/index.html#java-driver/quick_start/qsQuickstart_c.html. I translated the first example to scala. Also, look at the akka-cassandra example from typesafe activator. Cheers.

object Hello extends App {

  import com.datastax.driver.core.Cluster;
  import com.datastax.driver.core.Host;
  import com.datastax.driver.core.Metadata;
  import scala.collection.JavaConversions._

  var cluster: Cluster = null
  private var session: Session = null

  def connect(node: String) {
    cluster = Cluster.builder().addContactPoint(node).build()
    val metadata = cluster.getMetadata()
    printf("Connected to cluster: %s\n",
      metadata.getClusterName())
    metadata.getAllHosts() map {
      case host =>
        printf("Datatacenter: %s; Host: %s; Rack: %s\n",
          host.getDatacenter(), host.getAddress(), host.getRack())
    }
  }

  def close() {
    cluster.shutdown()
  }

  this.connect("127.0.0.1");
  this.close();
}

Upvotes: 5

Vidya
Vidya

Reputation: 30320

There were some Scala projects that arose to support Cassandra connectivity, including cassie by Twitter, but they all seemed to die off.

Since you know Hector, if you have the Hector jars in your classpath, you can simply use the Hector API in Scala if you prefer.

For example, borrowing from the documentation, you could just do this:

val myCluster = HFactory.getOrCreateCluster("test-cluster","localhost:9160")

or

val template = new ThriftColumnFamilyTemplate[String, String](ksp, columnFamily, StringSerializer.get(), StringSerializer.get())

I wrote this freehand, so the syntax might be off, but you get the idea.

Upvotes: 0

Related Questions