Neo4j Cypher:仅当结束节点存在时才创建关系

2024-03-16

对于以下 Cypher 语句:

start n=node:types(id={typeId}), g=node:groups(id={groupId})
create unique (n)<-[:has_type]-(unit {props})-[:has_group]->(g)
return unit

在某些情况下,g 可能为 null(即具有 id groupId 的组不存在)。 在这种情况下,我应该怎么做才能使该语句仍然创建单元,但跳过与 g 的 has_group 关系? 现在,单元尚未创建,可能是因为 g 为空。

我正在使用 Neo4j 高级 1.8

Thanks!


我建议将 g 的定义移至 where 子句,因为从不存在的节点开始会产生错误,因此无法继续查询到创建阶段。注意“?”它处理 Cypher 中的空值:

 start n=node:types(id={typeId})
 create unique (n)<-[:has_type]-(unit {props})-[:has_group]->(g)
 where g.id?={groupId}
 return unit

查询可能需要一些调整,这只是我的第一个未经测试的镜头。

edit:经过一番尝试后,我得出的结论是,您可能想要执行 2 个不同的查询,第一个用于创建与唯一节点的关系的第一部分(始终),第二个用于创建与可能不会发生的组的关系:

start n=node:types(id={typeId})
create unique (n)<-[:has_type]-(unit {props})    
return unit

start unit=node:unitProps({unitPropsValue}) ,g=node:groups(id={groupId}) 
create unique unit-[:has_group]->g    
return g

如果该组不存在,第二个查询将失败并出现错误,但这并不重要,因为您仍然会达到目标。由于某些奇怪的原因,我无法像我在第一个镜头中尝试的那样在 where 子句中实现一些限制。下面的查询似乎只是跳过了 where 条件(也许是一个错误?),尽管在我对 Cypher 的理解中,它应该与已经存在的组匹配,但它确实创建了一个新的 g 节点:

start n=node(1) 
create unique n-[:TYPE1]-(uniq {uid:333})
with uniq
create unique uniq-[:TYPE2]->g 
where has(g.gid) and g.gid=999 
return g
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Neo4j Cypher:仅当结束节点存在时才创建关系 的相关文章

随机推荐