apoc.merge.relationship

Procedure APOC Core

apoc.merge.relationship(startNode, relType, identProps:{key:value, …​}, onCreateProps:{key:value, …​}, endNode, onMatchProps:{key:value, …​}) - merge relationship with dynamic type, with support for setting properties ON CREATE or ON MATCH

Signature

apoc.merge.relationship(startNode :: NODE?, relationshipType :: STRING?, identProps :: MAP?, onCreateProps :: MAP?, endNode :: NODE?, onMatchProps = {} :: MAP?) :: (rel :: RELATIONSHIP?)

Input parameters

Name Type Default Description

startNode

NODE?

null

Start node of the merge pattern.

relationshipType

STRING?

null

Relationship type of the merge pattern.

identProps

MAP?

null

Properties on the relationships that are always merged.

onCreateProps

MAP?

null

Properties that are merged when the relationship is created.

endNode

NODE?

null

End node of the merge pattern.

onMatchProps

MAP?

{}

Properties that are merged when the relationship is matched.

Output parameters

Name Type

rel

RELATIONSHIP?

Usage Examples

The examples in this section are based on the following graph:

CREATE (p:Person {name: "Tom Hanks"})
CREATE (m:Movie {title:"You've Got Mail"});

This procedure provides a more flexible way of merging relationships than Cypher’s MERGE clause.

The example below shows equivalent ways of merging an ACTED_IN relationship between the Tom Hanks and You’ve Got Mail nodes:

apoc.merge.relationship
MATCH (p:Person {name: "Tom Hanks"})
MATCH (m:Movie {title:"You've Got Mail"})
CALL apoc.merge.relationship(p, "ACTED_IN",
  {roles:['Joe Fox']},
  {created: datetime()},
  m,
  {lastSeen: datetime()}
)
YIELD rel
RETURN rel;
MERGE clause
MATCH (p:Person {name: "Tom Hanks"})
MATCH (m:Movie {title:"You've Got Mail"})
MERGE (p)-[rel:ACTED_IN {roles:['Joe Fox']}]->(m)
ON CREATE SET rel.created = datetime()
ON MATCH SET rel.lastSeen = datetime()
RETURN rel;

If we run these queries a few times, we’ll see output as shown below:

Table 1. Results
rel

[:ACTED_IN {lastSeen: 2020-11-03T11:02:00.261Z, created: 2020-11-03T11:00:56.849Z, roles: ["Joe Fox"]}]

But this procedure is mostly useful for merging relationships that have a dynamic relationship type or dynamic properties. For example, we might want to merge a relationship with a relationship type or properties passed in as parameters.

The following creates relationshipType and properties parameters:

:param relType =>  ("ACTED_IN");
:param properties => ({roles: ["Joe Fox"]});

The following merges a relationship with a relationship type and properties based on the previously defined parameters:

MATCH (p:Person {name: "Tom Hanks"})
MATCH (m:Movie {title:"You've Got Mail"})
CALL apoc.merge.relationship(p, $relType, $properties, {}, m, {})
YIELD rel
RETURN rel;
Table 2. Results
rel

[:ACTED_IN {roles: ["Joe Fox"]}]