问题
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 }]
回答1:
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/
回答2:
r.table('users').orderBy({index: 'points'}).run(conn, callback)
Tis will return the list sorted by points. (Ie: The first element will have rank 1, the second element rank 2, etc.)
See also: https://rethinkdb.com/api/javascript/order_by/
回答3:
The .map
function accept one or more sequences/arrays (See Docs). So you can use your filtered sequence for first argument and use r.range()
as second parameter. So your callback function will have 2 arguments (each one representing an element of one sequence/array). See below:
r.table('users')
.orderBy({index: 'points'})
.map(r.range(), (user, number) => {
return user.merge(rank: number.add(1))
}
来源:https://stackoverflow.com/questions/33330073/how-do-i-get-the-rank-row-number-for-a-row