简体   繁体   中英

Can you create a node and link it to multiple nodes in one query?

I've been trying to crate a node and link it to a list of other nodes, I arrived at the following query:

MATCH (s:Subject), (p:Programme {name: 'Bsc. Agriculture' })
Where s.name IN ['Physics (CAPE)', 'Biology (CAPE)', 'Chemistry (CAPE)']
Create (c: Combo {amt:1}), (c)-[:contains]->(s), (p)-[:requires]->(c) return *

but unfortunately the combo node is created three times, and each combo node is linked to a Subject node. Is there any way I can adjust this query so that only one Combo node is created?

The query below uses the aggregation function COLLECT to produce a single row of data (instead of three) per p , to ensure that the first CREATE is only executed only once per p -- thus producing only a single Combo and requires relationship per p . The FOREACH clause then creates all the required contains relationships.

MATCH (sub:Subject), (p:Programme {name: 'Bsc. Agriculture' })
WHERE sub.name IN ['Physics (CAPE)', 'Biology (CAPE)', 'Chemistry (CAPE)']
WITH p, COLLECT(sub) AS subs
CREATE (p)-[:requires]->(c: Combo {amt:1})
FOREACH(s IN subs | CREATE (c)-[:contains]->(s))
RETURN *

Your query creates Combo node for every other node used in CREATE that was found by MATCH. One of the solutions could be that you create Combo node first and than use it in other parts of your query

Create (c: Combo {amt:1})
WITH c
MATCH (s:Subject), (p:Programme {name: 'Bsc. Agriculture' })
Where s.name IN ['Physics (CAPE)', 'Biology (CAPE)', 'Chemistry (CAPE)']
CREATE (c)-[:contains]->(s), (p)-[:requires]->(c) return *

If you use MERGE instead of CREATE, it should address your requirements and avoid creating duplicate nodes. But this assumes that each relationship target node is identified by all of its unique properties. Try this ...

MATCH (s:Subject), (p:Programme {name: 'Bsc. Agriculture' }) 
Where s.name IN ['Physics (CAPE)', 'Biology (CAPE)', 'Chemistry (CAPE)'] 
MERGE (c: Combo {amt:1}), (c)-[:contains]->(s), (p)-[:requires]->(c) return *

Merge will create an element only if it does not exist. The caution is that the element in question must match in all its parameters (name and properties). There is more on this at https://graphaware.com/neo4j/2014/07/31/cypher-merge-explained.html .

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