将阵列与Cypher(Neo4j)组合在一起

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将阵列与Cypher(Neo4j)组合在一起相关的知识,希望对你有一定的参考价值。

当我有一个看起来像这样的字符串:

"app-server/src/test/java/de/something/"

我如何得到任何可能的组合,如:

app-server/, app-server/src, app-server/src/test, ....

我显然可以用'/'拆分它然后我有一个部件的数组。我也可以手动附加所有这些,然后过滤null

...
WITH split(package.path,'/')[..size(split(package.path,'/'))-1]
WITH pathParts,
pathParts[0] AS p01,
pathParts[0] + '/' + pathParts[1] AS p02,
pathParts[0] + '/' + pathParts[1] + '/' + pathParts[2] AS p03,
...

替代:

WITH pathParts[0] AS p01,
reduce(s = pathParts[0], x IN pathParts[1..2] | s + '/' + x) + '/' AS p02,
reduce(s = pathParts[0], x IN pathParts[1..3] | s + '/' + x) + '/' AS p03,
reduce(s = pathParts[0], x IN pathParts[1..4] | s + '/' + x) + '/' AS p04,
...

但这些都是可怕的解决方案。


我还想从以下所有方面创建父子关系:

(childPackage:Package)-[:HAS_PARENT]->(parentPackage:Package)

例如(app-server/src)-[:HAS_PARENT]->(app-server/)

答案

有必要拆分字符串,从数组中删除空元素,并在连接所有以前的元素时遍历每个元素:

WITH "app-server/src/test/java/de/something/" AS path
WITH FILTER(p in SPLIT(path, "/") WHERE SIZE(p) > 0) AS pathParts
UNWIND RANGE(0, SIZE(pathParts)-1) AS i
RETURN REDUCE(acc = "", p IN pathParts[0..i+1] | acc + p + '/') AS pathPart

为了链接它们,第二次进行是不会有问题的:

WITH "app-server/src/test/java/de/something/" AS path
WITH FILTER(p in SPLIT(path, "/") WHERE SIZE(p) > 0) AS pathParts
UNWIND RANGE(0, SIZE(pathParts)-1) AS i
WITH collect(REDUCE(acc = "", p IN pathParts[0..i+1] | acc + p + '/')) AS pathParts

UNWIND RANGE(1, SIZE(pathParts)-1) AS i
  MERGE (P1:Package {path: pathParts[i-1]})
  MERGE (P2:Package {path: pathParts[i]})
  MERGE (P2)-[r:hasParent]->(P1)
RETURN P1, r, P2

以上是关于将阵列与Cypher(Neo4j)组合在一起的主要内容,如果未能解决你的问题,请参考以下文章

Neo4j:如何删除与 cypher 的特定关系?

cypher neo4j - 收集一组节点

Neo4j/Cypher 测试数据请求

如何往neo4j中批量插入cypher语句

如何优化Neo4J Cypher查询?

neo4j cypher 节点可以模糊匹配么