Neo4j cypher:查找到特定类型节点的所有路径

时间:2017-12-07 17:15:49

标签: neo4j cypher

在Neo4j中,我已经存储了类型为A和B的节点的数据。在2个节点A之间可能有很多类型为B的节点。我想为从给定节点A传出的每个路径获取类型A的第一个节点。我在下面发布了示例结构。

  /->A2->A3
A1-->A4->A5
  \->B1->A6

对于输入:A1,我希望我的查询只返回A2,A4和A6。

我现在正在使用的查询如下:

 MATCH p=(source:Node ) - [:relation*] -> (target:Node) WHERE
 source.name = "A1" AND target.type = "A" RETURN target

然而它返回我想要摆脱的节点A3和A5。

1 个答案:

答案 0 :(得分:1)

我已使用此示例数据集重现您的方案:

create (root:Node {name : "A1", type: "A"})-[:LINKED_TO]->(:Node{name : "A2", type: "A"})-[:LINKED_TO]->(:Node{name : "A3", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "A4", type: "A"})-[:LINKED_TO]->(:Node{name : "A5", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "B1", type: "B"})-[:LINKED_TO]->(:Node{name : "A6", type: "A"})

然后,此查询使用filter()函数:

// MATCH all paths between source and target, starting from 2 hops.
// target node should be the last node of the path.
MATCH p=(source:Node)-[:LINKED_TO*]->(target:Node)
WHERE source.name = "A1" AND target.type = "A" AND NOT (target)-->()
// grouping by path, I have filtered the nodes of each path, getting only ones that have type = "A"
// then I get the first one by index (index [0])
WITH p, filter(node IN nodes(p)[1..] WHERE node.type = "A")[0] as firstA
// return the firstA node
RETURN firstA

输出:

╒════════════════════════╕
│"firstA"                │
╞════════════════════════╡
│{"name":"A6","type":"A"}│
├────────────────────────┤
│{"name":"A4","type":"A"}│
├────────────────────────┤
│{"name":"A2","type":"A"}│
└────────────────────────┘

提示:您可以为表示类型的每个节点添加另一个标签,而不是名为type的属性,例如:A和:B。请记住,标签非常适合将节点分组到集合中。此外,节点可以有多个标签。