首页 > 解决方案 > Neo4J 查询不需要关系

问题描述

我正在使用这个查询来获取一个家庭的家谱,如果每个分支都有 3 代,它可以正常工作,但只要一代没有孩子,就不会得到其他分支的孩子。这是我的查询

Match p=(a:Person)-[a1:PARENT_OF]->(b:Person)-[b1:PARENT_OF]->(c:Person) 
where a.ID='9101'
WITH a,b,a1,b1,{id:c.ID,name:c.TEN,gioitinh:c.GIOI_TINH,loaiqh:b1.type} as thehe1
WITH a,a1,b1,{id:b.ID,name:b.TEN,gioitinh:b.GIOI_TINH,loaiqh:a1.type,loaiqh1:b1.type, children:collect(thehe1)} as thehe2
WITH  {id:a.ID,name:a.TEN,gioitinh:a.GIOI_TINH,loaiqh:a1.type, children:collect(thehe2)} as phahe 
return phahe

当一个或多个人 (b) 没有孩子时会发生这种情况,这意味着在这种情况下不存在关系 (b1) 和 (c)。Query 将为所有 Person (b) 返回 2 代,但并非所有 (b) 都没有使我的 Query 缺少数据的子代。

我应该怎么做才能使关系(b1)不需要?对不起我的英语不好,谢谢!

标签: neo4jcypher

解决方案


这可能对您有用:

MATCH p=(a:Person)-[a1:PARENT_OF]->(b:Person)
WHERE a.ID='9101'
OPTIONAL MATCH (b)-[b1:PARENT_OF]->(c:Person)
WITH a, a1,
  {id:b.ID, name:b.TEN, gioitinh:b.GIOI_TINH, loaiqh:a1.type,
   loaiqh1: CASE WHEN b1 IS NOT NULL THEN b1.type END,
   children: CASE WHEN b1 IS NOT NULL THEN COLLECT({id:c.ID,name:c.TEN,gioitinh:c.GIOI_TINH,loaiqh:b1.type}) ELSE [] END} as thehe2
RETURN  {id:a.ID,name:a.TEN,gioitinh:a.GIOI_TINH,loaiqh:a1.type, children:collect(thehe2)} as phahe

推荐阅读