Neo4j3.5学习笔记——图算法Graph Algorithm Examples

跟着官网代码学习.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 );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值