get column position

2019-03-04 05:28发布

问题:

In CassandraDB, using an ordered column family. I know you can get slices, but can you get the position. For example, in this datamodel I save scores like this:

"Scores":
{
   "1000": "bob, lucas",
   "900": "tim"
   "800": "mario"
}

Is it possible, knowing that the user has a score of "900" and his nick is "tim", to know that he is at position 2 of the ordered column family?

回答1:

Cassandra does not provide this functionality out of the box, but you could implement this yourself using three separate CFs. Consider this scenario:

"Scores":
{
   "1000": "bob, lucas"
   "900": "tim"
   "800": "mario"
}

"PlayerScores":
{
   "bob": "1000"
   "lucas": "1000"
   "tim": "900"
   "mario": "800"
}

"ScoreTotals":
{
   "1000": 
   {
      "1000":2
   }
   "900": 
   {
      "900":1
   }
   "800": 
   {
      "800":1
   }
}

The ScoreTotals CF would be used with counter columns to increment/decrement the value each time a user achieves that score. If you have additional granularity in your scores (like 910 vs an even 900) you can consider the keys as buckets with column names as specific scores. PlayerScores obviously exists so you can query a score for a player.

You can then determine ranking by simply summing the totals of all scores greater than that of the player. Since scores are stored in column names, you can use a standard slice query to get your range without needing to use an order-preserving partitioner (which has some negative side effects).