0
votes

I created two labels A and B with a relationship CONNECT. I need to create multiple nodes of of each label A and B and a relationship between them. i.e, for each node A and B, I need to create a relationship. e.g.: a1:A -[:CONNECT]-> b1:B, a2:A -[:CONNECT]-> b2:B,a3:A -[:CONNECT]-> b3:B, ... an:A -[:CONNECT]-> bn:B

Is there a way to create the relationship automatically? When I create nodes, can the db automatically create a relationship between the nodes of different existing labels? Please help.

I used the APOC procedure to create multiple relationships between nodes manually on a property - for 100 nodes of labels LABEL1 and LABEL2, on a property value, I can create a relationships manually with a single Cypher query using below proc:

MATCH (ref1:LABEL1), (ref2:LABEL2)
WHERE ref1.property = ref2.property 
CALL apoc.create.relationship(ref1, ‘RELATIONSHIP_NAME', {}, ref2) YIELD rel
RETURN rel

But I want to know if a way exists, where a relationship between two labels A and B already exists; and whenever a new node of label A and B are created, a relationship automatically creates without running a cypher query.

1

1 Answers

0
votes

If you want to create a relationship between 2 nodes created at the same time, just specify that pattern in your CREATE clause.

Here is example using LOAD CSV to import data:

LOAD CSV WITH HEADERS FROM 'file:///data.csv' AS row
CREATE (a:A {x: row.x})-[:CONNECT]->(b:B {y: row.y})

Generally, it would be risky for a DB to automatically create relationships on your behalf since it might cause relationships to be created that you did not intend.

[UPDATE]

However, if Label2 nodes are created at a later time than Label1 nodes, and you are sure you want to automatically create the CONNECT relationship, you can use APOC to create a trigger like this:

CALL apoc.trigger.add(
  "create-CONNECT-rel",
  "UNWIND $createdNodes AS ref2
   WITH ref2
   WHERE ref2:Label2
   MATCH (ref1:Label1 {property: ref2.property})
   CREATE (ref1)-[:CONNECT]->(ref2)",
  {phase:'before'})