[英]Get a shortestPath from neo4j
我的任務是制定一個找到2個城鎮之間最短路程的程序。 我必須使用C#和neo4j做到這一點。 問題是我嘗試過兩次查詢時返回的neo4j查詢的類型,問題是相同的,我找不到我必須使用哪種數據結構來接收對象。
Neo4j查詢:
MATCH p=(a:City{name:"Pleven"})-[*]->(b:City{name:"Mezdra"})
RETURN p AS shortestPath,
reduce(km=0, r in relationships(p) | km+r.km) AS totalDistance
ORDER BY totalDistance ASC
LIMIT 1
C#查詢1:
CypherQuery query1 = new CypherQuery("MATCH p=(a:City{name:'"+from+"'})-[*]->(b:City{name:'"+to+"'}) RETURN p AS shortestPath, reduce(km = 0, r in relationships(p) | km + r.km) AS totalDistance ORDER BY totalDistance ASC LIMIT 1", new Dictionary<string,object>(), CypherResultMode.Set);
var paths = ((IRawGraphClient)client).ExecuteGetCypherResults<List<string>>(query1);
C#查詢2:
var query1 = client.Cypher
.Match("p=(a:City{name:{from}})-[*]->(b:City{name:{to}})")
.WithParam("from",from)
.WithParam("to",to)
.Return((p) => new PathsResult<City>{
nodes = Return.As<IEnumerable<Node<City>>>("p AS shortestPath,reduce(km = 0, r in relationships(p) | km + r.km)"),})
.Limit(1);
var result = query1.Results;
C#接收包:
{"columns"frown emoticon"shortestPath","nodes"],"data":[[{"directions"frown emoticon"->","->","->"],"start":"http://localhost:7474/db/data}
我猜您可以只使用Cypher中的“ shortestPath”內置函數。
好的,我想出一種解決方案,我找到了一種返回城鎮之間距離的方法,現在的問題是,當我編寫p = Return.As(“ shortestPath”)時,它已被翻譯為RETURN shortestPath AS p。 當前版本的代碼:
var query = client.Cypher
.Match("p=(a:City{name:{from}})-[*]->(b:City{name:{to}})")
.WithParam("from", from)
.WithParam("to", to)
.Return((p,order) => new
{
shortestPath = Return.As<City>("p"),
order= Return.As<int>("reduce(km = 0, r in relationships(p) | km + r.km)")
}).OrderBy("order ASC")
.Limit(1);
如果有任何建議請幫助
如果有人需要,這是完整的解決方案:
var query = client.Cypher
.Match("p=(a:City{name:{from}})-[*]->(b:City{name:{to}})")
.WithParam("from", from)
.WithParam("to", to)
.Return((p,order) => new
{
shortestPath = Return.As<IEnumerable<Node<City>>>("nodes(p)"),
order= Return.As<int>("reduce(km = 0, r in relationships(p) | km + r.km)")
}).OrderBy("order ASC")
.Limit(1);
var result = query.Results;
foreach (var res in result) {
foreach (var city in res.shortestPath.ToList()) {
Console.WriteLine(city.Data.name);
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.