1
votes

I have three independent category trees that is going to import at any order using cypher.

  • (c2)-[PARENT]->(c1)
  • (c4)-[PARENT]->(c3)->[PARENT]->(c1)
  • (c5)-[PARENT]->(c3)

enter image description here

and need to create the structure mentioned in the figure using the query . The query I written is

MERGE (:Category {name:'c2'})-[:PARENT]->(:Category {name:'c1'})
MERGE (:Category {name:'c4'})-[:PARENT]->(:Category {name:'c3'})-[:PARENT]->(:Category {name:'c1'})
MERGE (:Category {name:'c5'})-[:PARENT]->(:Category {name:'c3'})

But above query creating duplicate category c1 for second merge query which I need to avoid . Also the third query should create new category c3 which is happening correctly now.

One more thing is that these three cypher query should be independently executable .eg: System already have a category tree (c2)-[PARENT]->(c1) and need to add (c4)-[PARENT]->(c3)->[PARENT]->(c1) in to the category tree using cypher.

I can go with some similar approach mention in the documentation http://neo4j.com/docs/stable/cypherdoc-linked-lists.html . but just want to check is there a simple way to solve this problem

3
The behavior is normal because you don't use identifiers and thus Cypher can not know if it is a new c1 node or node. Here is a very nice explanation about MERGE graphaware.com/neo4j/2014/07/31/cypher-merge-explained.html - Christophe Willemsen

3 Answers

1
votes

Try this (without typo in third query)

MERGE (:Category {name:'c2'})-[:PARENT]->(c1:Category {name:'c1'})
MERGE (:Category {name:'c4'})-[:PARENT]->(:Category {name:'c3'})-[:PARENT]->(c1)
MERGE (:Category {name:'c5'})-[:PARENT]->(:Category {name:'c3'})
0
votes

You can use single query to avoid duplicate entry
MERGE (:Category {name:'c4'})-[:PARENT]->(:Category {name:'c3'})-[:PARENT]->(:Category {name:'c1'})<-[:PARENT]-(:Category {name:'c2'})
MERGE (:Category {name:'c5'})-[:PARENT]->(:Category {name:'c5'})

0
votes

I solve the problem by adding one more label called Root for the top level category .

Cypher query for first tree - (c2)-[PARENT]->(c1)

MERGE (nc1:Category:Root{name:'c1'})
MERGE (nc3:Category {name:'c2'})-[:PARENT]->(nc1)

Cypher query for second tree - (c4)-[PARENT]->(c3)->[PARENT]->(c1)

MERGE (nc1:Category:Root{name:'c1'})
MERGE (nc3:Category {name:'c3'})-[:PARENT]->(nc1)
MERGE (:Category {name:'c4'})-[:PARENT]->(nc3)

Cypher query for third tree - (c5)-[PARENT]->(c3)

MERGE (nc3:Category:Root{name:'c3'})
MERGE (nc5:Category {name:'c5'})-[:PARENT]->(nc3)