跟着官网代码学习.jpg–jdk 1.8.0 & neo4j 3.5
https://neo4j.com/docs/java-reference/current/java-embedded/
目标:得到A和 B两个节点之间的最短路径
- 由于我尚未掌握junit,因此上传至github上的代码与官网的代码不尽相同。
1. 创建一个图数据库:
1)通过创建T类型
为PropertyContainer
的子类来设置setProperties方法,使得createNode
方法能够实现("property类型”,“对应具体值”,"property类型”,“对应具体值”,…)的方式创建Node。
private Node createNode(final Object... properties) {
return setProperties(graphDb.createNode(), properties);
}
private <T extends PropertyContainer> T setProperties
(final T entity, final Object[] properties) {
for(int i = 0; i < properties.length; i++) {
String key = properties[i++].toString();
Object value = properties[i];
entity.setProperty(key, value);
}
return entity;
}
2) 建立Node以及Node之间的Relationship。
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 );
private Relationship createRelationship(final Node start, final Node end, final Object... properties) {
return setProperties(start.createRelationshipTo(end, RelType.MY_TYPE), properties);
}
2. 计算最短路径:
1) 使用Dijkstra方法计算最短路径:
public WeightedPath findCheapestPathWithDijkstra(final Node nodeA, final Node nodeB) {
PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
PathExpanders.forTypeAndDirection(RelType.MY_TYPE, Direction.BOTH), "length");
WeightedPath path = finder.findSinglePath(nodeA, nodeB);
path.weight();
return path;
}
2) 使用aStar方法计算你最短路径:
EstimateEvaluator<Double> estimateEvaluator = new EstimateEvaluator<Double>()
{
@Override
public Double getCost( final Node node, final Node goal )
{
double dx = (Double) node.getProperty( "x" ) - (Double) goal.getProperty( "x" );
double dy = (Double) node.getProperty( "y" ) - (Double) goal.getProperty( "y" );
double result = Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
return result;
}
};
PathFinder<WeightedPath> astar = GraphAlgoFactory.aStar(
PathExpanders.allTypesAndDirections(),
CommonEvaluators.doubleCostEvaluator( "length" ), estimateEvaluator );
WeightedPath path = astar.findSinglePath( nodeA, nodeB );