user1905720
user1905720

Reputation:

reddit-like sorting in rethinkdb

I'm using rethinkdb with the thinky ORM on node.js.

I'm trying to sort documents (posts, comments) from a rethinkdb table using a function that takes data from documents, and outputs a number that represents the sorting index of each document, much like reddit's time-sensitive ranking algorithm. The data should then be able to be paginated using .slice().

Does anyone know how to do this? I'm completely lost.

Upvotes: 1

Views: 272

Answers (1)

Daniel Mewes
Daniel Mewes

Reputation: 1876

ReQL's orderBy term can take a function and order by its result.

I'm not certain about the exact syntax in Thinky (it should be similar), but this is how you would do it in plain ReQL:

r.table(...).orderBy(function (row) { return row('sorting_index'); })

The function function (row) { return row('sorting_index'); } is just an example. You can use any ReQL function, or even r.js() to supply an arbitrary JavaScript function http://rethinkdb.com/api/javascript/js/. Be aware though that r.js() is usually a lot slower than using native ReQL statements.

The documentation for orderBy has a complete example for this: http://rethinkdb.com/api/javascript/order_by/

If you run this query often and performance is important (or the data set is large), I recommend creating a secondary index to speed this operation up:

r.table(...).indexCreate("sorting_idx", function (row) { return row('sorting_index'); })

Then you can use:

r.table(...).orderBy({index: "sorting_idx"})

Upvotes: 2

Related Questions