How To Create a Neo4j Session Object

by John Singer November 10, 2020 at 8:32 am

In this post I will explore how to create a session object using the Neo4j Python driver. In order to run queries and manage transactions you will need to create and use a session object. The session object also allows you to further configure how the connection to Neo4j behaves. You might want to review how to create a connection to Neo4j using the Python driver here.

Take a look at the environment used for this tutorial. You can recreate this environment and follow along or use whatever python development environment you like.

Session Construction

This section describes session construction and configuration. You create a session object to manage transactions and run queries. While the driver object is typically created for the life of the application, the session object should be created and closed with the scope of the transactions you want to process. For this tutorial we will use the simple auto transaction. More complex transaction scenarios will be considered in another post.

This codes shows the default session creation.

from neo4j import GraphDatabase

# create the uri for the connection
uri = "neo4j://localhost:7687"
# create a driver object
driver = GraphDatabase.driver(uri, auth=("neo4j", "xxxxx"))
# create a session that connects to the default database
session = driver.session()

When the session object is created it will acquire a connection from the connection pool that is managed by the driver object. You don’t have to do any work regarding the connections.

You can specify which database the session should connect to using the database keyword parameter. The example below connects to the default database specifically. Notice the additional import.

from neo4j import DEFAULT_DATABASE
session = driver.session(database=DEFAULT_DATABASE)

You can specify an application database name using the database keyword parameter. This is needed if your Neo4j server has multiple application databases defined.

session = driver.session(database="myappdb")

Finally, this is how you connect to the Neo4j system database. The system database is needed to perform certain operations on the server itself such as create users and roles.

session = driver.session(database="system")

Session Configuration

Besides setting which database to connect to, the session object allows two more configuration parameters. The first is fetch_size which allows you to tell Neo4j how many result records to return for each interaction with the server. Here is an example of how to set the fetch_size on a Neo4j session:

session = driver.session(fetch_size=1000)

You can also set the default access mode which only applies in clustered environments. This allows you to route queries to the read or write servers in your cluster depending on the type of queries the application is running. This is useful to keep read only queries running on the read server and update queries on the write server. The example below shows how to set the default access mode to “write”. Note the additional import.

from neo4j import WRITE_ACCESS

session = driver.session(default_access_mode=WRITE_ACCESS)

Of course, all three keywords (database, default_access_mode, fetch_size) can be used when creating the session object.

Note the examples above only show the code for creating the session object and assume you’ve already created the driver object.

Run A Query

Now you have a driver object, a session object (with a connection from the connection pool) and you are ready to run some queries. This example shows how to run a simple query in an automatic transaction. This is the simplest form of transaction management as everything is done for you. A transaction is created, the query is submitted to the server and upon completion the transaction is committed – all without any code on your part. The example below shows how to run a simple query in an auto-commit transaction:

result = session.run("MATCH (n) RETURN n limit 1")

The example above assumes you’ve created the driver and session objects. It runs a simple match statement and returns a result object for your application to process. It’s interesting to note that the server does not actually return the results to the application until you access the result object (“consume the results”). Processing results will be covered in another post.

Close A Session

The session.close() method will “close” the session. This releases any connections acquired and will roll back any open transactions. The session object itself however remains ready to be used in another session.run() statement to run another query.

Python With Block

You can use the Python with block to create a context for running and processing a query. The example below shows how to create a session object in a with block context and then run a query.

with driver.session(database=DEFAULT_DATABASE) as session:
    result = session.run("MATCH (n) RETURN n limit 1")

Summary

This post has described how to create and configure a session object using the Neo4j Python Driver. The session object is used to manage transactions and run queries. We also looked at how to run a simple query in an auto-commit transaction. Here is the entire script you can save in a file and run in Idle or your IDE of choice.

from neo4j import GraphDatabase
from neo4j import DEFAULT_DATABASE
from neo4j import WRITE_ACCESS

print("tutorialsession1.py - starting")
# create the uri for the connection
uri = "neo4j://localhost:7687"

# create a driver object
driver = GraphDatabase.driver(uri, auth=("neo4j", "nachodog"))
print("the driver type is:{}".format(type(driver)))
print("tutorialconnect.py - driver created")

# get info about the driver
print("Host: {}".format(driver.default_host))
print("Port: {}".format(driver.default_port))
print("Encrypted: {}".format(driver.encrypted))

# create a session that connects to the default database
session = driver.session(database=DEFAULT_DATABASE)
session.close()

# create a session with the system database
session = driver.session(database="system")
session.close()

# create a session with an application database
session = driver.session(database="my_app_db")
session.close()

# create a session that connects to the default database with a fetch size
session = driver.session(fetch_size=1000)
session.close()

# create a session that connects to the default database with an access mode
session = driver.session(default_access_mode=WRITE_ACCESS)
session.close()


# run a simple query in an automatic transaction
session = driver.session(database=DEFAULT_DATABASE)
result = session.run("MATCH (n) RETURN n limit 1")
session.close()
print("tutorialsession1.py - run query")

# run a query in a with block context
with driver.session(database=DEFAULT_DATABASE) as session:
    result = session.run("MATCH (n) RETURN n limit 1")

# close the session
session.close()
print("tutorialsession1.py - session closed")
# close the driver
driver.close()
print("tutorialsession1.py - driver closed")

That’s it for session creation and configuration. Check out the entire series of posts here.

Add Comment