从neo4j获取最短路径

时间:2016-01-31 23:20:11

标签: c# neo4j neo4jclient

我有一个任务是制作一个在两个城镇之间找到最短路的程序。我不得不通过使用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}

3 个答案:

答案 0 :(得分:0)

我猜你可以在Cypher中使用“shortestPath”内置函数。

http://neo4j.com/docs/stable/cypherdoc-finding-paths.html

答案 1 :(得分:0)

好的,我找到了一种解决方案,我找到了一种方法来恢复城镇之间的距离,现在的问题是,当我写下p = Return.As(&#34; shortestPath&#34;) 它已被翻译为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);

如有任何建议请帮助

答案 2 :(得分:0)

如果有人需要,那就是完整的解决方案:

 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);
                };

            }