Reputation: 231
I expect this query to produce 7 nodes with 21 relationships.
It produces 13 nodes and 6 relationships
WITH [{address: "1", connections: []},
{address: "2",connections: ["1"]},
{address: "3",connections: ["1", "2"]},
{address: "4",connections: ["1", "2", "3"]},
{address: "5",connections: ["1", "2", "3", "4"]},
{address: "6",connections: ["1", "2", "3", "4", "5"]},
{address: "7",connections: ["1", "2", "3", "4", "5", "6"]}] AS seeds
UNWIND seeds AS seed
MERGE (source:Address { address: seed.address })
WITH seed.connections AS connections
UNWIND connections AS connection
MATCH (target:Address) WHERE target.address = connection
MERGE (source)-[:CONNECTS_TO]->(target)
I tried a dozen+ variations including FOREACH.
Am I wrong thinking this is possible?
Upvotes: 1
Views: 347
Reputation: 231
As @InverseFalcon describes, the final query looks like this
WITH [{address: "1", connections: []},
{address: "2",connections: ["1"]},
{address: "3",connections: ["1", "2"]},
{address: "4",connections: ["1", "2", "3"]},
{address: "5",connections: ["1", "2", "3", "4"]},
{address: "6",connections: ["1", "2", "3", "4", "5"]},
{address: "7",connections: ["1", "2", "3", "4", "5", "6"]}] AS seeds
UNWIND seeds AS seed
MERGE (source:Address { address: seed.address })
WITH source, seed.connections AS connections
UNWIND connections AS connection
MATCH (target:Address) WHERE target.address = connection
MERGE (source)-[:CONNECTS_TO]->(target)
Upvotes: 0
Reputation: 30407
This is very close, there is one thing we need to correct for this query to work as expected: the scope of your source
variable. This goes out of scope in the middle of your query on the WITH:
...
WITH seed.connections AS connections
...
source
isn't included in the WITH, so it goes out of scope. The source
in your the last line in your MERGE isn't bound to any prior node, so where such a pattern doesn't exist between some node and the target, a new blank node will be created as the starting node of the relationship.
To fix this, we need to include source
in your WITH so it stays in scope:
...
WITH source, seed.connections AS connections
...
Upvotes: 3