Search code examples
pythonneo4jpy2neo

Using py2neo to get nodes with second order connections?


How can py2neo RelationshipMatcher or similar be used to return all nodes with a second order connection to an original node?

I can use the following Cypher query:

MATCH (u)-[:has]-()-[:validates]-(result)
WHERE u.UserName = "Dave" 
RETURN result

Which with the below graph would give me routes A, B and C


Graph image

However, using db.evaluate(query (as below) with the same query only returns the first matching node (i.e. Route A)

from py2neo import Graph, Node, Relationship, NodeMatcher, RelationshipMatcher

def get_routes(username):
    query = "MATCH (u)-[:has]-()-[:validates]-(result) WHERE u.UserName = '"'{}'"' RETURN result".format(username)
    result = db.evaluate(query)

db = Graph("bolt://X.X.X.X:7687", username = "neo4j", password = "password")
get_routes("Dave")

Something like below would return the first order nodes connected to my user (i.e. Condition1, Condition2).

How can I amend this code to deliver the matching 2nd order nodes?

u = db.nodes.match("User", UserName=username).first()
matcher = RelationshipMatcher(db)
nodes = matcher.match((u, None), "has")

Solution

  • Found answer here

    result = db.run(query).data() instead of result = db.evaluate(query)

    This returns a dictionary of matching nodes