Difference between session.run and session.readTransaction or session.writeTransaction

This is a great question, a common one, and a difference with big consequences, so let's break it down.

Session.run is the simplest, easiest form, something called an "autocommit transaction". While it's an easy way to get started, it's not recommended in production. You should instead use readTransaction and writeTransaction, for a bunch of reasons.

  1. You should signal to the driver whether you're trying to read or write. In Neo4j clustered setups, when you're using the bolt+routing:// or neo4j:// schemes, this tells the driver how to appropriately route your query to the right machine. If you want to know more about this topic, have a look at Querying Neo4j Clusters.

  2. With session.run, note you're passing a cypher query. With the other two, you're passing a function that performs the work of the transaction. This is a critical difference. One lets you run a single query. In the other, you might have a function that does a number of different sub-queries, all of which you want to wrap. up into a single overall TX that either succeeds or fails. See (Transaction Management for much more detail). In complex setups this comes up a lot that doing a particular update to your system might take 3 cypher queries, not 1. And you don't want to "partially succeed" you want either all 3 to go through, or none. To do something like that you want a tx work function.

Bottom line -- prefer the use of readTransaction and writeTransaction. Get into that habit and you'll always be in good shape.

6 Likes