Maciej Sz
Maciej Sz

Reputation: 12035

Initiate and return node property if it does not exist using a single Cypher query

I'm looking for a single Cypher query that will increment an integer node parameter and return the value while initiating it to 0 in case if it does not exist.

Something like following pseudo-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

I was able to put together a query with a FOREACH statement that gets the job done, but this seems hacky and not appropriate for my use case:

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; 

How would this be done the right way?

Note: the Order node is very complex and contains many other properties, so MERGE statment in this case would be highly undesired.

Upvotes: 4

Views: 2278

Answers (1)

Neel Virdy
Neel Virdy

Reputation: 148

Neo4j provides a useful function for situations like this called coalesce.

Coalesce takes any number of arguments, and returns the first that is not NULL. In the case where all arguments are NULL, it simply returns NULL.

So, for example:

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

Thus, your query would look something like this:

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

Here's the official documentation on coalesce:

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

Upvotes: 9

Related Questions