Neo4J-Cypher:多个节点之间的最短路径 [英] Neo4J - Cypher: shortest path between multiple nodes

查看:935
本文介绍了Neo4J-Cypher:多个节点之间的最短路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有4个节点:

{id:1, name:"one"} {id:2, name:"two"} {id:3, name:"three"} {id:4, name:"four"}

{id:1, name:"one"} {id:2, name:"two"} {id:3, name:"three"} {id:4, name:"four"}

假设节点1链接到节点2,节点2链接到3,3到4,则结果将类似于:

Suppose node 1 is linked to node 2, node 2 to 3, 3 to 4 so the result would be something like:

(1)-->(2)-->(3)-->(4)

如何以任何给定顺序获得多个给定节点之间的最短路径?几个例子:

How would I be able to get the shortest path between multiple given nodes in any given order? A few examples:

findShortestPath(2,4,3)应导致:(2)-->(3)-->(4)

findShortestPath(3,1)应导致:(1)-->(2)-->(3)

findShortestPath(4,1)应导致:(1)-->(2)-->(3)-->(4)

findShortestPath(3,2)应导致:(2)-->(3)

我已经尝试过类似的方法,但是我感觉自己走错了方向,这并不是最有效的解决方案.请注意,我的查询是通过编程方式构造的,因为它可以包含任意数量和种类的节点.

I have tried something like this, but I feel like I'm going the wrong way and it's not the most performant solution. Note that my query gets constructed programmatically since it can contain any number and kind of nodes.

如果输入为:(2),(3),(1)

If the input would be: (2),(3),(1)

这将导致double for循环构造如下内容:

That would result in a double for loop constructing something like this:

match p=allShortestPaths((p2)-[*]-(p3)),allShortestPaths((p2)-[*]-(p1)),allShortestPaths((p3)-[*]-(p1)) where p1.name="Keanu Reeves" and p2.name="Gene Hackman" and p3.name="Clint Eastwood" return p;

我的问题是我不能为allShortestPaths()函数提供多个节点.只允许2个具有1个关系的节点.

My problem is that I can't provide multiple nodes to the allShortestPaths() function. Only 2 nodes with 1 relation is allowed.

推荐答案

您可以遍历所有节点对,并检查其他节点是否位于这些对之间的可能路径中:

You can go through all the pairs of nodes, and check that the other nodes are in the possible paths between these pairs:

WITH ["Keanu Reeves", "Gene Hackman", "Clint Eastwood"] AS names
UNWIND names AS nn
  MATCH (n {name: nn})
  WITH collect(n) AS nds

UNWIND nds AS n1
  UNWIND nds AS n2
  WITH nds, n1, n2 WHERE id(n1) > id(n2)
    MATCH path = allShortestPaths((n1)-[*]-(n2))
    WITH nds, path WHERE ALL(n IN nds WHERE n IN nodes(path))
RETURN path ORDER BY length(path) ASC

这篇关于Neo4J-Cypher:多个节点之间的最短路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆