Search code examples
neo4jcypher

Retrieve hierarchy based on node property with Cypher


I have nodes in my graph where they are in a hierarchy. The hierarchy is saved as a node property instead of edges. There are no connecting edges between these nodes in the graph.

eg:

P1 -CHILD-> P2, P3 -CHILD-> P4
P1 has Node property: Child - [P2,P3,P4]
P2 has Node property: Child - [P4]
P3 has Node property: Child - [P4]
P4 has Node property: Child - None

Is it possible to retrieve all the hierarchy starting from P1 in a cypher query?


Solution

  • To take advantage of the power of a graph database, your graph should have relationships. Create them with this query.

    MATCH (n)
    UNWIND n.child AS child
    MATCH (ch {name:child})
    CREATE (n)-[:HAS_CHILD]->(ch)
    

    Then you can return the full hierarchy with this query.

    MATCH path = (n {name:"P1"})-[:HAS_CHILD*]->(ch)
    RETURN [p in nodes(path) | p.name] AS pathToChild