Search code examples
neo4jneo4jrestclient

neo4jrestclient check relations


I am using neo4jrestclient with python. I would like to check if two nodes have a specific relation.

For example

alice = gdb.nodes.create(name="Alice", age=30)
bob = gdb.nodes.create(name="Bob", age=25)
alice.labels.add("Person")
bob.labels.add("Person")
alice.relationships.create("Knows", bob)

How can I check if Alice has the "Knows" relation with Bob? I tried to find something from documentation with no luck.


Solution

  • There are many ways to do it. I show below two:

    1. Using the the standard neo4jrestclient's API, which might not be the most efficient:

      bob in [rel.end for rel in alice.relationships.all(types=['Knows'])]
      

      Or taking into account only outgoing relationships from alice

      bob in [rel.end for rel in alice.relationships.outgoing(types=['Knows'])]
      
    2. Through a Cypher query

      from neo4jrestclient.client import Node
      cypher = "MATCH (a)-[Knows]-(b) WHERE a.name = 'Alice' AND b.name = 'Bob' RETURN b" 
      gdb.query(query, returns=Node)[0][0] == bob