Search code examples
neo4jcyphergraph-databases

How to return a list of related nodes for each node in Cypher


I would like to write a query for the graph below, which should return three lists, each list containing all persons working for the same person.

Given the graph below, the result should be this three lists:

  • [Fritz]
  • [Pepe]
  • [Susy, Peter]

Graph of work relationships

I fail to write such query. My query returns all employes in one list.

The following statements create the graph model for the example I have given:

MATCH  (c:Example) DETACH DELETE c;

CREATE (p1:Parent:Example {id: 1, name: 'Andy', title: 'Developer'});
CREATE (p2:Parent:Example {id: 2, name: 'Lila', title: 'Developer'});
CREATE (p3:Parent:Example {id: 3, name: 'Lula', title: 'Developer'});

CREATE (c11:Child:Example {id: 11, name: 'Peter', title: 'Developer'});
CREATE (c12:Child:Example {id: 12, name: 'Susy', title: 'Developer'});

CREATE (c21:Child:Example {id: 21, name: 'Fritz', title: 'Developer'});

CREATE (c31:Child:Example {id: 31, name: 'Pepe', title: 'Developer'});

MATCH (p {id: 1}), (c {id: 11}) MERGE (p)<-[:WORKS_FOR]-(c);
MATCH (p {id: 1}), (c {id: 12}) MERGE (p)<-[:WORKS_FOR]-(c);
MATCH (p {id: 2}), (c {id: 21}) MERGE (p)<-[:WORKS_FOR]-(c);
MATCH (p {id: 3}), (c {id: 31}) MERGE (p)<-[:WORKS_FOR]-(c);

Solution

  • It's relatively straightforward with Cypher

    MATCH (c)-[:WORKS_FOR]->(p)
    RETURN p.name AS boss, collect(c.name) AS coWorkers
    

    Result

    ╒══════╤════════════════╕
    │"boss"│"coWorkers"     │
    ╞══════╪════════════════╡
    │"Andy"│["Peter","Susy"]│
    ├──────┼────────────────┤
    │"Lila"│["Fritz"]       │
    ├──────┼────────────────┤
    │"Lula"│["Pepe"]        │
    └──────┴────────────────┘
    

    The trick is understanding aggregations https://neo4j.com/docs/cypher-manual/current/functions/aggregating/#grouping-keys