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

喜欢而已 提交于 2019-12-24 15:01:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!