neo4j - 为每个 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。
解决方案
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)
推荐阅读
- youtube - Discord.js - 音乐机器人。它播放任何视频,但不播放受版权保护的音乐
- excel - 使用 Internet Explorer 登录
- listview - 一起滚动图表和 ListView
- python - 我无法让我的代码打印出正确的信息。我只是永远打印一个数字
- python - file.write() 和 file.writelines() Python 之间的区别
- jenkins - 如何避免在第一次运行时在 Jenkinsfile 中取消存储期间丢失存储失败?
- assembly - 为什么在 LEA 中使用方括号?
- c# - 使用量子位进行球坐标旋转
- rest - 无法使用 tomcat、spring boot 和 Rest 访问 swagger UI
- javascript - Salesforce - 在 Lightning 的自定义 HTML 电子邮件模板中添加 If-Else 语句