代码之家  ›  专栏  ›  技术社区  ›  Oliver

如何返回Cypher中每个节点的相关节点列表

  •  0
  • Oliver  · 技术社区  · 1 年前

    我想为下面的图写一个查询,它应该返回三个列表,每个列表都包含为同一个人工作的所有人。

    给定下图,结果应该是以下三个列表:

    • [Fritz]
    • [Pepe]
    • [Sussy,Peter]

    Graph of work relationships

    我没能写出这样的疑问。我的查询返回一个列表中的所有员工。

    以下语句为我给出的示例创建了图形模型:

    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);
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   Christophe Willemsen    1 年前

    Cypher相对简单

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

    后果

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

    诀窍在于理解聚合 https://neo4j.com/docs/cypher-manual/current/functions/aggregating/#grouping-keys