我正在寻找一个单一的 Cypher查询,它将增加一个整数节点参数,并在启动它时返回该值0
,以防它不存在.
类似于遵循伪Cypher:
MATCH (n:Order)
IF n.product_count IS NULL THEN n.product_count = 0 // this line is what I need
SET n.product_count = n.product_count + 1
RETURN n.product_count
Run Code Online (Sandbox Code Playgroud)
我能够将一个查询与一个FOREACH
完成工作的语句放在一起,但这看起来很糟糕,并不适合我的用例:
MATCH (n:Order)
WHERE id(n) = 9503
FOREACH ( i in (CASE WHEN n.product_count IS NULL THEN [1] ELSE [] END) | SET n.product_count = 0 )
SET n.product_count = n.product_count + 1
RETURN n.product_count;
Run Code Online (Sandbox Code Playgroud)
如何以正确的方式完成?
注意:Order
节点非常复杂并且包含许多其他属性,因此MERGE
在这种情况下的定义非常不受欢迎.
小智 7
Neo4j为这种称为coalesce的情况提供了一个有用的功能.
Coalesce接受任意数量的参数,并返回非NULL的第一个参数.在所有参数都为NULL的情况下,它只返回NULL.
所以,例如:
coalesce(NULL, 1) // equates to 1
coalesce("hello", 6) // equates to "hello"
coalesce(NULL, "world", NULL) // equates to "world"
coalesce(NULL, NULL) // equates to NULL
Run Code Online (Sandbox Code Playgroud)
因此,您的查询看起来像这样:
MATCH (n:Order)
SET n.product_count = coalesce(n.product_count, 0) + 1
RETURN n.product_count
Run Code Online (Sandbox Code Playgroud)
这是关于coalesce的官方文档:
http://neo4j.com/docs/stable/query-functions-scalar.html#functions-coalesce