Skip to content

Instantly share code, notes, and snippets.

@keturn
Forked from jexp/graph_gist_template.adoc
Last active July 8, 2016 00:08
Show Gist options
  • Save keturn/3d2340112abdfc695b2c83081617bd4c to your computer and use it in GitHub Desktop.
Save keturn/3d2340112abdfc695b2c83081617bd4c to your computer and use it in GitHub Desktop.
Cypher: Multiple MERGE statements are not commutative

Muliple Merge Operations are Not Commutative

Note
See graphgist view.

Introduction

From #help-cypher:

<keturn> It seems MERGE patterns can’t have the commas that are allowed in MATCH? That is, I can make one relationship with MERGE (a)-[:rel_1]→(b) and two with MERGE (a)-[:rel_1]→(b)←[:rel_2](c) but as soon as I want to add a third relationship to (b) I’m stuck with the one-dimensional limitations of ascii cypher arrows.

I can have a MERGE following another MERGE, but that … would have different semantics, right? because the MERGE is match-or-create of the entire pattern, so it could pick “match” on one line without considering the “create” required by the following line.

Maybe I can CREATE UNIQUE here; it’s documented as being able to take comma-separated paths.

<Michael> it’s gonna go away. What is the problem with splitting it into two MERGE statements? One for each rel?

Setup

CREATE
  (c_alpha:Curriculum {name: "Alpha"}),
  (c_beta:Curriculum {name: "Beta"}),
  (a_cherry:Assignment {name: "Cherry"}),
  (a_durian:Assignment {name: "Durian"}),

  (a_cherry)<-[:REQUIRES]-(p_alpha:Prereq)-[:PERMITS]->(a_durian),
  (p_alpha)-[:IN_CURRICULUM]->(c_alpha);

Merge :REQUIRES first

MATCH
  (a_cherry:Assignment {name: "Cherry"}),
  (a_durian:Assignment {name: "Durian"}),
  (c_beta:Curriculum {name: "Beta"})

MERGE
  (a_cherry)<-[:REQUIRES]-(prereq:Prereq)-[:PERMITS]->(a_durian)
MERGE
  (prereq)-[:IN_CURRICULUM]->(c_beta);

Reset

MATCH (p:Prereq) DETACH DELETE p;

MATCH
  (a_cherry:Assignment {name: "Cherry"}),
  (a_durian:Assignment {name: "Durian"}),
  (c_alpha:Curriculum {name: "Alpha"})

CREATE
  (a_cherry)<-[:REQUIRES]-(p_alpha:Prereq)-[:PERMITS]->(a_durian),
  (p_alpha)-[:IN_CURRICULUM]->(c_alpha);

Merge Curriculum first

MATCH
  (a_cherry:Assignment {name: "Cherry"}),
  (a_durian:Assignment {name: "Durian"}),
  (c_beta:Curriculum {name: "Beta"})

MERGE
  (c_beta)<-[:IN_CURRICULUM]-(prereq:Prereq)-[:PERMITS]->(a_durian)
MERGE
  (prereq)-[:REQUIRES]->(a_cherry);
@jexp
Copy link

jexp commented Jul 8, 2016

what is the problem with:

MATCH
  (a_cherry:Assignment {name: "Cherry"}),
  (a_durian:Assignment {name: "Durian"}),
  (c_alpha:Curriculum {name: "Alpha"})

CREATE (p_alpha:Prereq)
MERGE (a_cherry)<-[:REQUIRES]-(p_alpha)
MERGE (p_alpha)-[:PERMITS]->(a_durian)
MERGE (p_alpha)-[:IN_CURRICULUM]->(c_alpha);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment