How to check if graph.commit(tx) has updated records in py2neo

52 views Asked by At

The py2neo cursor has attributes relating to if a query is writing data in cursor.summary() and cursor.stats() However this dictionary remains the same both before and after graph.commit(tx).

How can I confirm that graph.commit(tx) has written changes to the database?

My code is as follows:

from py2neo import Graph


def process_query(cursor):
    # Some logic would go here to create query 2 from the response of query 1.
    dummy_query = "CREATE (:Person {name: 'John'})"
    return dummy_query


# Create link.
graph = Graph(uri="*****", auth=("*****", "*****"))

# Start transaction.
tx = graph.begin()

# Run first query.
cursor1 = tx.run("MATCH (n) RETURN n")

# Process data from first query.
query2 = process_query(cursor1)

# Run second query.
cursor2 = tx.run(query2)

# Commit the transaction.
graph.commit(tx)

# Need logic here on success of final operation.

I can get the write information from cursor2.stats() but how should I monitor graph.commit(tx) if the transaction is unsuccesful? Does it throw an exception or return a specific response?

I have looked at the docs but I cannot get a clear idea on how this function works exactly.

1

There are 1 answers

3
jose_bacoy On

This is the documentation from py2neo about error handling:

https://py2neo.org/2021.1/errors.html 

and from neo4j about the status code

 https://neo4j.com/docs/status-codes/current/ 

On you sample code, I would add a try;catch exceptions like below:

from py2neo import Graph,Neo4jError,ClientError,TransientError,DatabaseError 

def process_query(cursor):
    # Some logic would go here to create query 2 from the response of query 1.
    dummy_query = "CREATE (:Person {name: 'John'})"
    return dummy_query


# Create link.
graph = Graph(uri="bolt://localhost:7687/", auth=("neo4j", "admin"))
try:
    # Start transaction.
    tx = graph.begin()

    # Run first query.
    cursor1 = tx.run("MATCH (n) RETURN n")

    # Process data from first query.
    query2 = process_query(cursor1)

    # Run second query.
    cursor2 = tx.run(query2)

    # Commit the transaction.
    graph.commit(tx)

# based on https://py2neo.org/2021.1/errors.html and https://neo4j.com/docs/status-codes/current/
except Neo4jError as e:
    print("Neo4j error: ", e)
except ClientError as e:
    print("Client error: ", e)
except TransientError as e:
    print("Transient error: ", e) 
except DatabaseError as e:
    print("Database error: ", e) 
except Excepton as e:
    print("Generic error: ", e)
finally:
    print('Done')
# Need logic here on success of final operation.