Search code examples
neo4jpy2neo

How to combine cypher queries into a transaction in Py2neo v3


In py2neo v2.0, it was possible to use a transaction to execute Cypher statements:

tx=graph.cypher.begin()
tx.append("MERGE (n:Process {proc_nm : {proc_nm}}) ON CREATE SET n.count = 1 ON MATCH SET n.count = n.count +1", {proc_nm : 'wibble'})
tx.commit

When processing complex files this allows very fast updates to be made to the Neo4J database.

In py2neo v3.0 the syntax has changed to:

graph.run(("MERGE (n:Process {proc_nm : {proc_nm}}) ON CREATE SET n.count = 1 ON MATCH SET n.count = n.count +1", {proc_nm : 'wibble'}))

This means that I can run the cypher statements singly but the performance takes a massive hit. I can write CREATE/MERGE for the Nodes and Relationships however I was hoping to not have to re-write a bunch of routines that I'm already using. What am I missing?


Solution

  • In py2neo v3, you can still use a Transaction, but the API has changed a bit.

    In your sample code, you must now:

    • Use graph.begin instead of graph.cypher.begin.
    • Use tx.run instead of tx.append.

    This pattern should work in v3:

    tx=graph.begin()
    tx.run(" ... Cypher statement 1 ... ", { ... })
    tx.run(" ... Cypher statement 2 ... ", { ... })
    tx.run(" ... Cypher statement 3 ... ", { ... })
    tx.commit()