图算法示例

有关图算法用法的详细信息,请参阅 Neo4j Javadocs for org.neo4j.graphalgo.GraphAlgoFactory.

示例中使用的源代码位于: PathFindingDocTest.java

计算两个节点之间的最短路径(最少的关系数)

Node startNode = tx.createNode();
Node middleNode1 = tx.createNode();
Node middleNode2 = tx.createNode();
Node middleNode3 = tx.createNode();
Node endNode = tx.createNode();
createRelationshipsBetween( startNode, middleNode1, endNode );
createRelationshipsBetween( startNode, middleNode2, middleNode3, endNode );

// Will find the shortest path between startNode and endNode via
// "MY_TYPE" relationships (in OUTGOING direction), like f.ex:
//
// (startNode)-->(middleNode1)-->(endNode)
//
PathFinder<Path> finder = GraphAlgoFactory.shortestPath( new BasicEvaluationContext( tx, graphDb ),
    PathExpanders.forTypeAndDirection( ExampleTypes.MY_TYPE, Direction.OUTGOING ), 15 );
Iterable<Path> paths = finder.findAllPaths( startNode, endNode );

使用 Dijkstra 源目标最短路径,您可以计算节点 A 和 B 之间的最便宜路径,其中每个关系都有权重(例如,成本),并且找到成本最低的路径。

PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra( new BasicEvaluationContext( tx, graphDb ),
    PathExpanders.forTypeAndDirection( ExampleTypes.MY_TYPE, Direction.BOTH ), "cost" );

WeightedPath path = finder.findSinglePath( nodeA, nodeB );

// Get the weight for the found path
path.weight();

使用 A* 最短路径,您可以计算节点 A 和 B 之间的最便宜路径,其中“最便宜”是指,例如,在道路网络中,节点 A 和 B 之间长度最短的路径。这是示例图

A* algorithm example graph
Node nodeA = createNode( "name", "A", "x", 0d, "y", 0d );
Node nodeB = createNode( "name", "B", "x", 7d, "y", 0d );
Node nodeC = createNode( "name", "C", "x", 2d, "y", 1d );
Relationship relAB = createRelationship( nodeA, nodeC, "length", 2d );
Relationship relBC = createRelationship( nodeC, nodeB, "length", 3d );
Relationship relAC = createRelationship( nodeA, nodeB, "length", 10d );

EstimateEvaluator<Double> estimateEvaluator = ( node, goal ) ->
{
    double dx = (Double) node.getProperty( "x" ) - (Double) goal.getProperty( "x" );
    double dy = (Double) node.getProperty( "y" ) - (Double) goal.getProperty( "y" );
    return Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
};
PathFinder<WeightedPath> astar = GraphAlgoFactory.aStar( new BasicEvaluationContext( tx, graphDb ),
        PathExpanders.allTypesAndDirections(),
        CommonEvaluators.doubleCostEvaluator( "length" ), estimateEvaluator );
WeightedPath path = astar.findSinglePath( nodeA, nodeB );