Search code examples
neo4jcypher

How can I create a edge based on the name of existing edge between 2 nodes?


I have 2 nodes

How to create an edge named "Son" from "Ben" to "John" if the existing relation is "Father" and "Ben's Gender is 'Male" like below:


Solution

  • This should work:

    MATCH (f:Person)-[:Father]->(s:Person)
    WHERE s.name = 'Ben' AND s.Gender = 'Male'
    CREATE (s)-[:Son]->(f)
    

    If it is possible that the Son relationship already exists, you should use MERGE instead of CREATE to avoid creating a duplicate relationship.

    You may also want to consider simplifying your data model (and reducing the storage size of your DB) by not adding the redundant Son relationship at all, since you can already tell that Ben is the son of John by using the above MATCH and WHERE clauses.