database - Query for most favorited in each category -
i have table of creations
. each belongs category (with categoryid
). have field called statfavorites
.
i want return flat list of single creation favorites each category in list.
the way can think of doing groupedmapreduce
. there way?
var categories; // objects id r.table('creations') .filter(function(creation) { return categories.filter(function(category) { return category.id == creation.categoryid }).length > 0 }) .groupedmapreduce(function(row) { return row("categoryid") } , function(row) { return row } , function(best, creation) { return r.branch(creation("statfavorites").gt(best("statfavorites")), creation, best })
two things happening above: first, i'm filtering creations match categories care (equivalent of in
query in mongo. how in rethink?)
second, i'm getting favorited of each one.
is there better way of doing this? may ok pre-calculate things when i'm writing data.
you can this: equivalent of in
contains
http://www.rethinkdb.com/api/javascript/contains/
categories = [id1, id2, id3] r.table('creations') .filter(function(creation) { return r.expr(categories).contains(creation("id")) }) .groupedmapreduce(function(row) { return row("categoryid") } , function(row) { return row } , function(best, creation) { return r.branch(creation("statfavorites").gt(best("statfavorites")), creation, best })
if categories object
{ id1: true, id2: true }
you can use hasfields
instead of contains
http://www.rethinkdb.com/api/javascript/has_fields/
r.table('creations') .filter(function(creation) { return r.expr(categories).hasfields(creation("id")) }) .groupedmapreduce(function(row) { return row("categoryid") } , function(row) { return row } , function(best, creation) { return r.branch(creation("statfavorites").gt(best("statfavorites")), creation, best })
Comments
Post a Comment