Neo4j:过滤路径以包含仅具有唯一中间节点的路径

时间:2018-05-14 22:35:59

标签: neo4j cypher neo4j-apoc

我在我的图表上使用了以下neo4j cypher查询:

MATCH (start:N1{id:'xyz'})
CALL apoc.path.expandConfig(start, {sequence:'N1, a>, N2, b>, N3, c>, 
N4', maxLevel:3}) YIELD path
RETURN path
ORDER BY length(path) DESC

这将返回所有路径,如

X-a->Y-b->Z-c->**A**
X-a->Y-b->Z-c->**B**
X-a->Y-b->Z-c->**C**
X-a->Y-b->Z
X-a->Y
X
X-a->V
X-a->W

但我想要返回的是路径没有重复的短路径,因为它们已经包含在更长的路径中。

这是我想要的输出:

X-a->Y-b->Z-c->**A**
X-a->Y-b->Z-c->**B**
X-a->Y-b->Z-c->**C**
X-a->V
X-a->W

有人可以帮忙吗?我是Neo4j的新手

1 个答案:

答案 0 :(得分:2)

目前,cypher没有语言功能来检查一条路径是否嵌套在另一条路径中。但是你可以使用一个简单的技巧:将路径关系的ID转换为文本并与所有其他ID进行比较:

MATCH (start:N1{id:'xyz'})
CALL apoc.path.expandConfig(start, {sequence:'N1, a>, N2, b>, N3, c>, 
N4', maxLevel:3}) YIELD path
WITH path ORDER BY LENGTH(path) ASC
WITH COLLECT(path) AS paths
UNWIND paths AS path
WITH 
  paths, path, 
  apoc.text.join([r in relationships(path)| '' + ID(r)],'.') AS pathTR
  WHERE ALL(p IN paths WHERE 
    CASE 
      WHEN SIZE(pathTR) > 0 AND path <> p AND
           apoc.text.join([r IN relationships(p)| '' + ID(r)],'.') CONTAINS pathTR 
      THEN FALSE 
      ELSE TRUE 
    END 
  )
RETURN path
ORDER BY LENGTH(path) DESC