Client applications

This section describes how to manage database connections within an application.

The Driver Object

Neo4j client applications require a Driver Object which, from a data access perspective, forms the backbone of the application. It is through this object that all Neo4j interaction is carried out, and it should therefore be made available to all parts of the application that require data access.

In languages where thread safety is an issue, the Driver Object can be considered thread-safe.

A note on lifecycle

Applications will typically construct a Driver Object on startup and destroy it on exit.

Destroying a Driver Object will immediately shut down any connections previously opened via that Driver Object, by closing the associated connection pool.

This will have the consequence of rolling back any open transactions, and closing any unconsumed results.

To construct a driver instance, a connection URI and authentication information must be supplied.

Additional configuration details can be supplied if required. The configuration details are immutable for the lifetime of the Driver Object. Therefore, if multiple configurations are required (such as when working with multiple database users) then multiple Driver Objects must be used.

Example 1. The driver lifecycle
        public class DriverLifecycleExample : IDisposable
        {
            public DriverLifecycleExample(string uri, string user, string password)
            {
                Driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
            }

            public IDriver Driver { get; }

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

    public class HelloWorldExampleTest : BaseExample
    {
        public HelloWorldExampleTest(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        [RequireServerFact]
        public void TestHelloWorldExample()
        {
            // Given
            using var example = new HelloWorldExample(Uri, User, Password);
            // When & Then
            example.PrintGreeting("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.ExecuteWrite(
                    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 ReadWriteTransactionExample : BaseExample
    {
        public ReadWriteTransactionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        [RequireServerFact]
        public void TestReadWriteTransactionExample()
        {
            // When & Then
            AddPerson("Alice").Should().BeGreaterOrEqualTo(0L);
        }

        public long AddPerson(string name)
        {
            using var session = Driver.Session();
            session.ExecuteWrite(tx => CreatePersonNode(tx, name));
            return session.ExecuteRead(tx => MatchPersonNode(tx, name));
        }

        private static IResultSummary CreatePersonNode(IQueryRunner tx, string name)
        {
            return tx.Run("CREATE (a:Person {name: $name})", new { name }).Consume();
        }

        private static long MatchPersonNode(IQueryRunner tx, string name)
        {
            var result = tx.Run("MATCH (a:Person {name: $name}) RETURN id(a)", new { name });
            return result.Single()[0].As<long>();
        }

    }

    public class ResultConsumeExample : BaseExample
    {
        public ResultConsumeExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public List<string> GetPeople()
        {
            using var session = Driver.Session();
            return session.ExecuteRead(
                tx =>
                {
                    var result = tx.Run("MATCH (a:Person) RETURN a.name ORDER BY a.name");
                    return result.Select(record => record[0].As<string>()).ToList();
                });
        }

        [RequireServerFact]
        public void TestResultConsumeExample()
        {
            // Given
            Write("CREATE (a:Person {name: 'Alice'})");
            Write("CREATE (a:Person {name: 'Bob'})");
            // When & Then
            GetPeople().Should().Contain(new[] { "Alice", "Bob" });
        }
    }

    public class ResultRetainExample : BaseExample
    {
        public ResultRetainExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public int AddEmployees(string companyName)
        {
            using var session = Driver.Session();
            var persons = session.ExecuteRead(tx => tx.Run("MATCH (a:Person) RETURN a.name AS name").ToList());
            return persons.Sum(
                person => session.ExecuteWrite(
                    tx =>
                    {
                        var result = tx.Run(
                            "MATCH (emp:Person {name: $person_name}) " +
                            "MERGE (com:Company {name: $company_name}) " +
                            "MERGE (emp)-[:WORKS_FOR]->(com)",
                            new { person_name = person["name"].As<string>(), company_name = companyName });

                        result.Consume();
                        return 1;
                    }));
        }

        [RequireServerFact]
        public void TestResultConsumeExample()
        {
            // Given
            Write("CREATE (a:Person {name: 'Alice'})");
            Write("CREATE (a:Person {name: 'Bob'})");
            // When & Then
            AddEmployees("Example").Should().Be(2);
            Read("MATCH (emp:Person)-[WORKS_FOR]->(com:Company) WHERE com.name = 'Example' RETURN count(emp)")
                .Single()[0]
                .As<int>()
                .Should()
                .Be(2);
        }
    }

    public class ServiceUnavailableExample : BaseExample
    {
        private readonly IDriver _baseDriver;

        public ServiceUnavailableExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
            _baseDriver = Driver;
            Driver = GraphDatabase.Driver(
                "bolt://localhost:8080",
                AuthTokens.Basic(User, Password),
                o => o.WithMaxTransactionRetryTime(TimeSpan.FromSeconds(3)));
        }

        protected override void Dispose(bool isDisposing)
        {
            if (!isDisposing)
            {
                return;
            }

            Driver = _baseDriver;
            base.Dispose(true);
        }

        public bool AddItem()
        {
            try
            {
                using var session = Driver.Session();
                return session.ExecuteWrite(
                    tx =>
                    {
                        tx.Run("CREATE (a:Item)").Consume();
                        return true;
                    });
            }
            catch (ServiceUnavailableException)
            {
                return false;
            }
        }

        [RequireServerFact]
        public void TestServiceUnavailableExample()
        {
            AddItem().Should().BeFalse();
        }
    }

    [SuppressMessage("ReSharper", "xUnit1013")]
    public class SessionExample : BaseExample
    {
        public SessionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public void AddPerson(string name)
        {
            using var session = Driver.Session();
            session.Run("CREATE (a:Person {name: $name})", new { name });
        }

        [RequireServerFact]
        public void TestSessionExample()
        {
            // Given & When
            AddPerson("Alice");
            // Then
            CountPerson("Alice").Should().Be(1);
        }
    }

    [SuppressMessage("ReSharper", "xUnit1013")]
    public class TransactionFunctionExample : BaseExample
    {
        public TransactionFunctionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public void AddPerson(string name)
        {
            using var session = Driver.Session();
            session.ExecuteWrite(tx => tx.Run("CREATE (a:Person {name: $name})", new { name }).Consume());
        }

        [RequireServerFact]
        public void TestTransactionFunctionExample()
        {
            // Given & When
            AddPerson("Alice");
            // Then
            CountPerson("Alice").Should().Be(1);
        }
    }

    [SuppressMessage("ReSharper", "xUnit1013")]
    public class TransactionTimeoutConfigExample : BaseExample
    {
        public TransactionTimeoutConfigExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public void AddPerson(string name)
        {
            using var session = Driver.Session();
            session.ExecuteWrite(
                tx => tx.Run("CREATE (a:Person {name: $name})", new { name }).Consume(),
                txConfig => txConfig.WithTimeout(TimeSpan.FromSeconds(5)));
        }

        [RequireServerFact]
        public void TestTransactionTimeoutConfigExample()
        {
            // Given & When
            AddPerson("Alice");
            // Then
            CountPerson("Alice").Should().Be(1);
        }
    }

    [SuppressMessage("ReSharper", "xUnit1013")]
    public class TransactionMetadataConfigExample : BaseExample
    {
        public TransactionMetadataConfigExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        public void AddPerson(string name)
        {
            using var session = Driver.Session();
            var txMetadata = new Dictionary<string, object> { { "applicationId", "123" } };

            session.ExecuteWrite(
                tx => tx.Run("CREATE (a:Person {name: $name})", new { name }).Consume(),
                txConfig => txConfig.WithMetadata(txMetadata));
        }

        [RequireServerFact]
        public void TestTransactionMetadataConfigExample()
        {
            // Given & When
            AddPerson("Alice");
            // Then
            CountPerson("Alice").Should().Be(1);
        }
    }

    public class DatabaseSelectionExampleTest : BaseExample
    {
        public DatabaseSelectionExampleTest(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        [RequireEnterpriseEdition("4.0.0", "5.0.0", VersionComparison.Between)]
        public async void TestUseAnotherDatabaseExample()
        {
            try
            {
                await DropDatabase(Driver, "examples");
            }
            catch (FatalDiscoveryException)
            {
                // Its a new server instance, the database didn't exist yet
            }

            await CreateDatabase(Driver, "examples");

            // Given
            using var example = new DatabaseSelectionExample(Uri, User, Password);
            // When
            example.UseAnotherDatabaseExample();

            // Then
            var greetingCount = ReadInt("examples", "MATCH (a:Greeting) RETURN count(a)");
            greetingCount.Should().Be(1);
        }

        [RequireEnterpriseEdition("5.0.0", VersionComparison.GreaterThanOrEqualTo)]
        public async void TestUseAnotherDatabaseExampleAsync()
        {
            try
            {
                await DropDatabase(Driver, "examples", true);
            }
            catch (FatalDiscoveryException)
            {
                // Its a new server instance, the database didn't exist yet
            }

            await CreateDatabase(Driver, "examples", true);

            // Given
            using var example = new DatabaseSelectionExample(Uri, User, Password);
            // When
            example.UseAnotherDatabaseExample();

            // Then
            var greetingCount = ReadInt("examples", "MATCH (a:Greeting) RETURN count(a)");
            greetingCount.Should().Be(1);
        }

        private int ReadInt(string database, string query)
        {
            using var session = Driver.Session(SessionConfigBuilder.ForDatabase(database));
            return session.Run(query).Single()[0].As<int>();
        }

        private class DatabaseSelectionExample : IDisposable
        {
            private readonly IDriver _driver;
            private bool _disposed;

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

            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }

            ~DatabaseSelectionExample()
            {
                Dispose(false);
            }

            public void UseAnotherDatabaseExample()
            {
                using (var session = _driver.Session(SessionConfigBuilder.ForDatabase("examples")))
                {
                    session.Run("CREATE (a:Greeting {message: 'Hello, Example-Database'}) RETURN a").Consume();
                }

                void SessionConfig(SessionConfigBuilder configBuilder)
                {
                    configBuilder.WithDatabase("examples")
                        .WithDefaultAccessMode(AccessMode.Read)
                        .Build();
                }

                using (var session = _driver.Session(SessionConfig))
                {
                    var result = session.Run("MATCH (a:Greeting) RETURN a.message as msg");
                    var msg = result.Single()[0].As<string>();
                    Console.WriteLine(msg);
                }
            }

            private void Dispose(bool disposing)
            {
                if (_disposed)
                {
                    return;
                }

                if (disposing)
                {
                    _driver?.Dispose();
                }

                _disposed = true;
            }
        }
    }

    [SuppressMessage("ReSharper", "xUnit1013")]
    public class PassBookmarksExample : BaseExample
    {
        public PassBookmarksExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
            : base(output, fixture)
        {
        }

        // Create a company node
        private IResultSummary AddCompany(IQueryRunner tx, string name)
        {
            return tx.Run("CREATE (a:Company {name: $name})", new { name }).Consume();
        }

        // Create a person node
        private IResultSummary AddPerson(IQueryRunner tx, string name)
        {
            return tx.Run("CREATE (a:Person {name: $name})", new { name }).Consume();
        }

        // Create an employment relationship to a pre-existing company node.
        // This relies on the person first having been created.
        private IResultSummary Employ(IQueryRunner tx, string personName, string companyName)
        {
            return tx.Run(
                    @"MATCH (person:Person {name: $personName}) 
                         MATCH (company:Company {name: $companyName}) 
                         CREATE (person)-[:WORKS_FOR]->(company)",
                    new { personName, companyName })
                .Consume();
        }

        // Create a friendship between two people.
        private IResultSummary MakeFriends(IQueryRunner tx, string name1, string name2)
        {
            return tx.Run(
                    @"MATCH (a:Person {name: $name1}) 
                         MATCH (b:Person {name: $name2})
                         MERGE (a)-[:KNOWS]->(b)",
                    new { name1, name2 })
                .Consume();
        }

        // Match and display all friendships.
        private int PrintFriendships(IQueryRunner tx)
        {
            var result = tx.Run("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name");

            var count = 0;
            foreach (var record in result)
            {
                count++;
                Console.WriteLine($"{record["a.name"]} knows {record["b.name"]}");
            }

            return count;
        }

        public void AddEmployAndMakeFriends()
        {
            // To collect the session bookmarks
            var savedBookmarks = new List<Bookmarks>();

            // Create the first person and employment relationship.
            using (var session1 = Driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write)))
            {
                session1.ExecuteWrite(tx => AddCompany(tx, "Wayne Enterprises"));
                session1.ExecuteWrite(tx => AddPerson(tx, "Alice"));
                session1.ExecuteWrite(tx => Employ(tx, "Alice", "Wayne Enterprises"));

                savedBookmarks.Add(session1.LastBookmarks);
            }

            // Create the second person and employment relationship.
            using (var session2 = Driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write)))
            {
                session2.ExecuteWrite(tx => AddCompany(tx, "LexCorp"));
                session2.ExecuteWrite(tx => AddPerson(tx, "Bob"));
                session2.ExecuteWrite(tx => Employ(tx, "Bob", "LexCorp"));

                savedBookmarks.Add(session2.LastBookmarks);
            }

            // Create a friendship between the two people created above.
            using (var session3 = Driver.Session(
                       o =>
                           o.WithDefaultAccessMode(AccessMode.Write).WithBookmarks(savedBookmarks.ToArray())))
            {
                session3.ExecuteWrite(tx => MakeFriends(tx, "Alice", "Bob"));

                session3.ExecuteRead(PrintFriendships);
            }
        }


        [RequireServerFact]
        public void TestPassBookmarksExample()
        {
            // Given & When
            AddEmployAndMakeFriends();

            // Then
            CountNodes("Person", "name", "Alice").Should().Be(1);
            CountNodes("Person", "name", "Bob").Should().Be(1);
            CountNodes("Company", "name", "Wayne Enterprises").Should().Be(1);
            CountNodes("Company", "name", "LexCorp").Should().Be(1);

            var works1 = Read(
                "MATCH (a:Person {name: $person})-[:WORKS_FOR]->(b:Company {name: $company}) RETURN count(a)",
                new { person = "Alice", company = "Wayne Enterprises" });

            works1.Count().Should().Be(1);

            var works2 = Read(
                "MATCH (a:Person {name: $person})-[:WORKS_FOR]->(b:Company {name: $company}) RETURN count(a)",
                new { person = "Bob", company = "LexCorp" });

            works2.Count().Should().Be(1);

            var friends = Read(
                "MATCH (a:Person {name: $person1})-[:KNOWS]->(b:Person {name: $person2}) RETURN count(a)",
                new { person1 = "Alice", person2 = "Bob" });

            friends.Count().Should().Be(1);
        }
    }
}

[Collection(SaIntegrationCollection.CollectionName)]
public abstract class BaseExample : IDisposable
{
    private bool _disposed;
    protected string Password = DefaultInstallation.Password;
    protected string Uri = DefaultInstallation.BoltUri;
    protected string User = DefaultInstallation.User;

    protected BaseExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
    {
        Output = output;
        Driver = fixture.StandAloneSharedInstance.Driver;
    }

    protected ITestOutputHelper Output { get; }
    protected IDriver Driver { set; get; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~BaseExample()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            using (var session = Driver.Session())
            {
                session.Run("MATCH (n) DETACH DELETE n").Consume();
            }
        }

        _disposed = true;
    }

    protected int CountNodes(string label, string property, string value)
    {
        using var session = Driver.Session();
        return session.ExecuteRead(
            tx => tx.Run(
                    $"MATCH (a:{label} {{{property}: $value}}) RETURN count(a)",
                    new { value })
                .Single()[0]
                .As<int>());
    }

    protected int CountPerson(string name)
    {
        return CountNodes("Person", "name", name);
    }

    protected void Write(string query, object parameters = null)
    {
        using var session = Driver.Session();
        session.ExecuteWrite(
            tx =>
                tx.Run(query, parameters).Consume());
    }

    protected List<IRecord> Read(string query, object parameters = null)
    {
        using var session = Driver.Session();
        return session.ExecuteRead(tx => tx.Run(query, parameters).ToList());
    }
}

Connection URIs

A connection URI identifies a graph database and how to connect to it.

The encryption and trust settings provide detail to how that connection should be secured.

Starting with Neo4j 4.0, client-server communication uses only unencrypted local connections by default. This is a change from previous versions, which switched on encryption by default, but generated a self-signed certificate out of the box.

When a full certificate is installed, and encryption is enabled on the driver, full certificate checks are carried out (refer to Operations Manual → SSL framework). Full certificates provide better overall security than self-signed certificates as they include a complete chain of trust back to a root certificate authority.

Neo4j Aura is a secure hosted service backed by full certificates signed by a root certificate authority.

To connect to Neo4j Aura, driver users must enable encryption and the complete set of certificate checks (the latter of which are enabled by default).

For more information, see Examples below.

Initial address resolution

The address provided in a neo4j:// URI is used for initial and fallback communication only.

This communication occurs to bootstrap the routing table, through which all subsequent communication is carried out. Fallback occurs when the driver is unable to contact any of the addresses held in the routing table. The initial address is once again reused to bootstrap the system.

Several options are available for providing this initial logical-to-physical host resolution. These include regular DNS, custom middleware such as a load balancer, and the Driver Object resolver function, all of which are described in the following sections.

DNS resolution

DNS resolution is the default, and always-available option. As it is possible to configure DNS to resolve a single host name down to multiple IP addresses, this can be used to expose all core server IP addresses under a single host name.

dns resolution
Figure 1. Initial address resolution over DNS

Custom middleware

Middleware, such as a load balancer, can be used to group the core servers under a single public address.

custom middleware
Figure 2. Initial address resolution using custom middleware

Resolver function

Neo4j Drivers also present an address resolution intercept hook called the resolver function.

This takes the form of a callback function that accepts a single input address and returns multiple output addresses. The function may hard code the output addresses or may draw them from another configuration source, as required.

resolver function
Figure 3. Initial address resolution using resolver function

The example below shows how to expand a single address into multiple (hard-coded) output addresses:

Example 2. Custom Address Resolver
private IDriver CreateDriverWithCustomResolver(
    string virtualUri,
    IAuthToken token,
    params ServerAddress[] addresses)
{
    return GraphDatabase.Driver(
        virtualUri,
        token,
        o => o.WithResolver(new ListAddressResolver(addresses)).WithEncryptionLevel(EncryptionLevel.None));
}

public void AddPerson(string name)
{
    using var driver = CreateDriverWithCustomResolver(
        "neo4j://x.example.com",
        AuthTokens.Basic(Username, Password),
        ServerAddress.From("a.example.com", 7687),
        ServerAddress.From("b.example.com", 7877),
        ServerAddress.From("c.example.com", 9092));

    using var session = driver.Session();
    session.Run("CREATE (a:Person {name: $name})", new { name });
}

Routing table

The routing table acts like the glue between the driver connectivity layer and the database surface. This table contains a list of server addresses, grouped as readers and writers, and is refreshed automatically by the driver as required.

The driver does not expose any API to work directly with the routing table, but it can sometimes be useful to explore when troubleshooting a system.

Load balancing policies

A policy parameter can be included in the query string of a neo4j:// URI, to customize the routing table and take advantage of multi-data center routing settings.

A prerequisite for using load balancing policies with the driver is that the database is operated on a cluster, and that some server policies are set up.

Examples

Connection URIs are typically formed according to the following pattern:

neo4j://<HOST>:<PORT>[?policy=<POLICY-NAME>]

This targets a routed Neo4j service that may be fulfilled by either a cluster or a single instance. The HOST and PORT values contain a logical hostname and port number targeting the entry point to the Neo4j service (e.g. neo4j://graph.example.com:7687).

In a clustered environment, the URI address will resolve to one of more of the core members; for standalone installations, this will simply point to that server address. The policy parameter allows for customization of the routing table and is discussed in more detail in load balancing policies.

An alternative URI form, using the bolt URI scheme (e.g. bolt://graph.example.com:7687), can be used when a single point-to-point connection is required. This variant is useful for the subset client applications (such as admin tooling) that need to be aware of individual servers, as opposed to those which require a highly available database service.

bolt://<HOST>:<PORT>

Each of the neo4j and bolt URI schemes permit variants that contain extra encryption and trust information. The +s variants enable encryption with a full certificate check, and the +ssc variants enable encryption, but with no certificate check. This latter variant is designed specifically for use with self-signed certificates.

Table 1. Available URI schemes
URI scheme Routing Description

neo4j

Yes

Unsecured

neo4j+s

Yes

Secured with full certificate

neo4j+ssc

Yes

Secured with self-signed certificate

bolt

No

Unsecured

bolt+s

No

Secured with full certificate

bolt+ssc

No

Secured with self-signed certificate

Neo4j 3.x did not provide a routing table in single instance mode and therefore you should use a bolt:// URI if targeting an older, non-clustered server.

The table below provides example code snippets for different deployment configurations. Each snippet expects an auth variable to have been previously defined, containing the authentication details for that connection.

Connecting to a service

The tables below illustrate examples of how to connect to a service with routing:

Table 2. Neo4j Aura or Neo4j >= 4.x, secured with full certificate

Product

Neo4j Aura, Neo4j >= 4.x

Security

Secured with full certificate

Code snippet

GraphDatabase.Driver("neo4j+s://graph.example.com:7687", auth)

Comments

This is the default (and only option) for Neo4j Aura.

Table 3. Neo4j >= 4.x, unsecured

Product

Neo4j >= 4.x

Security

Unsecured

Code snippet

GraphDatabase.Driver("neo4j://graph.example.com:7687", auth);

Comments

This is the default for Neo4j >= 4.x series

Table 4. Neo4j >= 4.x, secured with self-signed certificate

Product

Neo4j >= 4.x

Security

Secured with self-signed certificate

Code snippet

GraphDatabase.Driver("neo4j+ssc://graph.example.com:7687", auth)
To connect to a service without routing, you can replace neo4j with bolt.

Authentication

Authentication details are provided as an auth token which contains the user names, passwords or other credentials required to access the database. Neo4j supports multiple authentication standards but uses basic authentication by default.

Basic authentication

The basic authentication scheme is backed by a password file stored within the server and requires applications to provide a user name and password. For this, use the basic auth helper:

Example 3. Basic authentication
public IDriver CreateDriverWithBasicAuth(string uri, string user, string password)
{
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
}

The basic authentication scheme can also be used to authenticate against an LDAP server.

Kerberos authentication

The Kerberos authentication scheme provides a simple way to create a Kerberos authentication token with a base64 encoded server authentication ticket. The best way to create a Kerberos authentication token is shown below:

Example 4. Kerberos authentication
public IDriver CreateDriverWithKerberosAuth(string uri, string ticket)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Kerberos(ticket),
        o => o.WithEncryptionLevel(EncryptionLevel.None));
}

The Kerberos authentication token can only be understood by the server if the server has the Kerberos Add-on installed.

Custom authentication

For advanced deployments, where a custom security provider has been built, the custom authentication helper can be used.

Example 5. Custom authentication
public IDriver CreateDriverWithCustomizedAuth(
    string uri,
    string principal,
    string credentials,
    string realm,
    string scheme,
    Dictionary<string, object> parameters)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Custom(principal, credentials, realm, scheme, parameters),
        o => o.WithEncryptionLevel(EncryptionLevel.None));
}

Configuration

ConnectionAcquisitionTimeout

The maximum amount of time a session will wait when requesting a connection from the connection pool. For connection pools where all connections are currently being used and the MaxConnectionPoolSize limit has been reached, a session will wait this duration for a connection to be made available. Since the process of acquiring a connection may involve creating a new connection, ensure that the value of this configuration is higher than the configured ConnectionTimeout.

Setting a low value will allow for transactions to fail fast when all connections in the pool have been acquired by other transactions. Setting a higher value will result in these transactions being queued, increasing the chances of eventually acquiring a connection at the cost of longer time to receive feedback on failure. Finding an optimal value may require an element of experimentation, taking into consideration the expected levels of parallelism within your application as well as the MaxConnectionPoolSize.

Default: 60 seconds

Example 6. Configure connection pool
public IDriver CreateDriverWithCustomizedConnectionPool(string uri, string user, string password)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Basic(user, password),
        o => o.WithMaxConnectionLifetime(TimeSpan.FromMinutes(30))
            .WithMaxConnectionPoolSize(50)
            .WithConnectionAcquisitionTimeout(TimeSpan.FromMinutes(2)));
}
ConnectionTimeout

The maximum amount of time to wait for a TCP connection to be established. Connections are only created when a session requires one unless there is an available connection in the connection pool. The driver maintains a pool of open connections which can be loaned to a session when one is available. If a connection is not available, then an attempt to create a new connection (provided the MaxConnectionPoolSize limit has not been reached) is made with this configuration option, providing the maximum amount of time to wait for the connection to be established.

In environments with high latency and high occurrences of connection timeouts it is recommended to configure a higher value. For lower latency environments and quicker feedback on potential network issues configure with a lower value.

Default: 30 seconds

Example 7. Configure connection timeout
public IDriver CreateDriverWithCustomizedConnectionTimeout(string uri, string user, string password)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Basic(user, password),
        o => o.WithConnectionTimeout(TimeSpan.FromSeconds(15)));
}
CustomResolver

Specify a custom server address resolver used by the routing driver to resolve the initial address used to create the driver. See Resolver function for more details.

Encryption

Specify whether to use an encrypted connection between the driver and server.

Default: False

Example 8. Unencrypted configuration
public IDriver CreateDriverWithCustomizedSecurityStrategy(string uri, string user, string password)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Basic(user, password),
        o => o.WithEncryptionLevel(EncryptionLevel.None));
}
MaxConnectionLifetime

The maximum duration the driver will keep a connection for before being removed from the pool. Note that while the driver will respect this value, it is possible that the network environment will close connections inside this lifetime. This is beyond the control of the driver. The check on the connection’s lifetime happens when a session requires a connection. If the available connection’s lifetime is over this limit it is closed and a new connection is created, added to the pool and returned to the requesting session. Changing this configuration value would be useful in environments where users don’t have full control over the network environment and wish to proactively ensure all connections are ready.

Setting this option to a low value will cause a high connection churn rate, and can result in a performance drop. It is recommended to pick a value smaller than the maximum lifetime exposed by the surrounding system infrastructure (such as operating system, router, load balancer, proxy and firewall). Negative values result in lifetime not being checked.

Default: 1 hour (3600 seconds)

MaxConnectionPoolSize

The maximum total number of connections allowed, per host (i.e. cluster nodes), to be managed by the connection pool. In other words, for a direct driver using the bolt:// scheme, this sets the maximum number of connections towards a single database server. For a driver connected to a cluster using the neo4j:// scheme, this sets the maximum amount of connections per cluster member. If a session or transaction tries to acquire a connection at a time when the pool size is at its full capacity, it must wait until a free connection is available in the pool or the request to acquire a new connection times out. The connection acquiring timeout is configured via ConnectionAcquisitionTimeout.

This configuration option allows you to manage the memory and I/O resources being used by the driver and tuning this option is dependent on these factors, in addition to number of cluster members.

Default: 500 connections

MaxTransactionRetryTime

The maximum amount of time that a managed transaction will retry for before failing. Queries that are executed within a managed transaction gain the benefit of being retried when a transient error occurs. When this happens the transaction is retired multiple times up to the MaxTransactionRetryTime.

Configure this option higher in high latency environments or if you are executing many large transactions which could limit the number of times that they are retired and therefore their chance to succeed. Configure lower in low latency environments and where your workload mainly consists of many smaller transactions. Failing transactions faster may highlight the reasons behind the transient errors making it easier to fix underlying issues.

Default: 30 seconds

Example 9. Configure maximum retry time
public IDriver CreateDriverWithCustomizedMaxRetryTime(string uri, string user, string password)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Basic(user, password),
        o => o.WithMaxTransactionRetryTime(TimeSpan.FromSeconds(15)));
}
TrustedCertificates

Specify how to determine the authenticity of encryption certificates provided by the Neo4j instance that you are connecting to. If encryption is disabled, this option has no effect.

Possible values are:

  • TrustManager.CreateChainTrust() - [Default] Accept any certificate that can be verified against the system store.

  • TrustManager.CreateCertTrust(new []{"/path/ca1.crt", "/path/ca2.crt"}) - Accept certificates at specified paths.

  • TrustManager.CreateInsecure() - Accept any certificate, including self-signed ones. Not recommended for production environments.

Example 10. Configure trusted certificates
public IDriver CreateDriverWithCustomizedTrustStrategy(string uri, string user, string password)
{
    return GraphDatabase.Driver(
        uri,
        AuthTokens.Basic(user, password),
        o => o.WithTrustManager(TrustManager.CreateInsecure()));
}
KeepAlive

Specify whether TCP keep-alive should be enabled. To ensure that the connection between the driver and server is still operational, the TCP layer can periodically send messages to check the connection.

Default: True

Logging

All official Neo4j Drivers log information to standard logging channels. This can typically be accessed in an ecosystem-specific way.

The code snippet below demonstrates how to redirect log messages to standard output:

#Please note that you will have to provide your own console logger implementing the ILogger interface.
IDriver driver = GraphDatabase.Driver(..., o => o.WithLogger(logger));