Skip to content

MERGE clause

Marijn van Wezel edited this page Dec 13, 2022 · 4 revisions

The MERGE lause ensures that a pattern exists in the graph. Either the pattern already exists, or it needs to be created. It accepts the pattern to merge and optionally a query to execute upon creation or upon a match of a node.

Query::merge(CompletePattern $pattern, ?SetClause $createClause = null, ?SetClause $matchClause = null): Query

Parameters

  • $pattern : The pattern to "merge".
  • $createClause: The clause to execute on all nodes that need to be created.
  • $matchClause: The clause to execute on all found nodes.

Relevant methods

  • setPattern(CompletePattern $pattern): self : Sets the pattern to "merge".
  • setOnCreate(?SetClause $createClause): self : Sets the clause to execute on all nodes that need to be created.
  • setOnMatch(?SetClause $matchClause): self : Sets the clause to execute on all found nodes.

Examples

Merge single node with a label

$robert = node('Critic');

$query = query()
    ->merge($robert)
    ->returning($robert)
    ->build();

$this->assertStringMatchesFormat("MERGE (%s:Critic) RETURN %s", $query);

Merge with ON CREATE

$keanu = node('Person')->withProperties(['name' => 'Keanu Reeves']);

$query = query()
    ->merge($keanu, (new SetClause())->add($keanu->property('created')->replaceWith(procedure()::raw('timestamp'))))
    ->returning([$keanu->property('name'), $keanu->property('created')])
    ->build();

$this->assertStringMatchesFormat("MERGE (%s:Person {name: 'Keanu Reeves'}) ON CREATE SET %s.created = timestamp() RETURN %s.name, %s.created", $query);

Merge with ON MATCH

$keanu = node('Person')->withProperties(['name' => 'Keanu Reeves']);

$query = query()
    ->merge($keanu, null, (new SetClause())->add($keanu->property('created')->replaceWith(procedure()::raw('timestamp'))))
    ->returning([$keanu->property('name'), $keanu->property('created')])
    ->build();

$this->assertStringMatchesFormat("MERGE (%s:Person {name: 'Keanu Reeves'}) ON MATCH SET %s.created = timestamp() RETURN %s.name, %s.created", $query);

External links