4
votes

How do I perform the functions of shortestPath() and allShortestPaths() in py2neo?

In Cypher, I'd execute something like:

START beginning=node(4), end=node(452)
MATCH p = shortestPath(beginning-[*..500]-end)
RETURN p

I've tried what I thought was the equivalent (below), but this doesn't work (these relationships work in cypher, and the node_* objects are indeed the correct nodes

>>> rels = list(graph_db.match(start_node=node_4, end_node=node_452))
>>> rels
[]
1
The way you call the method you match paths of any relationship type and depth one between (4) and (452). If you want variable depth you have to pass a 'limit' parameter as well. This is still not equivalent to a shortest path algorithm, however, and I'm not sure if there is a wrapper method for that in py2neo. If there isn't one, can you use the cypher methods to execute your query instead? Most py2neo methods create cypher queries under the hood anyway, so you might as well 'wrap your own' query if there isn't a method already in the api.jjaderberg

1 Answers

12
votes

I don't want to steal jjaderberg's comment but here is how you could run your Cypher query with py2neo. As far as I know graph algorithms are not implemented.

query_string = "START beginning=node(4), end=node(452) 
                MATCH p = shortestPath(beginning-[*..500]-end) 
                RETURN p"

result = neo4j.CypherQuery(graph_db, query_string).execute()

for r in result:
    print type(r) # r is a py2neo.util.Record object
    print type(r.p) # p is a py2neo.neo4j.Path object

You can then get what you need from your path as described here: http://book.py2neo.org/en/latest/paths/