W3cubDocs

/RethinkDB Ruby

ReQL command: reduce

Command syntax

sequence.reduce(function) → value
r.reduce(sequence, function) → value

Description

Produce a single value from a sequence through repeated application of a reduction function.

The reduction function can be called on:

  • two elements of the sequence
  • one element of the sequence and one result of a previous reduction
  • two results of previous reductions

The reduction function can be called on the results of two previous reductions because the reduce command is distributed and parallelized across shards and CPU cores. A common mistaken when using the reduce command is to suppose that the reduction is executed from left to right. Read the map-reduce in RethinkDB article to see an example.

If the sequence is empty, the server will produce a ReqlRuntimeError that can be caught with default.
If the sequence has only one element, the first element will be returned.

Example: Return the numbers of documents in the table posts.

r.table("posts").map{|doc| 1 }
    .reduce{ |left, right| left+right }
    .default(0).run(conn)

A shorter way to execute this query is to use count.

Example: Suppose that each post has a field comments that is an array of comments.
Return the number of comments for all posts.

r.table("posts").map{|doc|
    doc["comments"].count()
}.reduce{ |left, right|
    left+right
}.default(0).run(conn)

Example: Suppose that each post has a field comments that is an array of comments.
Return the maximum number comments per post.

r.table("posts").map{|doc|
    doc["comments"].count()
}.reduce{ |left, right|
    r.branch(
        left > right,
        left,
        right
    )
}.default(0).run(conn)

A shorter way to execute this query is to use max.

Related commands

Get more help

Couldn't find what you were looking for?

© RethinkDB contributors
Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
https://rethinkdb.com/api/ruby/reduce/