Search code examples
pythonneo4jdriver

How to get a list using neo4j python driver?


When my query asks for a single response everything is OK, but when I try to get a whole list, it gives my this error:

Record name=u'Tom Hanks' relations=12> /home/roldanx/.local/lib/python2.7/site-packages/neo4j/v1/api.py:772: UserWarning: Expected a result with a single record, but this result contains 13

Which only gives me the first row of the list (Tom Hanks, 12). Is there any way I can get the whole list? This is my code:

from neo4j.v1 import GraphDatabase

    driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

    session = driver.session()

    def degree():
        return session.run("""
            MATCH(a:Person{name:"Tom Hanks"})--(b)
            return a.name AS name, count(distinct b) AS relations
            UNION 
            MATCH (a:Person{name:"Tom Hanks"})--(b)--(c)
            return b.title AS name, (count(distinct c)+1) AS relations
            """)

    deg = degree().single()
    print(deg)
    driver.close()

Solution

  • When you run a cypher query, a BoltStatementResult is returned. It provides a handle to the result of the query, but also some metadata. So you can't directly typecast it into a list. But it is iterable, so you can simply loop over the result to get all the records:

    result = degree()
    entire_result = [] # Will contain all the items
    for record in result:
        entire_result.append(record)