简体   繁体   English

与cypher有条件地建立关系(neo4j)

[英]Creating relationship conditionally with cypher (neo4j)

I am attempting to create a linked list with neo4j, and have a root node with no relationships. 我试图用neo4j创建一个链表,并且有一个没有关系的根节点。 Here is the pseudo cypher I am trying to create, but I am not sure how, or even if it is possible: 这是我想要创建的伪cypher,但我不确定如何,或者即使它是可能的:

START root=node(1), item=node(2)
MATCH root-[old?:LINK]->last
WHERE old IS NOT NULL
CREATE root-[:LINK]->item-[:LINK]->last
DELETE old
WHERE old IS NULL
CREATE root-[:LINK]->item

Basically I am trying to insert a node into the list if the list exists, and simply create the first list item otherwise. 基本上,如果列表存在,我试图将一个节点插入到列表中,否则只需创建第一个列表项。 Obviously you cannot do multiple WHERE s like I have done above. 显然你不能像我上面那样做多个WHERE Any ideas how I can achieve this desired functionality with a cypher? 有关如何使用密码实现所需功能的任何想法?

The docs solve the problem by first creating a recurrent :LINK relationship on the root node, but I would like to solve this without doing that (as you then need to create possibly unnecessary relationships for each node). 文档通过首先在根节点上创建recurrent :LINK关系来解决问题,但我想在不这样做的情况下解决这个问题(因为您需要为每个节点创建可能不必要的关系)。

For anyone interested, I figured out a way to solve the above using some WITH tricks. 对于任何有兴趣的人,我想出了一种使用一些WITH技巧解决上述问题的方法。 This is essentially a solution for creating linked lists in neo4j without having to first create a self referencing relationship. 这本质上是一种在neo4j中创建链表的解决方案,而无需首先创建自引用关系。

START root=node(1), item=node(2) 
MATCH root-[old?:LIST_NEXT]->last
CREATE root-[:LIST_NEXT]->item 
WITH item, old, last 
WHERE old IS NOT NULL 
CREATE item-[:LIST_NEXT]->last 
DELETE old

This works by first looking for an existing link relationship, and creating the new one from the root to the item. 这通过首先查找现有的链接关系,并从根到项目创建新的链接关系来实现。 Then by using WITH we can chain the query to now examine whether or not the matched relationship did in fact exist. 然后通过使用WITH我们可以链接查询现在检查匹配的关系是否确实存在。 If it did, then remove it, and create the remaining link piece from the new item to the old one. 如果是,则将其删除,并将新项目中的剩余链接片段创建为旧项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM