在 Neo4J 中切换关系

Toggle relationship in Neo4J

我正在尝试在 Neo4J 中实现 follow/unfollow。我想写一个查询来切换两个节点之间的关系。

我目前有以下查询:

neoSession.writeTransaction(tx => tx.run('MATCH (me:User), (other:User) WHERE ID(me) = $me AND ID(other) = $other OPTIONAL MATCH (me)-[af:FOLLOWS]->(other) CALL apoc.do.when(af IS NULL, CREATE (me)-[f:FOLLOWS]->(other), DELETE af)', { me: req.user_id, other: req.body.user, datetime: Date.now() }));

美化仅查询:

MATCH (me:User), (other:User) 
  WHERE ID(me) = $me AND ID(other) = $other 
OPTIONAL MATCH (me)-[af:FOLLOWS]->(other) 
CALL 
  apoc.do.when(
    af IS NULL, 
    CREATE (me)-[f:FOLLOWS]->(other), 
    DELETE af
  )

但这会导致错误

Neo4jError: Invalid input '>' (line 1, column 169 (offset: 168))

"MATCH (me:User), (other:User) WHERE ID(me) = $me AND ID(other) = $other OPTIONAL MATCH (me)-[af:FOLLOWS]->(other) CALL apoc.do.when(af IS NULL, CREATE (me)-[f:FOLLOWS]->(other), DELETE af)"

apoc.do.when() 的查询(最后两个参数)必须是字符串,因此请分别引用它们。

此外,为了让每个查询都使用这些变量,您需要将这些变量作为第四个参数传递到参数映射中。

每个条件查询都必须 RETURN 一些内容,否则将不会产生任何行,之后的任何内容都将是空操作。

调用必须 YIELD value,因此需要存在,最后,查询不能以过程调用结束,因此您需要 RETURN 一些东西。

这个应该可以,您可以根据需要进行调整:

MATCH (me:User), (other:User) 
  WHERE ID(me) = $me AND ID(other) = $other 
OPTIONAL MATCH (me)-[af:FOLLOWS]->(other) 
CALL 
  apoc.do.when(
    af IS NULL, 
    "CREATE (me)-[f:FOLLOWS]->(other) RETURN f", 
    "DELETE af RETURN null as f",
    {me:me, af:af}
  ) YIELD value
RETURN value.f as f