Question

I have a table with votes that have some entries like (id, song_id, user_id and vote).. vote can contain the value "like" or "dislike"

now I want to make a queue thats groups by song_id and then returning the number of likes and dislikes value from that group

r.db('songs').table('votes').groupedMapReduce(
    function(vote) { return vote('song_id')},
    function(vote) { return vote.pluck('vote')},
    function(acc, vote) {
        return ?????;
        /* 
        ** some kind of loop to get all the likes and dislikes
        ** if vote === 'like' likes++
        ** if vote === 'dislike' dislikes++
        ** return {song_id:song_id, likes:likes, dislikes:dislikes}
        */
    }
 )

hoping for output like:

[
    {song_id: 1, likes: 8, dislikes: 3},
    {song_id: 2, likes: 2, dislikes: 6},
    // and so on
]
Was it helpful?

Solution

I think that's the groupedMapReduce you are looking for:

r.db('songs').table('votes').groupedMapReduce(
    function(vote) { return vote('song_id')},
    function(vote) { return r.branch(
        vote("vote").eq("like"),
        {like: 1, dislike: 0},
        {like: 0, dislike: 1}
    )},
    function(left, right) {
        return {
            like: left("like").add(right("like")),
            dislike: left("dislike").add(right("dislike"))
        }
    }
)

Also RethinkDB next version (schedule in 1-2 weeks) is going to replace groupedMapReduce with a better group command.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top