Python返回neo4j的中间路径

2024-04-25 00:02:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图返回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>

我怎样才能拥有完整的路径而不是只有起始节点和结束节点


Tags: 路径idnodelabels节点valuesessionas
1条回答
网友
1楼 · 发布于 2024-04-25 00:02:22

这可以返回完整路径

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+'\n')

引用:explain this question here

相关问题 更多 >