Question

I have a table of creations. Each belongs to a category (with categoryId). They also have a field called statFavorites.

I want to return a flat list of the single creation with the most favorites for each category in a list.

The only way I can think of doing it is with groupedMapReduce. Is there another way?

var categories; // objects with an 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 the creations to only match the categories I care about (equivalent of an in query in mongo. How to do this in rethink?)

Second, I'm getting the most favorited of each one.

Is there a better way of doing this? It may also be ok to pre-calculate things when I'm writing data.

Was it helpful?

Solution

You can do something like this: The equivalent of in is 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 is an object like

{
    id1: true,
    id2: true
}

You can also 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
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top