Chapter 1. Get started

This section gives an overview of the official Neo4j drivers and how to connect to a Neo4j database with a "Hello World" example.

1.1. About the official drivers

Neo4j provides official drivers for a number of popular programming languages. These drivers are supported by Neo4j.

Community drivers also exist for many languages, but vary greatly in terms of feature sets, maturity, and support. To find more about community drivers, visit https://neo4j.com/developer/language-guides/.

The following languages and frameworks are officially supported by Neo4j:

Table 1.1. Supported languages and frameworks for the 4.x driver series
Language/framework Versions supported

.NET

.NET Standard 2.0

Java

Java 8+ (latest patch releases).

JavaScript

All LTS versions of Node.JS, specifically the 4.x and 6.x series runtimes (https://github.com/nodejs/LTS).

Python

CPython 3.5 and above.

The 4.1 Go driver is a work in progress. There is currently no release date available.

The latest Go Driver is 1.8. For information on the 1.8 Go Driver, see https://neo4j.com/docs/driver-manual/1.7.

The driver API is intended to be topologically agnostic. This means that the underlying database topology — single instance, Causal Cluster, etc. — can be altered without requiring a corresponding alteration to application code. In the general case, only the connection URI needs to be modified when changes are made to the topology.

The official drivers do not support HTTP communication. If you need an HTTP driver, choose one of the community drivers. See also the HTTP API documentation.

1.2. Driver versions and installation

Starting with Neo4j 4.0, the versioning scheme for the database, driver and protocol have all been aligned. This simplifies general compatibility concerns.

Cross-version compatibility is still available, and minimum support for current and previous versions between both server and driver is guaranteed. More specifically, this means that Neo4j 4.0 is guaranteed to be compatible with both 4.0 Drivers and 1.7 Drivers, and the 4.0 Drivers are guaranteed to be compatible with both Neo4j 4.0 and Neo4j 3.5. In cases where at least one peer is below version 4.0, communication will occur in fallback mode, limiting functionality to that available in the lowest-versioned component.

Drivers 1.7 do not support multiple databases and Neo4j Fabric, features introduced in Neo4j 4.0. To be able to run multiple databases online concurrently and to do distributed queries over them, you must upgrade Drivers from 1.7 to 4.0. For information, see 4.0 Migration Guide → Chapter 6. Upgrade Neo4j drivers.

Wherever possible, it is recommended to use the latest stable driver release available. This will provide the greatest degree of stability and will ensure that the full set of server functionality is available. The drivers, when used with Neo4j Enterprise Edition, come with full cluster routing support. The drivers make no explicit distinction between Enterprise Edition and Community Edition however, and simply operate with the functionality made available by Neo4j itself.

To install a driver or to find out more about which driver versions are available, use the relevant language distribution system, described below.

Example 1.1. Acquire the driver

The .NET driver is distributed via the NuGet Gallery. To find the latest version of the driver, visit https://www.nuget.org/packages/Neo4j.Driver/.

Dependencies

  • .NETStandard (^2.0)
  • System.Net.NameResolution (^4.3.0)
  • System.Net.Security (^4.3.2)
  • System.Net.Sockets (^4.3.0)
  • System.Runtime.InteropServices.RuntimeInformation (^4.3.0)
  • System.Runtime.Serialization.Primitives (^4.3.0)
  • System.Threading.Thread (^4.3.0)
  • System.ValueTuple (^4.5.0)

The .NET Reactive API is under package Neo4j.Driver.Reactive. It is built upon System.Reactive. There is no extra dependency required use .NET reactive API.

Example 1.2. Installation via Install-package

To install the latest version of the driver using NuGet in Visual Studio:

PM> Install-Package Neo4j.Driver

It is also an option to install a certain version of the driver.

PM> Install-Package Neo4j.Driver -Version $DOTNET_DRIVER_VERSION

In the following example we are installing driver version 4.1.0.

PM> Install-Package Neo4j.Driver -Version 4.1.0

The release notes for this driver are available here.

To use the Java driver, it is recommended employing a dependency manager, such as Maven or Gradle. To find the latest version of the driver, visit the Maven Central Repository.

Dependencies

  • org.reactivestreams:reactive-streams
  • org.apache.logging.log4j:log4j (optional)

The driver is dependent on the Reactive Streams API, thus maintaining JDK 8 compatibility. To make optimal use of the reactive APIs, we suggest an additional framework like Project Reactor or RxJava2. Both implement the Reactive Streams API and provide an exhaustive set of operators.

Example 1.3. Installation via Maven

When using Maven, add the following block to the pom.xml file. The driver version can either be declared as a property (as in the first example) or as an explicit version number (as in the second).

<dependencies>
    <dependency>
        <groupId>org.neo4j.driver</groupId>
        <artifactId>neo4j-java-driver</artifactId>
        <version>$JAVA_DRIVER_VERSION</version>
    </dependency>
</dependencies>

In the following example, driver version 4.1.1 is added.

<dependencies>
    <dependency>
        <groupId>org.neo4j.driver</groupId>
        <artifactId>neo4j-java-driver</artifactId>
        <version>4.1.1</version>
    </dependency>
</dependencies>
Example 1.4. Installation via Gradle

For Gradle, a compile line will be required. Again, this can use a property or an explicit version number.

compile 'org.neo4j.driver:neo4j-java-driver:$JAVA_DRIVER_VERSION'

In the following example, a driver version 4.1.1 is added.

compile 'org.neo4j.driver:neo4j-java-driver:4.1.1'

The release notes for this driver are available here.

To use the JavaScript driver, it is recommended employing npm. To find the latest version of the driver, use:

npm show neo4j-driver@* version

Dependencies

  • Babel/Runtime (^7.5.5)
  • RxJS (^6.5.2)
  • text-encoding-utf-8 (^1.0.2)
  • URI-js (^4.2.2)

The JavaScript Reactive API is built and exposed via RxJs. A dependency of RxJs is automatically installed with the driver.

Example 1.5. Installation via npm

To install the latest version of the driver:

npm install neo4j-driver

It is also an option to install a certain version of the driver.

npm install neo4j-driver@$JAVASCRIPT-DRIVER-VERSION

In the following example, driver version 4.1.1 is installed.

npm install neo4j-driver@4.1.1

The release notes for this driver are available here.

To find the latest stable version of the Python Driver, visit https://pypi.org/project/neo4j/

To find a list of all available releases, visit https://pypi.org/simple/neo4j/

To install the latest stable version of the Python Driver:

pip install neo4j

It is also an option to install a certain version of the driver.

Example 1.6. Installation with Python

The following is the syntax for installing a certain version of the Python Driver:

pip install neo4j==$PYTHON_DRIVER_VERSION

In the following example we are installing Python Driver version 4.1.0.

pip install neo4j==4.1.0
Example 1.7. Installation with Python, get Python Driver prerelease

In the following example we get the latest prerelease version:

pip install neo4 --pre

The release notes for the Python Driver are available here

1.3. A "Hello World" example

The example below shows the minimal configuration necessary to interact with Neo4j through a driver.

Example 1.8. Hello World
public class HelloWorldExample : IDisposable
{
    private readonly IDriver _driver;

    public HelloWorldExample(string uri, string user, string password)
    {
        _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
    }

    public void PrintGreeting(string message)
    {
        using (var session = _driver.Session())
        {
            var greeting = session.WriteTransaction(tx =>
            {
                var result = tx.Run("CREATE (a:Greeting) " +
                                    "SET a.message = $message " +
                                    "RETURN a.message + ', from node ' + id(a)",
                    new {message});
                return result.Single()[0].As<string>();
            });
            Console.WriteLine(greeting);
        }
    }

    public void Dispose()
    {
        _driver?.Dispose();
    }

    public static void Main()
    {
        using (var greeter = new HelloWorldExample("bolt://localhost:7687", "neo4j", "password"))
        {
            greeter.PrintGreeting("hello, world");
        }
    }
}
public class HelloWorldExample implements AutoCloseable
{
    private final Driver driver;

    public HelloWorldExample( String uri, String user, String password )
    {
        driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
    }

    @Override
    public void close() throws Exception
    {
        driver.close();
    }

    public void printGreeting( final String message )
    {
        try ( Session session = driver.session() )
        {
            String greeting = session.writeTransaction( new TransactionWork<String>()
            {
                @Override
                public String execute( Transaction tx )
                {
                    Result result = tx.run( "CREATE (a:Greeting) " +
                                                     "SET a.message = $message " +
                                                     "RETURN a.message + ', from node ' + id(a)",
                            parameters( "message", message ) );
                    return result.single().get( 0 ).asString();
                }
            } );
            System.out.println( greeting );
        }
    }

    public static void main( String... args ) throws Exception
    {
        try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
        {
            greeter.printGreeting( "hello, world" );
        }
    }
}
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import org.neo4j.driver.Result;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.TransactionWork;

import static org.neo4j.driver.Values.parameters;
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()

try {
  const result = await session.writeTransaction(tx =>
    tx.run(
      'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
      { message: 'hello, world' }
    )
  )

  const singleRecord = result.records[0]
  const greeting = singleRecord.get(0)

  console.log(greeting)
} finally {
  await session.close()
}

// on application exit:
await driver.close()
class App:

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

    def close(self):
        # Don't forget to close the driver connection when you are finished with it
        self.driver.close()

    def create_friendship(self, person1_name, person2_name):
        with self.driver.session() as session:
            # Write transactions allow the driver to handle retries and transient errors
            result = session.write_transaction(
                self._create_and_return_friendship, person1_name, person2_name)
            for row in result:
                print("Created friendship between: {p1}, {p2}".format(p1=row['p1'], p2=row['p2']))

    @staticmethod
    def _create_and_return_friendship(tx, person1_name, person2_name):
        # To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/
        # The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/
        query = (
            "CREATE (p1:Person { name: $person1_name }) "
            "CREATE (p2:Person { name: $person2_name }) "
            "CREATE (p1)-[:KNOWS]->(p2) "
            "RETURN p1, p2"
        )
        result = tx.run(query, person1_name=person1_name, person2_name=person2_name)
        try:
            return [{"p1": row["p1"]["name"], "p2": row["p2"]["name"]}
                    for row in result]
        # Capture any errors along with the query and data for traceability
        except ServiceUnavailable as exception:
            logging.error("{query} raised an error: \n {exception}".format(
                query=query, exception=exception))
            raise

    def find_person(self, person_name):
        with self.driver.session() as session:
            result = session.read_transaction(self._find_and_return_person, person_name)
            for row in result:
                print("Found person: {row}".format(row=row))

    @staticmethod
    def _find_and_return_person(tx, person_name):
        query = (
            "MATCH (p:Person) "
            "WHERE p.name = $person_name "
            "RETURN p.name AS name"
        )
        result = tx.run(query, person_name=person_name)
        return [row["name"] for row in result]


if __name__ == "__main__":
    # Aura queries use an encrypted connection using the "neo4j+s" URI scheme
    bolt_url = "%%BOLT_URL_PLACEHOLDER%%"
    user = "<Username for Neo4j Aura database>"
    password = "<Password for Neo4j Aura database>"
    app = App(bolt_url, user, password)
    app.create_friendship("Alice", "David")
    app.find_person("Alice")
    app.close()
from neo4j import GraphDatabase
import logging
from neo4j.exceptions import ServiceUnavailable

1.4. Driver API docs

For a comprehensive listing of all driver functionality, refer to the API documentation for the specific driver language.