Search code examples
pythonneo4jcypherpy2neo

Is there a way to pass in a parameter for matching on labels in neo4j


I'm using py2neo and trying to pass a parameter(a label) between methods for matching on but I can't figure out the syntax. In the browser I would use this:

MATCH n
where n:`Name`
RETURN n 

This is my python code, where I'm trying to do similar match:

def similar_noder(a):

try:
    graph_db = neo4j.GraphDatabaseService(url)
    query = neo4j.CypherQuery(graph_db, 
    """CYPHER 2.0
        MATCH n      
        where (n:`{z}`)
        RETURN id(n)
        """) 
    result = query.execute(z=a)
    for r in result:           
        label = ", ".join(str(e) for e in (r.values[0]))#label
        print label            
except Exception as e:
    print e

In this case, "a" is the label "Name" that I'm trying to pass and match on. I'm trying to find all nodes that have the label name.


Solution

  • Something you can do, when you don't have many nodes to search is to use this:

    MATCH (n)
    WHERE {z} IN labels(n)
    RETURN n
    

    But it won't be fast, as Cypher can't optimize it if it doesn't know the label at compile time.