neo4j 有没有一种方法可以在密码的情况下使用create和return?

4jb9z9bj  于 2023-06-22  发布在  其他
关注(0)|答案(2)|浏览(139)

当rv存在时,我试图创建节点n1,如果rv不存在,则创建n2,如果rv存在,则声明变量flag。如果flag为true,则返回n1,如果flag为false,则返回n2。
我的代码:

WITH rv IS NOT NULL AS flag
WHERE flag
CREATE (n1:Test1 {name: "Test1"})
Return n1

WITH flag
WHERE NOT flag
CREATE (n2:Test2 {name: "Test2"})
Return n2
zed5wv10

zed5wv101#

您可以使用APOC函数来实现此目的。

Line 1 is an illustration when rv is null. Remove it on your actual query
Line 2 is using the APOC function 'do when'
Line 3 is the condition. if true then run line 4 else line 5
Line 4 is your true condition
Line 5 is your false condition
Line 6 returns the node that you created

1    WITH null as rv
2    CALL apoc.do.when(
3      rv is not null,
4      "CREATE (n1:Test1 {name: 'Test1'}) RETURN n1",
5      "CREATE (n2:Test2 {name: 'Test2'}) RETURN n2") YIELD value 
6    RETURN value
wpx232ag

wpx232ag2#

除了使用apoc.do.when,如@jose_bacoy所建议的,您还可以使用apoc.create.node

... // prior Cypher that defines rv
WITH CASE
  WHEN rv IS NULL THEN {l: 'Test2', n: 'Test2'}
  ELSE {l: 'Test1', n: 'Test1'}
END AS x
CALL apoc.create.node([x.l], {name: x.n}) YIELD node AS n
RETURN n

或者,如果出于某种原因不想使用APOC库,可以在neo4j 4.1+中使用CALL subquery

... // prior Cypher that defines rv
CALL {
    WITH rv
    WITH rv WHERE rv IS NOT NULL
    CREATE (n:Test1 {name: "Test1"})
    RETURN n

    UNION

    WITH rv
    WITH rv WHERE rv IS NULL
    CREATE (n:Test2 {name: 'Test2'})
    RETURN n
}
RETURN n

相关问题