ReQL command: merge

Command syntax

singleSelection.merge([object | function, object | function, ...]) → object
object.merge([object | function, object | function, ...]) → object
sequence.merge([object | function, object | function, ...]) → stream
array.merge([object | function, object | function, ...]) → array

Description

Merge two or more objects together to construct a new object with properties from all. When there is a conflict between field names, preference is given to fields in the rightmost object in the argument list. merge also accepts a function that returns an object, which will be used similarly to a map function.

Example: Equip Thor for battle.

r.table("marvel").get("thor")
 .merge(r.table("equipment").get("hammer"),
        r.table("equipment").get("pimento_sandwich"))
 .run(conn);

Example: Equip every hero for battle, using a function to retrieve their weapons.

r.table("marvel").merge(
    hero -> r.hashMap("weapons", r.table("weapons").get(hero.g("weapon_id")))
).run(conn);

Example: Use merge to join each blog post with its comments.

Note that the sequence being merged—in this example, the comments—must be coerced from a selection to an array. Without coerceTo the operation will throw an error (“Expected type DATUM but found SELECTION”).

r.table("posts").merge(
    post -> r.hashMap("comments", r.table("comments").getAll(post.g("id"))
                      .optArg("index", "post_id").coerceTo("array"))
).run(conn);

Example: Merge can be used recursively to modify sub-objects within objects.

r.expr(r.hashMap("weapons", r.hashMap("spectacular graviton beam",
    r.hashMap("dmg", 10).with("cooldown", 20))))
 .merge(r.hashMap("weapons", r.hashMap("spectacular graviton beam",
    r.hashMap("dmg", 10))))
 .run(conn);

Example: To replace a nested object with another object you can use the literal term.

r.expr(r.hashMap("weapons", r.hashMap("spectacular graviton beam",
    r.hashMap("dmg", 10).with("cooldown", 20))))
 .merge(r.hashMap("weapons", r.literal(r.hashMap("repulsor rays",
    r.hashMap("dmg", 3).with("cooldown", 0)))))
 .run(conn);

Example: literal can be used to remove keys from an object as well.

r.expr(r.hashMap("weapons", r.hashMap("spectacular graviton beam",
    r.hashMap("dmg", 10).with("cooldown", 20))))
 .merge(r.hashMap("weapons", r.hashMap("spectacular graviton beam",
    r.literal())))
 .run(conn);

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