0
votes

I have a graph containing some nodes with :SubSystem labels. I want to add a new node with a :Document label and create relationships with each of the existing :SubSystem nodes.

When I execute this statement:

MATCH (s:SubSystem)
CREATE (d:Document {title:'New Document'})
CREATE (d)-[:DEPICTS]->(s);

I was surprised when Neo4j created a new :Document node for each :SubSystem. I have 12 sub-systems, so I ended up with 12 new documents each related to one sub-system. I would have expected this behavior had I written:

MATCH (s:SubSystem)
CREATE (:Document {title:'New Document'})-[:DEPICTS]->(s);

But I was expecting that separating the CREATE clauses would create 1 document then create relationships between that document and each of the sub-systems.

Can someone explain why this doesn't work as I was expecting.

EDIT:

I found a solution. This statement does what I wanted, but I still think my original attempt should have worked.

CREATE (d:Document {title:'New Document'})
WITH d MATCH (s:SubSystem) CREATE (d)-[:DEPICTS]->(s);
1

1 Answers

0
votes

A MATCH clause generates one or more result rows (or aborts the query if no results are found). A subsequent read/write clause would be executed once per row. Rearranging the order of the clauses, as you did, is one way to work around that (when possible).