Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q: How to include a WHERE clause in a MERGE statement in Neo4j

Tags:

neo4j

cypher

I have an object which has a unique but not required property, i.e. a Facebook ID. If I insert another of the object with the same name and there is an object without a Facebook ID then I assume they are the same. If there is an object with the same name but a different Facebook ID then I assume they're different and create a new object.

I've tried various statements based off the Cypher documentation but couldn't get any of them to be valid syntax.

While this example is not valid I think it gets the point across of what I'm trying to do:

MERGE (t:Thing {name: 'My Not Always Unique Name'})
WHERE EXISTS(t.facebook_id) AND t.facebook_id <> '111111111'
ON CREATE SET t.name = 'My Not Always Unique Name', 
              t.facebook_id = '111111111', 
              t.another_property = 'blah'
ON MATCH SET t.another_property = 'blah'
RETURN t;
like image 217
bassburner Avatar asked Jun 06 '16 15:06

bassburner


1 Answers

I believe I have an answer for this which depends on the UUIDs that I'm setting to the id property.

OPTIONAL MATCH (t:Thing {name: 'My Not Always Unique Name'}) WHERE t.facebook_id IS NULL OR t.facebook_id = '1111111' 
WITH t 
MERGE (s:Thing {id: COALESCE(t.id, 'e8344f24-faff-443a-ac48-b757381eddb8')}) 
ON MATCH SET s.name = 'My Not Always Unique Name', s.facebook_id = '1111111'
ON CREATE SET s.name = 'My Not Always Unique Name', s.facebook_id = '1111111' RETURN s;

Not sure if this is the best way to do this but it works for me. I'll leave this open for a little to see if anyone has a better answer.

One negative side-effect is if I'm inserting something that doesn't have a facebook_id it will need a separate merge statement.

like image 112
bassburner Avatar answered Oct 19 '22 20:10

bassburner