首页 > 解决方案 > 为每个 cypher-neo4j 创建关系

问题描述

我的后端有一个触发查询的语句。该语句正在检查我的 neo4j 数据库中存在的最大插槽数,然后再创建 50 个插槽,每个插槽都有一个。

MATCH (s:Slot)
WITH MAX(s.number) AS maxSlotNumber
WITH COALESCE(maxSlotNumber, 0) AS lastExistingSlotNumber
FOREACH (i in range(lastExistingSlotNumber+1, lastExistingSlotNumber+50) | CREATE (:Slot {number: i}))

我现在需要的是,这 50 个新创建的插槽中的每一个都将与一个名为 box 的新节点建立关系。这背后的原理是每个盒子包含 50 个插槽。如果 50 个插槽已满,我将填充我的后端并且没有其他可用插槽,则此查询应创建 50 个新插槽和 1 个盒子。我试过了:

MATCH (s:Slot)
CREATE (b:Box{number:1})
WITH MAX(s.number) AS maxSlotNumber
WITH COALESCE(maxSlotNumber, 0) AS lastExistingSlotNumber
FOREACH (i in range(lastExistingSlotNumber+1, lastExistingSlotNumber+50) | CREATE (:Slot {number: i})-[:in_box]->(b))

但是这个语句创建了 100 个新节点,每个节点都与自己的盒子有关系。 图表链接

所需的结果应该在图中看起来像这样,但当然有 50 个插槽,我只画了 3 个。

第二个问题是。您如何建议创建新盒子?在上面的代码中,我是硬编码数字 1。但是当 box1 的 50 个插槽已满时,应该创建一个新的盒子,其编号为 2,插槽从 51 到 100。

标签: neo4jcypherrelationship

解决方案


The first problem with your query is that you lose b when you define maxSlotNumber. This will fix it:

CREATE (b:Box{number:1})
WITH b
OPTIONAL MATCH (s:Slot)
WITH COALESCE(MAX(s.number), 0) AS lastExistingSlotNumber, b
FOREACH (i in range(lastExistingSlotNumber+1, lastExistingSlotNumber+50) | CREATE (:Slot {number: i})-[:IN_BOX]->(b))

As for the creation of the box node, you can do something like this:

OPTIONAL MATCH (b:Box) WITH COALESCE(MAX(b.number), 0)+1 as lastBoxNumber
CREATE (b:Box {number: lastBoxNumber})
WITH b
OPTIONAL MATCH (s:Slot)
WITH COALESCE(MAX(s.number), 0) AS lastExistingSlotNumber, b
FOREACH (i in range(lastExistingSlotNumber+1, lastExistingSlotNumber+50) | CREATE (:Slot {number: i})-[:IN_BOX]->(b))

By the way, if you don't like FOREACH, you can do this instead:

OPTIONAL MATCH (b:Box) WITH COALESCE(MAX(b.number), 0)+1 as lastBoxNumber
CREATE (b:Box {number: lastBoxNumber})
WITH b
OPTIONAL MATCH (s:Slot)
WITH COALESCE(MAX(s.number), 0) AS lastExistingSlotNumber, b
WITH range(lastExistingSlotNumber+1, lastExistingSlotNumber+50) as newNumbers, b
UNWIND newNumbers as newNumber
WITH newNumber, b
CREATE (:Slot {number: newNumber})-[:IN_BOX]->(b)

推荐阅读