2014-12-27 30 views
1

我在尋找一個單個 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 

我能夠把一個查詢與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; 

這將如何正確完成?

注意:Order節點非常複雜,並且包含許多其他屬性,因此在這種情況下MERGE陳述將是非常不希望的。

回答

5

Neo4j爲此類情況提供了一種有用的功能,稱爲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 

因此,您的查詢會是這個樣子:

MATCH (n:Order) 
SET n.product_count = coalesce(n.product_count, 0) + 1 
RETURN n.product_count 

下面是關於聚結官方文檔:

http://neo4j.com/docs/stable/query-functions-scalar.html#functions-coalesce

+0

好東西, 謝謝!不知怎的,這裏我沒有想到使用'coalesce'。 –

相關問題