如何在Cypher中按上级节点分组返回下属节点列表
问题需求
需要编写Cypher查询,返回三个独立列表,每个列表包含为同一上级工作的所有员工。预期结果:
- [Fritz]
- [Pepe]
- [Susy, Peter]
当前编写的查询会将所有员工合并到同一个列表中,无法得到预期结果。
示例图模型创建语句
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);
正确的Cypher查询
MATCH (parent:Parent)<-[:WORKS_FOR]-(child:Child) RETURN collect(child.name) AS team_members
说明
该查询通过匹配Parent节点和其下属Child节点的WORKS_FOR关系,利用collect()函数按每个上级分组收集下属姓名,最终返回三个独立列表,每个列表对应一位上级的所有下属,与预期结果完全匹配。
内容的提问来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

