Neo4j Cypher:仅在结束节点存在时创建关系 [英] Neo4j Cypher: Create a relation only if the end node exists

查看:243
本文介绍了Neo4j Cypher:仅在结束节点存在时创建关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下Cypher语句:

For the following Cypher statement:

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

在某些情况下,g可能为空(即,不存在ID为groupId的组)。
在这种情况下,我该怎么做才能使此语句仍然创建单位,但跳过与g的has_group关系?
现在,无法创建单位,大概是因为g为空。

There are cases when g may be null (i.e. a group with id groupId does not exist). In such a case, what should I do to make this statement still create the unit, but skip the has_group relation to g? Right now, unit does not get created, presumably because g is null.

我正在使用Neo4j Advanced 1.8

I'm using Neo4j Advanced 1.8

谢谢!

推荐答案

我建议将g的定义移至where子句,因为从一个不存在的节点会给出错误,因此无法继续查询到创建阶段。注意处理Cypher中空值的'?':

I would suggest to move the definition of g to the where clause, since starting at a non-existing node gives error and thus one can't continue the query to the create phase. Note the '?' which handles the null values in Cypher:

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

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

the query might need some tweaking, this is just my first untested shot.

编辑:经过一番尝试,我得出了一个结论,即您可能要进行2个不同的查询,首先是与唯一的节点,始终是第二个节点,它是第二个创建可能不会发生的组关系的子节点:

edit: After some trying I came to a conclusion, that you might want to do 2 different queries, first for creating the first part of relationships with the unique node which is always and the second to create the relationship to the group which may not happen:

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节点:

the second query will fail with an error in case the group does not exist, but that does not matter since you will still reach the target. For some strange reason I couldn't manage to implement some restrictions in the where clause like I tried in the first shot. following query seems to simply jump over the where conditions (maybe a bug?) although in my comprehension of Cypher it shall match the already existing group, but it does create a new g node instead:

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

这篇关于Neo4j Cypher:仅在结束节点存在时创建关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆