Search code examples
neo4jpy2neo

Specify a 'visit only once condition' on a node in neo4j using py2neo


So I have a graphdb that has multiple nodes and at most a single edge between each of the nodes. For gathering certain data, I need to visit all nodes, say something like a breadth-first search. For that, I am using match method of py2neo like so:

graph.match(node, "KNOWS", end_node=None, bidirectional=True)

However, I need to visit a node only once. Meaning, my use would be intolerant about having a node twice in the data set. How do I specify such a constraint on the graphdb using py2neo?

Thanks


Solution

  • I would suggest you use the Cypher query language to query the graph. Cypher allows you to define a pattern in the graph and search for paths in the graph that match this pattern.

    Cypher can be used easily with py2neo. For example:

    query = '''
        MATCH (p1:Person})-[:KNOWS]->(friend:Person)<-[:KNOWS]-(p2:Person)
        WHERE p1.name = "Bob" AND p2.name = "Jane"
        RETURN DISTINCT friend
    '''
    results = graph.cypher.execute(query)
    

    The above query would return distinct friends in common between Bob and Jane.

    Perhaps you could add a bit more of the specifics of your data model what you are trying to accomplish to work out the appropirate Cypher query.