Search code examples
python-3.xneo4jpy2neo

Get number of records from a match query with py2neo


Is there an easy way to get the number of records return from a match query using py2neo?

records = g.db.run("MATCH (n:Project) where n.id={id} and ({user} in n.users) return n", id=project_id, user=user_name)
num_records_returned = # how do I do this?

Solution

  • The result of a query returns a python generator/iterator, as they are not collections after all you cannot know the size/length of it without iterating it.

    So if only the count of nodes interest you, you can adapt your query to what Tomaz said.

    Otherwise you can use a counter :

    result = session.run("MATCH (n:Product) RETURN n")
    n = 0
    
    for record in result:
        print(record["n"]["id"])
        n = n+1
    
    print("total number of records : " + str(n))
    

    Another solution is to transform the iterator to a list, then you will have the len function available :

    result = session.run("MATCH (n:Product) RETURN n")
    
    records = list(result)
    print(len(records))
    for record in records:
        print(record["n"]["id"])