天天看点

neo4j使用cypher求多个结点两两间的最短路径

with [3105, 200025928, 200025929, 151286502, 135660351] as id_list
match (v:vertices) where v.id in id_list
  with collect(v) as nodes
  unwind nodes as source
  unwind nodes as target
  with source,target where id(source)<id(target)
match paths = shortestPath((source)-[:HOLDER|MANAGER*0..2]-(target)) where all(x in nodes(paths) where x.id<>3105)
  with paths limit 20000
  return paths
           
  1. 使用with定义一个列表变量,里面是所有的点;
  2. 使用match匹配出所有的结点,将结点放到列表中,注意这里列表中的元素是结点类型,上面是业务id;
  3. 使用两个unwind再次将结点列表打散到行,之前提到过两个unwind的结点也是以笛卡尔积的方式返回的(看这篇博客),所以这里是两两的任意组合,甚至两个结点相同的组合,实际上我们这里求最短路径1到2和2到1肯定是一样的,所以用id(source)<id(target)来去除一半;
  4. 最后是shortestPath函数,里面的source,target就是前面的组合;

注意一点就是如果在求最短路径shortestPath的时候如果最短路径有条件则where一定要直接跟在shortestPath后,不能先with出来后再where,这样可能不是你想要的结果(看这篇博客)。

继续阅读