Using Neo4j from Python

Goals
This guide provides an overview of how to connecting to Neo4j from Python.
Prerequisites
You should be familiar with graph database concepts and the property graph model. You should have created an Neo4j AuraDB cloud instance, or installed Neo4j locally

Intermediate

Neo4j and Python

python logo

Neo4j provides drivers which allow you to make a connection to the database and develop applications which create, read, update, and delete information from the graph.

Learn with GraphAcademy

badge

Building Neo4j Applications with Python

In this free course, we walk through the steps to integrate Neo4j into your Python projects. You will learn about the Neo4j Python Driver, how sessions and transactions work and how to query Neo4j from an existing application.

Neo4j Python Driver

The Neo4j Python driver is officially supported by Neo4j and connects to the database using the binary protocol. It aims to be minimal, while being idiomatic to Python.

Support for Python 2 was removed in the 2.0 release of the driver.
pip install neo4j
from neo4j import GraphDatabase

class HelloWorldExample:

    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):
        self.driver.close()

    def print_greeting(self, message):
        with self.driver.session() as session:
            greeting = session.write_transaction(self._create_and_return_greeting, message)
            print(greeting)

    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run("CREATE (a:Greeting) "
                        "SET a.message = $message "
                        "RETURN a.message + ', from node ' + id(a)", message=message)
        return result.single()[0]


if __name__ == "__main__":
    greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "password")
    greeter.print_greeting("hello, world")
    greeter.close()

Driver Configuration

From Neo4j version 4.0 and onwards, the default encryption setting is off by default and Neo4j will no longer generate self-signed certificates. This applies to default installations, installations through Neo4j Desktop and Docker images. You can verify the encryption level of your server by checking the dbms.connector.bolt.enabled key in neo4j.conf.

Table 1. Table Scheme Usage
Certificate Type Neo4j Causal Cluster Neo4j Standalone Server Direct Connection to Cluster Member

Unencrypted

neo4j

neo4j

bolt

Encrypted with Full Certificate

neo4j+s

neo4j+s

bolt+s

Encrypted with Self-Signed Certificate

neo4j+ssc

neo4j+ssc

bolt+ssc

Neo4j AuraDB

neo4j+s

N/A

N/A

Please review your SSL Framework settings when going into production. If necessary, you can also generate certificates for Neo4j with Letsencrypt

Name

Version

Authors

neo4j-driver

4.4.4

The Neo4j Team

Package

Neo4j Online Community

Docs

API

Source

The Example Project

The Neo4j example project is a small, one page webapp for the movies database built into the Neo4j tutorial. The front-end page is the same for all drivers: movie search, movie details, and a graph visualization of actors and movies. Each backend implementation shows you how to connect to Neo4j from each of the different languages and drivers.

You can learn more about our small, consistent example project across many different language drivers here. You will find the implementations for all drivers as individual GitHub repositories, which you can clone and deploy directly.

Neo4j Community Drivers

Members of the each programming language community have invested a lot of time and love to develop each one of the community drivers for Neo4j, so if you use any one of them, please provide feedback to the authors.

The community drivers have been graciously contributed by the Neo4j community. Many of them are fully featured and well-maintained, but some may not be. Neo4j does not take any responsibility for their usability.

For anyone working with Python, the Neo4j community have contributed a range of driver options. These range from lightweight to comprehensive driver packages as well as libraries designed for use with web frameworks such as Django.

While Python 3 is preferred, some drivers still support Python 2, please check with the individual project if you need it.

While we do not provide a specific web framework recommendation, both the lightweight Flask and the more comprehensive Django frameworks are known to work well.

Py2neo

py2neo.200x200

Py2neo is a client library and comprehensive toolkit for working with Neo4j from within Python applications and from the command line. It has been carefully designed to be easy and intuitive to use.

Author

Nigel Small

Package

https://pypi.python.org/pypi/py2neo

Source

https://github.com/technige/py2neo

Example

https://github.com/neo4j-examples/movies-python-py2neo

Docs

http://py2neo.org/

Python

2.7 / 3.4+

Protocols

Bolt, Http

Installation
pip install py2neo
Example
from py2neo import Graph
graph = Graph()

tx = graph.begin()
for name in ["Alice", "Bob", "Carol"]:
    tx.append("CREATE (person:Person name: $name) RETURN person", name=name)
alice, bob, carol = [result.one for result in tx.commit()]

Neomodel

neomodel.200x80

An Object Graph Mapper built on top of the Neo4j python driver. Familiar Django style node definitions with a powerful query API, thread safe and full transaction support. A Django plugin django_neomodel is also available.

Author

Athanasios Anastasiou and Robin Edwards

Package

https://pypi.python.org/pypi/neomodel

Source

http://github.com/neo4j-contrib/neomodel

Docs

https://neomodel.readthedocs.io/en/latest/

Python

2.7 / 3.3+

Protocols

Bolt

Example App

https://github.com/neo4j-examples/neo4j-movies-python-neomodel

Installation
pip install neomodel
Example
from neomodel import StructuredNode, StringProperty, RelationshipTo, RelationshipFrom, config

config.DATABASE_URL = 'bolt://neo4j:test@localhost:7687'

class Book(StructuredNode):
    title = StringProperty(unique_index=True)
    author = RelationshipTo('Author', 'AUTHOR')

class Author(StructuredNode):
    name = StringProperty(unique_index=True)
    books = RelationshipFrom('Book', 'AUTHOR')

harry_potter = Book(title='Harry potter and the..').save()
rowling =  Author(name='J. K. Rowling').save()
harry_potter.author.connect(rowling)