-
Notifications
You must be signed in to change notification settings - Fork 137
Paths
Path finding between two nodes is the most basic way to query a graph database. neo4jphp provides a simple way to find and filter paths between nodes.
If you have two nodes, the simplest way to find a path between them is with the Node::findPathsTo()
method:
$paths = $startNode->findPathsTo($endNode)
->getPaths();
Node::findPathsTo()
returns a PathFinder
object, which can be used to further refine the search criteria. It is possible to restrict the paths that will be found by direction and type. The following code finds all outgoing "KNOWS" relationships:
$paths = $startNode->findPathsTo($endNode, 'KNOWS', Relationship::DirectionOut)
->getPaths();
By default, the maximum length of a path that will be searched is 1 relationship long. The path length can be increased with the PathFinder::setMaxDepth()
method:
$paths = $startNode->findPathsTo($endNode, 'KNOWS', Relationship::DirectionOut)
->setMaxDepth(5)
->getPaths();
PathFinder::getPaths()
will return an array of Path
objects, and PathFinder::getSinglePath()
will return a single Path
object or null if there is no path. Each path is an ordered collection of nodes and relationships. It is possible to loop through either the nodes or relationships:
$path = $startNode->findPathsTo($endNode, 'KNOWS', Relationship::DirectionOut)
->getSinglePath();
// Loop through the nodes - the default
foreach ($path as $node) {
echo $node->getId() . "\n";
}
echo "The path is " . count($path) . "nodes long\n";
// Loop through the relationships
$path->setContext(Path::ContextRelationship);
foreach ($path as $rel) {
echo $rel->getId() . "\n";
}
echo "The path is " . count($path) . "relationships long\n";
By default, the path finder will return the shortest path or paths found. Path length is determined by the number of relationships in the path.
There are several other path finding algorithms:
- all paths - any path, regardless of length, even if the path goes through the same node more than once
- all simple paths - any path, regardless of length, that only goes through each node in the path once
- dijkstra - the least cost path
Dijkstra paths use a property of the relationships in the path to determine how much a given path "costs" and returns the lowest cost path or paths. The path length is ignored in this case; two paths, one of length 2 and one of length 5, that both have the same cost will both be returned. There are a few additional path finder methods that can be used for a Dijkstra path:
$paths = $startNode->findPathsTo($endNode)
->setAlgorithm(PathFinder::AlgorithmDijkstra)
->setMaxDepth(5)
->setCostProperty('distance')
->setDefaultCost(2)
->getPaths();
The above code searches for all Dijkstra paths, using the "distance" property of each relationship to determine a given path's cost. If a relationship does not have a "distance" property, a default cost of 2 is used for that relationship.