neo4jnestedcypherrelationshipusergroups

How do i query for direct, indirect, and nested nodes depending on a starting node and a specific relation?


I need to query the nodes owned by a user. I have the follwing simplified Graph: Graph Structure

INPUT: (User) PG

EXPECTED OUTPUT:

973732e... , f7f3693... , 9c572ae... (OWNER_OF -->Group)

I'm completely new to neo4j and cypher so i dont really know where to start.
Does anyone have some pointers or any idea?

Thanks in advance


Solution

  • This is one way to do it

    // get all the paths
    MATCH p= (u:User {name:'PG'})-[:MEMBER_OF|OWNER_OF*]->(:Group)
    
    // extract the nodes that have an incoming  `OWNER_OF` relationship
    WITH [node IN nodes(p) WHERE EXISTS(()-[:OWNER_OF]->(node))] AS ownedGroups
    
    // get the distinct nodes
    UNWIND ownedGroups AS ownedGroup
    RETURN DISTINCT ownedGroups