Skip to content

Latest commit

 

History

History
89 lines (70 loc) · 2.27 KB

File metadata and controls

89 lines (70 loc) · 2.27 KB
layout api-command
language JavaScript
permalink api/javascript/reduce/
command reduce
io
sequence
value
related_commands
group map concat_map sum avg min max
group/
map/
concat_map/
sum/
avg/
min/
max/

Command syntax

{% apibody %} sequence.reduce(function) → value r.reduce(sequence, function) → value {% endapibody %}

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 number of documents in the table posts.

r.table("posts").map(function(doc) {
    return 1;
}).reduce(function(left, right) {
    return left.add(right);
}).default(0).run(conn, callback);

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(function(doc) {
    return doc("comments").count();
}).reduce(function(left, right) {
    return left.add(right);
}).default(0).run(conn, callback);

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(function(doc) {
    return doc("comments").count();
}).reduce(function(left, right) {
    return r.branch(
        left.gt(right),
        left,
        right
    );
}).default(0).run(conn, callback);

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