RT 对一个示例数据集采用了最短路径算法,发现该算法对无权重图和有权重图的输出路径一样,其中有权重情况下的输出结果和实际正确路径不符 示例数据地址: https://github.com/neo4j-graph-analytics/book/raw/master/data/transport-relationships.csv https://github.com/neo4j-graph-analytics/book/raw/master/data/transport-nodes.csv 代码:
MATCH (source:Place {id:‘Amsterdam’}),(target:Place {id:‘London’}) CALL gds.shortestPath.dijkstra.stream({nodeProjection:‘Place’,relationshipProjection:‘EROAD’,relationshipProperties:‘distance’,sourceNode:source,targetNode:target,relationshipWeightProperty:‘distance’}) YIELD nodeIds,costs WITH [nodeId in nodeIds|gds.util.asNode(nodeId).id] AS nodeName,costs AS costs, size(nodeIds) AS siz UNWIND range(0,siz-1) AS n RETURN nodeName[n] AS city, costs[n] AS step
上述代码输出结果如下图:
而正确的结果应该如下图:
请问以上状况是什么原因造成的,应该如何修复?
导入节点: WITH “https://github.com/neo4j-graph-analytics/book/raw/master/data” AS base WITH base + “/transport-nodes.csv” AS uri LOAD CSV WITH HEADERS FROM uri AS row MERGE (place:Place {id:row.id}) SET place.latitude = toFloat(row.latitude), place.longitude = toFloat(row.latitude), place.population = toInteger(row.population) 导入关系: WITH “https://github.com/neo4j-graph-analytics/book/raw/master/data/” AS base WITH base + “/transport-relationships.csv” AS uri LOAD CSV WITH HEADERS FROM uri AS row MATCH (origin:Place {id: row.src}) MATCH (destination:Place {id: row.dst}) MERGE (origin)-[:EROAD {distance: toInteger(row.cost)}]->(destination)
上面的导入语句是来自于《Graph Algorithms:Practical Examples in Apache Spark and Neo4j》这本书上照着敲的
我翻了下这本书,当时的算法处理方式都是无向图,我从新的文档里看到gds算法是有向的了。所以需要配置一下让算法支持无向。 需要分两步,先创建和配置用于算法的图,在这里指定忽略关系的方向:
CALL gds.graph.create( ‘g1’, ‘Place’, { EROAD: {type: “EROAD”, orientation: “UNDIRECTED”}}, { relationshipProperties: ‘distance’ } )
第二步使用算法:
MATCH (source:Place {id: “Amsterdam”}), (destination:Place {id: “London”}) CALL gds.shortestPath.dijkstra.stream(‘g1’,{ sourceNode: source, targetNode: destination, relationshipWeightProperty: ‘distance’ }) YIELD nodeIds, costs WITH [nodeId in nodeIds|gds.util.asNode(nodeId).id] AS nodeName,costs AS costs, size(nodeIds) AS siz UNWIND range(0,siz-1) AS n RETURN nodeName[n] AS city, costs[n] AS step
参考资料:
我用的 https://neo4j.com/docs/graph-data-science/current/algorithms/dijkstra-source-target/?_gl=18jrdvy_gaMTQ3NDg1MDY2Mi4xNTg2NjYzMTc3_ga_DL38Q8KGQC*MTY0NzgyMDc3NS4zNi4xLjE2NDc4MjA5MzkuMA…&_ga=2.143278453.1923003501.1647820776-1474850662.1586663177#algorithms-dijkstra-source-target-examples 这个实例没啥问题