Python返回neo4j的中间路径

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python返回neo4j的中间路径相关的知识,希望对你有一定的参考价值。

我试图返回neo4j的完整路径,但它只能返回python中的start节点和end节点,它返回neo4j中的完整路径。

我的python代码是:

from neo4j import GraphDatabase,basic_auth

uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("", ""))

session = driver.session()

paths = session.run('''PROFILE
                   with ['aaa''bbb''ccc''ddd''eee'] as value_list
                   match (n:Node) where n.value in value_list
                       with collect(n) as result
                       unwind result as source
                       unwind result as target
                   match paths = shortestpath((source)-[*0..2]-(target)) where source<>target
                       with paths limit 200
                       return paths''')

for record in paths:
    print(",".join("%s:%s"%(key,record[key]) for key in record.keys()))

session.close()

neo4j中的路径返回是:

"paths"                                                             
[{"value":"aaa"},{"value":"ab_relation"},{"value":"bbb"},"value":"bbb"},{"value":"bc_relation"},{"value":"ccc"}] 
[{"value":"aaa"},{"value":"ad_relation"},{"value":"ddd"},"value":"ddd"},{"value":"de_relation"},{"value":"eee"}] 

但是在python中返回:

paths:<Path start=<Node id=9650694 labels={'Node'} properties={'value': 'aaa'}> end=<Node id=23038409 labels={'Node'} properties={'value': 'ccc'}> size=2>
paths:<Path start=<Node id=9650694 labels={'Node'} properties={'value': 'aaa'}> end=<Node id=9011159 labels={'Node'} properties={'value': 'eee'}> size=2>

我怎样才能拥有完整路径而不仅仅是启动节点和结束节点?

答案

这可以返回完整的路径!

for record in paths:
    #print(record)
    relationships = record["path"].relationships
    nodes = record["path"].nodes
    path = ""
    for i in (range(len(relationships))):
        path += "{0}-[{1}]->".format(nodes[i]["value"], relationships[i]["value"])
    path += nodes[-1]["value"]
    wt.write(path+'
')

参考:explain this question here

以上是关于Python返回neo4j的中间路径的主要内容,如果未能解决你的问题,请参考以下文章

windows neo4j load csv 路径怎么写

neo4j 多个可选路径 - 密码

Neo4j:返回并行查询结果

Neo4j的。 Dijkstra算法。查找包含一组节点的路径(graphalgo)

如何往neo4j中批量插入cypher语句

从没有中间转换变量的片段中观察 ViewModel LiveData