neo4j使用cypher查询路径避免出现环路
neo4j在使用可变长路径找两个点之前的所有路径时,会返回包含环路的路径(一个点在路径中出现两次),如下面的语句:
MATCH path = (x)-[:KNOWS*]-(y)
可能返回a->b->c->d->b->e这样的路径,如图:
解决方法:
纯cypher实现
- MATCH path = (x)-[:KNOWS*]-(y)
- UNWIND NODES(path) AS n
- WITH path,
- SIZE(COLLECT(DISTINCT n)) AS testLength
- WHERE testLength = LENGTH(path) + 1
- RETURN path
使用apoc
- MATCH path = (x)-[:KNOWS*]-(y)
- WHERE SIZE(apoc.coll.toSet(NODES(path))) = LENGTH(path) + 1
- RETURN path
或者也可以这样:
- MATCH path = (x)-[:KNOWS*]-(y)
- WHERE apoc.coll.duplicates(NODES(path)) = []
- RETURN path
本文链接:https://blog.csdn.net/wry2008wry/article/details/80899860