2016-05-15 2 views
1

Есть ли примеры реализации операции счетчика в phantom-dsl?Как увеличить счетчик столбцов Cassandra с помощью phantom-dsl?

Проверили:

http://outworkers.com/blog/post/a-series-on-cassandra-part-3-advanced-features

https://github.com/outworkers/phantom/wiki/Counter-columns

https://github.com/outworkers/phantom/blob/develop/phantom-dsl/src/test/scala/com/websudos/phantom/tables/CounterTableTest.scala

Любопытное ищет версию фантомным Dsl этой информации:

https://github.com/Netflix/astyanax/wiki/Working-with-counter-columns


Ниже приводится частичная реализация. Она поднялась на два вопроса:

  1. Я не знаю, как принимать значения из приложения и осуществить операцию приращения счетчика в колонке счетчика внутри счетчика таблицы.

  2. Как обновить строки в таблицах, относящихся к той же записи, где таблицы имеют различное количество строк и ключей.

В thiagos example две таблицы; 'songs' & 'songs_by_artist' имеют одинаковые строки, но с разными разделами (первичные ключи/столбцы кластеризации)

Я не уверен, как в phantom-dsl будут обновляться строки, относящиеся к тем же элементам, записи "&" record_transaction_counts "таблицы ниже.

например.

RecordTransactionCounts.{hash, time} relates to Records.{hash, time}


case class Record(hash: String, 
       size: Int, 
       time: Long, 
       difficulty: Float) 


sealed class RecordsModel extends CassandraTable[RecordsModel, Record] { 

    override def fromRow(row: Row): Record = { 
    Record(
     hash(row), 
     size(row), 
     time(row), 
     difficulty(row) 
    ) 
    } 

    object hash extends StringColumn(this) with PartitionKey[String] 

    object size extends IntColumn(this) 

    object time extends LongColumn(this) 

    object difficulty extends FloatColumn(this) 

} 

abstract class ConcreteRecordsModel extends RecordsModel with RootConnector { 

    override val tableName = "records" 

    def insertNew(block: Record): Future[ResultSet] = insertNewRecord(block).future() 

    def insertNewRecord(r: Record) = { 
    insert 
     .value(_.hash, r.hash) 
     .value(_.size, r.size) 
     .value(_.time, r.time) 
     .value(_.difficulty, r.difficulty) 
    } 

} 

case class RecordTransactionCounts(hash: String, time: Long, num_transactions: Long) 

class RecordTransactionCountsModel extends CassandraTable[RecordTransactionCountsModel, RecordTransactionCounts] { 

    override def tableName: String = "record_transaction_counts" 

    object hash extends StringColumn(this) with PartitionKey[String] 

    object time extends LongColumn(this) with ClusteringOrder[Long] 

    object num_transactions extends CounterColumn(this) 

    override def fromRow(r: Row): RecordTransactionCounts = { 
    RecordTransactionCounts(
     hash(r), 
     time(r), 
     num_transactions(r) 
    ) 
    } 

} 

abstract class ConcreteRecordTransactionCountsModel extends TransactionCountsModel with RootConnector { 

    def createTable(): Future[ResultSet] = { 
    create.ifNotExists().future() 
    } 

    def store(count: RecordTransactionCounts): Future[ResultSet] = { 
    insert 
     .value(_.hash, count.hash) 
     .value(_.time, count.time) 
     .value(_.num_transactions, count.num_transactions) 
     .future() 
    } 

    def getCount(hash: String): Future[Option[Long]] = { 
    select(_.count).where(_.hash eqs hash).one() 
    } 
} 

class Database(val keyspace: KeySpaceDef) extends DatabaseImpl(keyspace) { 

    def insertRecordTransactionCounts(tc: RecordTransactionCounts) = { 
    Batch.logged 
     .add(ChainDatabase.tc.store(tc)) 
     .future() 
    } 

    object tc extends ConcreteRecordTransactionCountsModel with keyspace.Connector 

} 

object ChainDatabase extends Database(Config.keySpaceDefinition) 
+0

@flavian это может быть тот, который вы, возможно, сможете уточнить ... –

ответ

3

Как предложил Тьяго, вы можете использовать += или в качестве альтернативы оператору -= для уменьшения значения счетчика. Вы также можете использовать методы increment или decrement для достижения того же.

def increment(count: RecordTransactionCounts): Future[ResultSet] = { 
    update 
    .where(_.hash eqs count.hash) 
    .and(_.time eqs count.time) 
    .modify(_.num_transactions += count.num_transactions) 
    .future() 
} 
// or 
def increment(count: RecordTransactionCounts): Future[ResultSet] = { 
    update 
    .where(_.hash eqs count.hash) 
    .and(_.time eqs count.time) 
    .modify(_.num_transactions increment count.num_transactions) 
    .future() 
} 

Для уменьшения, просто замените строки с:

... 
    .modify(_.num_transactions -= count.num_transactions) 
    // or 
    .modify(_.num_transactions decrement count.num_transactions) 

Прежде чем полагаться слишком много на прилавках, вы должны также Google немного, чтобы выяснить, какие проблемы другие люди столкнулись.

2

Для того, чтобы использовать CounterColumn в фантомной-DSL, вы должны использовать следующий шаблон для увеличения его:

.modify(_.myCounterColumn += 1) //or whatever value you want to increment 

в вашем ConcreteRecordTransactionCountsModel вы можете изменить ваш магазин, чтобы увеличить счетчик таким образом:

def increment(count: RecordTransactionCounts): Future[ResultSet] = { 
    update 
    .where(_.hash eqs count.hash) 
    .and(_.time eqs count.time) 
    .modify(_.num_transactions += count.num_transactions) 
    .future() 
} 

Я попытаюсь обновить свой github еще несколькими примерами, с которыми я работал раньше. Также, если у вас есть какие-либо предложения, пожалуйста, откройте билет, и я сделаю это.

Смежные вопросы