rethinkdbrethinkdb-javascript

How do I get the rank / row number for a row?


Is there a way to get the row numbers (rank) for a filtered set and append the row number to the result?

An example scenario would be that I have a table with records like:

[ 
  { points: 123, name: 'Glenn' },
  { points: 948, name: 'Bob' },
  { points: 22, name: 'Sarah' }
]

In the above table there are hundreds of thousands of rows, and I want to be able to rank all records based on a condition like points descending and then return a subset of the rows (using a filter) with their rank value included in the result like this:

[ { points: 123, name: 'Glenn', rank: 2 }]

Solution

  • You should use the offsetsOf function

    r.table('users') .orderBy({index: 'points'}) .offsetsOf(r.row('user_id').eq(yourUserId)) .run(conn, callback)

    Command Reference: http://rethinkdb.com/api/javascript/offsets_of/