3

I've a neo4j schema in which I've 3 nodes. e.g. p,b,c

I want to write a Merge query such that

MERGE (p)-[:has_b]->(b),
MERGE (p)-[:has_c]->(c1),
MERGE (p)-[:has_c]->(c2)

where c1 and c2 are instance of c node having different property values.

i.e. Merge on all three relationships.

If any of 3 merge queries creates a new node, all relationships should use newly created p node.

I can achieve this if I had only two relationships using

(c)<-[:has_c]-MERGE (p)-[:has_b]->(b)

Any suggestions how to do it for 3 relationships as in my case?

FYI, I'm using py2neo which isn't helping at all.

randomuser
  • 1,201
  • 2
  • 10
  • 19

1 Answers1

0

Nodes don't have instances. A node is a node and it has a label.

You can MERGE your nodes first to make sure they exist and that all relationships use the same p:

MERGE (p:LabelA {k: "v"})
MERGE (b:LabelB {k: "v"})
MERGE (c1:LabelC {k: "v"})
MERGE (c2:LabelC {k: "v"})
MERGE (p)-[:has_b]->(b)
MERGE (p)-[:has_c]->(c1)
MERGE (p)-[:has_c]->(c2)

This will create the nodes and relationships only once.

Martin Preusse
  • 9,151
  • 12
  • 48
  • 80
  • this will fetch p node having {k:v}, that may or may not having has_b/has_c relationships. Basically, I want p node to check it's relationships with b, c1 and c2 and return the old p node if all three relationships exist and have same properties, and create a new node even if any one of three relationships are new (if property of end_node is different, relationship name can be same). Do let me know if you want me to explain more. – randomuser Feb 03 '16 at 07:15
  • 1
    similar to what (c:LabelC {c:'d'})<-[:has_c]-MERGE (p:LabelP {p:'q'})-[:has_b]->(b:LabelB {b:'b'}) provides. But this is for only two realtionships. I want this functionality for 3 realtionships – randomuser Feb 03 '16 at 07:21
  • basically i want MERGE query for 3 relationships in one query – randomuser Feb 03 '16 at 10:00
  • Don't get it. They query I posted *does* `MERGE` 3 relationships. It will return the old p if existing or create a new one. The query you mention in your second comment does not make sense, what is the `MERGE` doing? – Martin Preusse Feb 03 '16 at 10:40
  • sorry query in 2nd comment should be MERGE (c:LabelC {c:'d'})<-[:has_c]-(p:LabelP {p:'q'})-[:has_b]->(b:LabelB {b:'b'}) – randomuser Feb 03 '16 at 11:05
  • Just do it separately. And note that `MERGE` might create duplicate nodes when used with complex patterns: http://neo4j.com/docs/stable/query-merge.html#merge-merge-on-a-relationship-between-an-existing-node-and-a-merged-node-derived-from-a-node-property – Martin Preusse Feb 03 '16 at 11:37
  • I'm okay with duplicate p nodes. Need merge query for a node having 3 relationships – randomuser Feb 03 '16 at 12:13