【问题标题】:How to Implement Cassandra Counter Columns with phantom-dsl?如何使用 phantom-dsl 实现 Cassandra 计数器列?
【发布时间】:2016-05-16 22:49:14
【问题描述】:

这是对这个问题的扩展:

How to increment Cassandra Counter Column with phantom-dsl?

here 也有人问过这个问题。

Thiagos example这两个表中; 'songs' 和 'songs_by_artist' 都具有相同的行但具有不同的分区(主键/集群列)

CREATE TABLE test.songs (
    song_id timeuuid PRIMARY KEY,
    album text,
    artist text,
    title text
);

CREATE TABLE test.songs_by_artist (
    artist text,
    song_id timeuuid,
    album text,
    title text,
    PRIMARY KEY (artist, song_id)
) WITH CLUSTERING ORDER BY (song_id ASC);

这意味着在 SongsService 内的两个表中插入、更新和删除都适用于相同的基本数据/行。

例如,您将如何拥有一个表,例如“artist_songs_counts”,其中包含“song_id”(K)和“num_songs”(++)列,并确保“SongsService”为每个表添加相应的行; 'songs' & 'songs_by_artist' & 'artist_songs_counts'(行数不同,但信息应关联,例如艺术家信息)。

CREATE TABLE test.artist_songs_counts (
    artist text PRIMARY KEY,
    num_songs counter);

【问题讨论】:

  • @flavian 这可能是你的另一个...

标签: scala cassandra-2.0 phantom-dsl


【解决方案1】:

SongsService 扩展 ProductionDatabaseProvider 为您提供一个名为 database 的对象,您可以在其中访问某个数据库下的表:

/**
    * Find songs by Id
    * @param id
    * @return
    */
  def getSongById(id: UUID): Future[Option[Song]] = {
    database.songsModel.getBySongId(id)
  }

或者更好的是,同时处理两个表:

  /**
   * Save a song in both tables
   *
   * @param songs
   * @return
   */
  def saveOrUpdate(songs: Song): Future[ResultSet] = {
    for {
      byId <- database.songsModel.store(songs)
      byArtist <- database.songsByArtistsModel.store(songs)
    } yield byArtist
  }

由于您可以通过database 对象访问属于特定数据库的所有表,因此我将通过以下方式为艺术家实现计数器:

def increment(artist: String): Future[ResultSet] = {
  update
    .where(_.artist eqs artist)
    .modify(_.numSongs += 1)
    .future()
}

那么saveOrUpdate方法可以写成如下:

def saveOrUpdate(song: Song): Future[ResultSet] = {
    for {
      byId <- database.songsModel.store(songs)
      byArtist <- database.songsByArtistsModel.store(songs)
      counter <- database.artistSongsCounter.increment(song.artist)
    } yield byArtist
  }

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 2014-12-02
    • 2016-04-10
    • 1970-01-01
    • 2017-02-19
    • 2016-11-27
    • 2016-09-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多