为啥 Cypher 中的变量需要提醒 `WITH` 子句?

Posted

技术标签:

【中文标题】为啥 Cypher 中的变量需要提醒 `WITH` 子句?【英文标题】:Why does the `WITH` clause need to be reminded about the variable in Cypher?为什么 Cypher 中的变量需要提醒 `WITH` 子句? 【发布时间】:2021-12-11 00:52:39 【问题描述】:

group 属性中说我有值cat dogchicken egg。我想将group 中值的初始字符分配给属性gid,即cdce。这是我的查询:

match (n) 
with split(n.group," ") as array 
set n.gid=left(array[0],1)+left(array[1],1) 
return n.name, n.gid;

我收到此错误:

Variable `n` not defined (line 2, column 48 (offset: 48))
"match (n) with split(n.group," ") as array set n.gid=left(array[0],1)+left(array[1],1) return n.name, n.gid;"
                                                ^

但是,这是可行的:

match (n) 
with n, split(n.group," ") as array 
set n.gid=left(array[0],1)+left(array[1],1) 
return n.name, n.gid;

我不明白这是为什么?我查看了WITH 文档,但没有发现任何问题?

【问题讨论】:

【参考方案1】:

来自WITH 文档本身

重要的是要注意 WITH 影响范围内的变量。任何 未包含在 WITH 子句中的变量不会转移到 查询的其余部分。

在第一个查询中,

match (n) 
with split(n.group," ") as array 
...

只有array 被转移到查询的其余部分,n 被遗忘。这就是你得到错误的原因。

【讨论】:

我明白了。但是假设它携带变量,会出现什么问题? 在内部,密码执行引擎节省了存储这些变量的内存。一些变量可能有很多与之相关的数据。另外,我想这会节省一些处理时间。

以上是关于为啥 Cypher 中的变量需要提醒 `WITH` 子句?的主要内容,如果未能解决你的问题,请参考以下文章

带有两个 OPTIONAL MATCH 和两个单独的 WITH 语句的 Cypher 查询

如何在neo4j Cypher中获取列表的子集

Neo4j Cypher - 有条件的 With 子句查询

为啥 try-with-resources 不能与字段变量一起使用?

如何使用Cypher只在Neo4j中获得朋友的朋友

Cypher学习《一》