scalacassandraphantom-dsl

Cassandra insert without batch


I'm learning to use the PhantomDSL driver (Scala) for Cassandra. There's an excellent sample here: https://github.com/iamthiago/cassandra-phantom

For example to add a Song to Cassandra:

 def saveOrUpdate(songs: Song): Future[ResultSet] = {
    Batch.logged
      .add(SongsModel.store(songs))
      .add(SongsByArtistsModel.store(songs))
      .future()
  }

To simplify I'm going to remove using SongsByArtistsModel:

 def saveOrUpdate(songs: Song): Future[ResultSet] = {
    Batch.logged
      .add(SongsModel.store(songs))
      .future()
  }

I have two questions: 1- How do I know if the operation has been successfully or has been an error? 2- I've been reading that using Batch isn't good in terms of performance. What's the code for inserting without using Batch?

Sorry if these are dummy questions, I'm just starting.


Solution

  • 1- How do I know if the operation has been successfully or has been an error?

    For this one, ideally, you would be checking if the Future returns success or failure. You can use a .transform on your Future in case you want to return something or .onComplete if you don't care about returning anything, then, pattern matching between Success and Failure, and decide what to do on each case. See the example below.

    save(song).transform {
       case Success(value) => //handle success case
       case Failure(exception) => //handle failure case
    }
    

    2- I've been reading that using Batch isn't good in terms of performance. What's the code for inserting without using Batch

    Batch operation in Cassandra is recommended in case you want to achieve atomicity. So you can combine multiple operations and that's exactly what I tried to do in my example because I want both tables to be consistent. Now, if you want to work with only one table you could write your method as follow:

    def save(song: Song): Future[ResultSet] = {
       SongsModel
          .store(song)
          .future()
    }