When you use MERGE
on matches with relationships in Cypher, the entire object is being matched or created. When a match cannot be found, the entire object is created.
For example:
MERGE (n:Page { url: "http://www.neo4j.org" })
RETURN n
Gets or creates the Page
with the property url
set to http://www.neo4j.org
. This statement will never create a duplicate node.
Now let's assume that this node now exists within the Neo4j database and then we run the following query:
MERGE (n:Page { url: "http://www.neo4j.org" })-[:CONNECTED_TO]->(test:Test { id: "test" })
RETURN *
This will attempt to match the entire pattern and if it does not exist, it will create the entire path regardless of whether or not the Page
node exists.
To resolve your issue, make sure that you use MERGE
to get or create your individual nodes first. Then you can use MERGE
to get or create the relationship between the two nodes.
Example:
MERGE (n:Page { url: "http://www.neo4j.org" })
MERGE (s:StyleSheet { url: "http://www.neo4j.org/styles/main.css" })
MERGE (n)-[:CONTAINS_STYLESHEET]->(s)
RETURN *