Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Neo4j cypher:查找到特定类型节点的所有路径_Neo4j_Cypher - Fatal编程技术网

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

Neo4j cypher:查找到特定类型节点的所有路径,neo4j,cypher,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.nam

在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

我使用此示例数据集再现了您的场景:

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"})
然后,使用以下函数执行此查询:

// 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"}│
└────────────────────────┘

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

请注意,如果您将标签用于:a和:B节点而不是作为属性,则可以使用APOC中的某些过程来完成您想要的操作,即在每个路径的给定标签的第一个节点上停止。