Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j merge return something only if it was created

Tags:

neo4j

cypher

Neo4j's merge will create new node if it doesn't exist. And it has ON CREATE and ON MATCH as two distinctions. However, is there a way to return different information if the node was created as to if the node was matched?

MERGE (charlie { name:'Charlie Sheen' })
ON CREATE SET charlie.name = 'Charlie'
RETURN charlie

Something like: ON CREATE RETURN 1, ON MERGE RETURN 0

like image 268
pewpewlasers Avatar asked Nov 18 '14 12:11

pewpewlasers


1 Answers

There's a relevant example on the merge page of the documentation:

MERGE (keanu:Person { name:'Keanu Reeves' })
ON CREATE SET keanu.created = timestamp()
ON MATCH SET keanu.lastSeen = timestamp()
RETURN keanu.name, has(keanu.lastSeen);

Basically this stores your 0 or 1 flag in the existence or absence of the "lastSeen" attribute.

Your query has this oddity that you're matching on "Charlie Sheen" but then modifying the value you matched (name) to be "Charlie". That's odd -- it means that because you're modifying it each time, even if you add an ON MATCH clause, it will never fire. You'll create it new each time, then modify it, guaranteeing it will be created new the next time you run that query. I would guess that it's a bad idea to modify the terms of your match later in the query, unless it's a special circumstance.

like image 175
FrobberOfBits Avatar answered Sep 22 '22 14:09

FrobberOfBits