简体   繁体   中英

In Neo4j how can I create relationships between one node an a collection of other nodes?

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);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM