W3cubDocs

/RethinkDB Java

ReQL command: branch

Command syntax

r.branch(test, true_action[, test2, test2_action, ...], false_action) → any
test.branch(true_action[, test2, test2_action, ...], false_action) → any

Description

Perform a branching conditional equivalent to if-then-else.

The branch command takes 2n+1 arguments: pairs of conditional expressions and commands to be executed if the conditionals return any value but false or null (i.e., “truthy” values), with a final “else” command to be evaluated if all of the conditionals are false or null.

You may call branch infix style on the first test. (See the second example for an illustration.)

r.branch(test1, val1, test2, val2, elseval)

is the equivalent of the Java statement

if (test1) {
    return val1;
} else if (test2) {
    return val2;
} else {
    return elseval;
}

Example: Test the value of x.

int x = 10;
r.branch(r.expr(x).gt(5), "big", "small").run(conn);

// Result:
"big"

Example: As above, infix-style.

int x = 10;
r.expr(x).gt(5).branch("big", "small").run(conn);

// Result:
"big"

Example: Categorize heroes by victory counts.

r.table("marvel").map(hero -> r.branch(
    hero.g("victories").gt(100),
    hero.g("name").add(" is a superhero"),
    hero.g("victories").gt(10),
    hero.g("name").add(" is a hero"),
    hero.g("name").add(" is very nice")
)).run(conn);

If the documents in the table marvel are:

[
    { "name": "Iron Man", "victories": 214 },
    { "name": "Jubilee", "victories": 49 },
    { "name": "Slava", "victories": 5 }
]

The results will be:

[
    "Iron Man is a superhero",
    "Jubilee is a hero",
    "Slava is very nice"
]

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/java/branch/