删除之前的节点和关系,并指向具有相同关系的当前节点

Delete the previous node and relationship and point it to the current node with same relationship

我正在尝试建立关系 b/w parent 和 child。

MERGE (c:Child{name:'CA'})
MERGE (p:Parent{name:'Parent'})

为了建立关系,

MERGE (p)-[:parent_of]->(c)

此查询是在名为 createParentChildRelationship 的单独 java 函数中编写的。 每当我尝试使用相同的 Parent 名称和不同的 child 名称调用此函数时,将参数传递给函数,它就会形成新的关系。但是我只需要当前的child节点指向parent节点,通过删除之前的child节点及其与parent的关系。 所以我尝试了这种方法,

MERGE (c:Child{name:'CA'})
MERGE (p:Parent{name:'Parent'})
MATCH (c)-[r:parent_of]-(p) DELETE r, c, p
CREATE (p)-[:parent_of]->(c) 

但它向我显示 1 property is set 但未建立关系

您的查询有两个问题:

  1. 您正在删除 parent、child 和关系。如果您刚刚删除 parent,则无法与新 child 建立新关系。此外,您要删除刚刚创建的 child,而不是 parent 的当前 child,因此也需要修复。

  2. 如果 MATCH 失败,则没有行可执行,查询中也不会发生任何其他事情。您可能需要一个可选匹配,或者可能需要一个模式理解。

您可以试试这个:

MERGE (p:Parent {name:'Parent'})
WITH p, [(p)-[:parent_of]->(existing) | existing] as existingChildren
FOREACH (child IN existingChildren | DETACH DELETE child)
MERGE (c:Child {name:'CA'})
CREATE (p)-[:parent_of]->(c)

试试这个,它适用于我的 neo4j 桌面;

  1. Find that relationship between CA and parent (OPTIONAL because it will continue the query if there is no match found)
  2. Delete the relationship
  3. Find that parent and create if not found (MERGE)
  4. Using the child and parent nodes, create a new relationship
OPTIONAL MATCH (c:Child)-[r:parent_of]-(:Parent{name:'Parent'})
DELETE r
MERGE (p2:Parent{name:'Parent'})
MERGE (p2)-[r2:parent_of]->(c2:Child{name:'CA'})
RETURN c2, r2, p2

您不能删除 c 和 p,因为它在创建过程中仍然是查询的一部分。