恐怕 Cassandra 不适合处理可变订单。 (请考虑使用 Redis 排序集)
话虽如此,您实际上可以使用类似 CAS 的语义(比较和设置)和轻量级事务来实现这一点,这将使您的更新速度慢 20 倍左右。
您还需要一个附加表,用于查找每个 bucket_id/photo_id 的当前 like_count。
create table yy (
bucket_id int,
photo_id int,
like_count int,
PRIMARY KEY((bucket_id,photo_id))
)
然后从 xx 执行轻量级事务删除,然后(如果成功)重新插入 xx 并更新到 yy:
一些伪代码:
//CAS loop (supposedly in a function of args: bucket_id, photo_id, username, new_score)
for (;;) {
//read current score (the assumption here is that the bucket_id/photo_id entry already exists in both xx and yy)
ResultSet rs1 = select like_count from yy where bucket_id = ? and photo_id = ?
int old_score = rs1.one().getInt(0)
//same score don't do anything
if (new_score == old_score) break;
//attempt to delete using light-weight transaction (note usage of IF EXISTS)
ResultSet r2 = delete from xx where bucket_id = ? and photo_id = ? and like_count = old_score IF EXISTS
if (rs2.one().getBool(0)) {
//if delete was successful, reinsert with the new score
insert bucket_id, photo_id, photo_id, username, like_count into xx values (?, ?, ?, new_score)
//update lookup table
update yy set like_count = new_score where bucket_id = ? and photo_id = ?
//we are done!
break;
}
//delete was not successful, someone already updated the score
//try again in a next CAS iteration
}