问题
MATCH (u:User {name:{user}}), (target:Group {name: {group}}), p=shortestPath((u)-[*]->(target)) RETURN p
When I run the above query in the Neo4j web UI, a fell graph of the resulting paths is displayed.
However, when I run the same query with the neo4j-python
driver, only a Path
objects with limited information are returned
<Path start=479557 end=404582 size=1>
How can I use Cypher and python to get complete path details, including all nodes and the relationships that connect them?
回答1:
Depends on how you want to return data, but you can try something like this
MATCH (u:User {name:{user}}), (target:Group {name: {group}}),
p=shortestPath((u)-[*]->(target)) RETURN nodes(p),relationships(p)
回答2:
Thanks for the help everyone! For reference, here's my complete example that converts paths to human-readable strings for console or email output.
def find_paths_from_standard_user_to_domain_admins(standard_user, domain_admins_group):
"""Returns a list of paths that a standard user could take to get domain admin credentials"""
results = []
query = "MATCH (u:User {name:{user}}), (target:Group {name: {group}})," \
"p=allShortestPaths((u)-[*]->(target)) RETURN p"
with driver.session() as session:
with session.begin_transaction() as tx:
for record in tx.run(query, user=standard_user, group=domain_admins_group):
relationships = record["p"].relationships
nodes = record["p"].nodes
path = ""
for i in (range(len(relationships))):
path += "{0}-[{1}]->".format(nodes[i]["name"], relationships[i].type)
path += nodes[-1]["name"]
results.append(path)
return results
This is a query for a graph generated by the Bloodhound project, which builds graphs of Active Directory structures. It's extremely useful for domain admins, system architects, network defenders, and pentesters.
来源:https://stackoverflow.com/questions/42456004/how-can-i-get-all-the-hops-in-a-path-of-unknown-length-with-neo4j-python