Home > Back-end >  variable relationships within a single query in neo4j
variable relationships within a single query in neo4j

Time:07-14

I am new to neo4j. I have two types of nodes in the database, i.e., "Person" and "House". I want to create relationships between each "Person" and the "House" with names like "resident_1", "resident_2", etc. Please find my code below:

CREATE (n1:Person {name: '1'})
CREATE (n2:Person {name: '2'})
CREATE (n3:Person {name: '3'})
CREATE (n4:Person {name: '4'})
CREATE (t1:House {name:"T1"})
With n1, n2,n3,n4,t1
MATCH(a:House{name: "T1"})
with a
MATCH(b:Person) 
WITH a, b
Create (a)-[r:resident_1]->(b)
RETURN type(r)

The output generates

╒════════════╕
│"type(r)"   │
╞════════════╡
│"resident_1"│
├────────────┤
│"resident_1"│
├────────────┤
│"resident_1"│
├────────────┤
│"resident_1"│
└────────────┘

But, I want to generate

╒════════════╕
│"type(r)"   │
╞════════════╡
│"resident_1"│
├────────────┤
│"resident_2"│
├────────────┤
│"resident_3"│
├────────────┤
│"resident_4"│
└────────────┘

How to do that? Any help is highly appreciated. Thanks!

CodePudding user response:

Cypher only supports static value of relationship type so you need to use an APOC function (it is awesome) if the relationship type is dynamic. If you need help on installing APOC, here it is: enter image description here

  • Related