Search code examples
neo4jcypher

Trying to create a relationships between nodes with 2 different properties names but some of them have the same value


Hey all a beginner neo4j student here o/ I created 40 nodes
20 :EMPLOYEE and 20 :ORGANIZATION nodes

Employee nodes have the owns_organizationNr property

Organization nodes have the ownedBy_organizationNr property

some of those nodes have the same value and I tried the query below to create relationships between those who match by the property value and insert the n1.owns_organizationNr property and value into to new relationship but something is missing can you guys help me, please?

MATCH (n1:EMPLOYEE) , (n2:ORGANIZATION) 
WHERE
  HAS(n1.owns_organizationNr) AND HAS(n2.ownedBy_organizationNr) AND n1.owns_organizationNr = n2.ownedBy_organizationNr
CREATE (n1) -[:OWNS_ORG{n1.owns_organizationNr}]->(n2)

Solution

  • The query is doing a cartesian product so it is resulting to a lot of rows. You can use below query. Also, there is a typo error on the CREATE statement. I also fix it in the last line.

    MATCH (n1:EMPLOYEE) WHERE  n1.owns_organizationNr is not null
    WITH n1
    MATCH (n2:ORGANIZATION) 
    WHERE n2.ownedBy_organizationNr is not null AND n1.owns_organizationNr = n2.ownedBy_organizationNr 
    CREATE (n1) -[:OWNS_ORG{owns_organizationNr: n1.owns_organizationNr}]->(n2)
    

    Sample result:

    enter image description here