Skip to content

Latest commit

 

History

History
140 lines (114 loc) · 7.39 KB

README.md

File metadata and controls

140 lines (114 loc) · 7.39 KB

Neo4j .NET Driver

This repository contains the official Neo4j driver for .NET.

This document covers the usage of the driver; for contribution guidance, see Contributing.

Installation

Neo4j publishes its .NET libraries to NuGet with the following targets:

To add the latest NuGet package:

> dotnet add package Neo4j.Driver

Versions

Starting with 5.0, the Neo4j drivers moved to a monthly release cadence. A new minor version is released on the last Thursday of each month to maintain versioning consistency with the core product (Neo4j DBMS), which also has moved to a monthly cadence.

As a policy, Neo4j will not release patch versions except on rare occasions. Bug fixes and updates will go into the latest minor version; users should upgrade to a later version to patch bug fixes. Driver upgrades within a major version will never contain breaking API changes, excluding the Neo4j.Driver.Preview namespace reserved for the preview of features.

See also: https://neo4j.com/developer/kb/neo4j-supported-versions/

Synchronous and Reactive driver extensions

Strong-named

A strong-named version of each driver package is available on NuGet Neo4j.Driver.Signed. The strong-named packages contain the same version of their respective packages with strong-name compliance. Consider using the strong-named version only if your project is strong-named or requires strong-named dependencies.

To add the strong-named version of the driver to your project using the NuGet Package Manager:

> Install-Package Neo4j.Driver.Signed

Getting started

Connecting to a Neo4j database:

using Neo4j.Driver;

await using var driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "password"));

There are a few points to highlight when adding the driver to your project:

  • Each IDriver instance maintains a pool of connections inside; as a result, use a single driver instance per application.
  • Sessions and transactions do not open new connections if a free one is in the driver's connection pool; this makes both resources cheap to create and close.
  • The driver is thread-safe and made to be used across an application. Sessions and transactions are not thread-safe; using a session or transaction concurrently will result in undefined behavior.

Verifying connectivity:

await driver.VerifyConnectivityAsync();

To ensure the credentials and URLs specified when creating the driver, you can call VerifyConnectivityAsync on the driver instance. If either configuration is wrong, the Task will result in an exception.

Executing a single query transaction:

await driver.ExecutableQuery("CREATE (:Node{id: 0})")
    .WithConfig(new QueryConfig(database:"neo4j"))
    .ExecuteAsync();

As of version 5.10, The .NET driver includes a fluent querying API on the driver's IDriver interface. The fluent API is the most concise API for executing single query transactions. It avoids the boilerplate that comes with handling complex problems, such as results that exceed memory or multi-query transactions.

Remember to specify a database.

    .WithConfig(new QueryConfig(database:"neo4j"))

Always specify the database when you know which database the transaction should execute against. By setting the database parameter, the driver avoids a roundtrip and concurrency machinery associated with negotiating a home database.

Getting Results

var response = await driver.ExecutableQuery("MATCH (n:Node) RETURN n.id as id")
    .WithConfig(dbConfig)
    .ExecuteAsync();

The response from the fluent APIs is an EagerResult<IReadOnlyList<IRecord>> unless we use other APIs; more on that later. EagerResult comprises of the following:

  • All records materialized(Result).
  • keys returned from the query(Keys).
  • a query summary(Summary).

Decomposing EagerResult

var (result, _, _) = await driver.ExecutableQuery(query)
    .WithConfig(dbConfig)
    .ExecuteAsync();
foreach (var record in result)
    Console.WriteLine($"node: {record["id"]}")

EagerResult allows you to discard unneeded values with decomposition for an expressive API.

Mapping

var (result, _, _) = await driver.ExecutableQuery(query)
    .WithConfig(dbConfig)
    .WithMap(record => new EntityDTO { id = record["id"].As<long>() })
    .ExecuteAsync();

Types

Values in a record are currently exposed as of object type. The underlying types of these values are determined by their Cypher types.

The mapping between driver types and Cypher types are listed in the table bellow:

Cypher Type Driver Type
null null
List IList< object >
Map IDictionary<string, object>
Boolean boolean
Integer long
Float float
String string
ByteArray byte[]
Point Point
Node INode
Relationship IRelationship
Path IPath

To convert from object to the driver type, a helper method ValueExtensions#As<T> can be used:

IRecord record = await result.SingleAsync();
string name = record["name"].As<string>();

Temporal Types - Date and Time

The mapping among the Cypher temporal types, driver types, and convertible CLR temporal types - DateTime, TimeSpan and DateTimeOffset - (via IConvertible interface) are as follows:

Cypher Type Driver Type Convertible CLR Type
Date LocalDate DateTime, DateOnly(.NET6+)
Time OffsetTime TimeOnly(.NET6+)
LocalTime LocalTime TimeSpan, DateTime
DateTime ZonedDateTime DateTimeOffset
LocalDateTime LocalDateTime DateTime
Duration Duration ---