UNWIND与子UNWIND产生错误的节点和关系

时间:2017-04-24 14:20:44

标签: neo4j cypher

我希望这个查询产生7个节点,其中包含21个关系。

它产生13个节点和6个关系

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)

我尝试了十几种+变种,包括FOREACH。

我认为这是可能的吗?

2 个答案:

答案 0 :(得分:2)

这非常接近,我们需要纠正一个问题,让这个查询按预期工作:source变量的范围。在WITH:

的查询过程中,这超出了范围
...
WITH seed.connections AS connections
...

source未包含在WITH中,因此超出了范围。 MERGE最后一行中的source未绑定到任何先前节点,因此在某个节点和目标之间不存在这种模式的情况下,将创建一个新的空白节点作为关系的起始节点。

要解决此问题,我们需要在您的WITH中加入source,以便它保持在范围内:

...
WITH source, seed.connections AS connections
...

答案 1 :(得分:0)

正如@InverseFalcon所描述的那样,最终查询看起来像这样

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)