简体   繁体   中英

How to create relationship to just one node (with a similar name) in neo4j cypher?

I want to design a Database about airports. Every airport has at least five terminals (named A, B, C, D and E). So I want to have Airport Schiphol INCLUDES A, B, C, D,E. But I have created five terminals with the name "A" and thus if I run this code:

MATCH (a:Airport{name:"Schiphol"}),(b:Terminal{name:"A"}) CREATE (a)-[r: INCLUDES]->(b)

it attaches every Terminal A to Schiphol. How can I avoid this, and assign just 1 set of A , B, C, D and E to the airport?

Thanks in advance

MERGE is going to be the solution here, creating the pattern of the airport including a terminal, but not creating the :Terminal nodes ahead of time.

When you use MERGE for a pattern and one of the nodes is already bound (the :Airport node) and other isn't (the :Terminal), then if the pattern needs to be created the unbound node will be created along with the relationship between the nodes. This is how you create terminals per airport.

MATCH (a:Airport{name:"Schiphol"})
MERGE (a)-[:INCLUDES]->(termA:Terminal{name:"A"}) 

And if you want to create all the terminals at once per airport:

MATCH (a:Airport{name:"Schiphol"})
UNWIND ['A','B','C','D','E'] as term
MERGE (a)-[:INCLUDES]->(terminal:Terminal{name:term})

Why having five terminals with 'A' name ? A solution can be :

MATCH (a:Airport{name:"Schiphol"})
MATCH (b:Terminal{name:"A"}) 
WITH a, COLLECT (b) as terminals
WITH a, HEAD(terminals) as terminal 
CREATE (a)-[r: INCLUDES]->(terminal)

(not tried) But it is arbitrary...

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