简体   繁体   English

Neo4j - 如何找到两个节点之间的最短路径

[英]Neo4j - How to find shortest path between two nodes

I have an extraordinarily basic question about Neo4j.我有一个关于 Neo4j 的非常基本的问题。

I've imported a simple dataset which contains a number of nodes as 'example_nodes' like so:我导入了一个简单的数据集,其中包含许多节点作为“example_nodes”,如下所示:

sourceId , targetId sourceId , targetId sourceId

Thus, my database has a simple two column table of sources and targets.因此,我的数据库有一个简单的两列源和目标表。

How could I find the shortest path between an arbitrary sourceId and targetId ?如何找到任意sourceIdtargetId之间的最短路径?

My initial attempt is along the lines of:我最初的尝试是这样的:

MATCH (source:example_nodes),(target:example_nodes),
p = shortestPath((source)--(target))
WHERE (source.sourceId) = 1234 AND (target.targetId) = 5678
return p

Which returns no records, when I can clearly see the first line in my database is itself a single path:当我可以清楚地看到数据库中的第一行本身就是一条路径时,它不返回任何记录:

{"sourceId":"1234","targetId":"5678"}

What am I doing wrong?我究竟做错了什么? Do I need to create all the relationships before I can run a query (as all I've done so far is imported the nodes and created indices)我是否需要在运行查询之前创建所有关系(因为到目前为止我所做的只是导入了节点并创建了索引)

You should find the source and target first, and then invoke shortestpath :您应该首先找到sourcetarget ,然后调用shortestpath

MATCH (source:example_nodes),(target:example_nodes)
WHERE source.sourceId = 1234 AND target.targetId = 5678
MATCH p = shortestPath((source)-[*]-(target))
return p;

If this query runs too long, try limiting the maximum path length searched.如果此查询运行时间过长,请尝试限制搜索的最大路径长度。 For example, use [*..8] to limit the length to 8.例如,使用[*..8]将长度限制为 8。

一个更紧凑和干净的查询是:

match s=shortestPath((src {sourceId:1234})-[*]-(dst {targetId:5678})) return s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM