• Stars
    star
    832
  • Rank 52,734 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated 19 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Neo4j Bolt driver for JavaScript

Neo4j Driver for JavaScript

This is the official Neo4j driver for JavaScript.

Starting with 5.0, the Neo4j Drivers will be moving to a monthly release cadence. A minor version will be released on the last Friday of each month so as to maintain versioning consistency with the core product (Neo4j DBMS) which has also moved to a monthly cadence.

As a policy, patch versions will not be released except on rare occasions. Bug fixes and updates will go into the latest minor version and users should upgrade to that. Driver upgrades within a major version will never contain breaking API changes.

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

Resources to get you started:

What's New in 5.x

Including the Driver

In Node.js application

Stable channel:

npm install neo4j-driver

Pre-release channel:

npm install neo4j-driver@next

Please note that @next only points to pre-releases that are not suitable for production use. To get the latest stable release omit @next part altogether or use @latest instead.

var neo4j = require('neo4j-driver')

Driver instance should be closed when Node.js application exits:

driver.close() // returns a Promise

otherwise application shutdown might hang or it might exit with a non-zero exit code.

In web browser

We build a special browser version of the driver, which supports connecting to Neo4j over WebSockets. It can be included in an HTML page using one of the following tags:

<!-- Direct reference -->
<script src="lib/browser/neo4j-web.min.js"></script>

<!-- unpkg CDN non-minified -->
<script src="https://unpkg.com/neo4j-driver"></script>
<!-- unpkg CDN minified for production use, version X.Y.Z -->
<script src="https://unpkg.com/[email protected]/lib/browser/neo4j-web.min.js"></script>

<!-- jsDelivr CDN non-minified -->
<script src="https://cdn.jsdelivr.net/npm/neo4j-driver"></script>
<!-- jsDelivr CDN minified for production use, version X.Y.Z -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/neo4j-web.min.js"></script>

This will make a global neo4j object available, where you can create a driver instance with neo4j.driver:

var driver = neo4j.driver(
  'neo4j://localhost',
  neo4j.auth.basic('neo4j', 'password')
)

From 5.4.0, this version is also exported as ECMA Script Module. It can be imported from a module using the following statements:

// Direct reference
import neo4j from 'lib/browser/neo4j-web.esm.min.js'

// unpkg CDN non-minified , version X.Y.Z where X.Y.Z >= 5.4.0
import neo4j from 'https://unpkg.com/[email protected]/lib/browser/neo4j-web.esm.js'

// unpkg CDN minified for production use, version X.Y.Z where X.Y.Z >= 5.4.0
import neo4j from 'https://unpkg.com/[email protected]/lib/browser/neo4j-web.esm.min.js'

// jsDelivr CDN non-minified, version X.Y.Z where X.Y.Z >= 5.4.0
import neo4j from 'https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/neo4j-web.esm.js'

// jsDelivr CDN minified for production use, version X.Y.Z where X.Y.Z >= 5.4.0
import neo4j from 'https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/neo4j-web.esm.min.js'

It is not required to explicitly close the driver on a web page. Web browser should gracefully close all open WebSockets when the page is unloaded. However, driver instance should be explicitly closed when it's lifetime is not the same as the lifetime of the web page:

driver.close() // returns a Promise

Usage examples

Constructing a Driver

// Create a driver instance, for the user `neo4j` with password `password`.
// It should be enough to have a single driver per database per application.
var driver = neo4j.driver(
  'neo4j://localhost',
  neo4j.auth.basic('neo4j', 'password')
)

// Close the driver when application exits.
// This closes all used network connections.
await driver.close()

Acquiring a Session

Regular Session

// Create a session to run Cypher statements in.
// Note: Always make sure to close sessions when you are done using them!
var session = driver.session()
with a Default Access Mode of READ
var session = driver.session({ defaultAccessMode: neo4j.session.READ })
with Bookmarks
var session = driver.session({
  bookmarks: [bookmark1FromPreviousSession, bookmark2FromPreviousSession]
})
against a Database
var session = driver.session({
  database: 'foo',
  defaultAccessMode: neo4j.session.WRITE
})

Reactive Session

// Create a reactive session to run Cypher statements in.
// Note: Always make sure to close sessions when you are done using them!
var rxSession = driver.rxSession()
with a Default Access Mode of READ
var rxSession = driver.rxSession({ defaultAccessMode: neo4j.session.READ })
with Bookmarks
var rxSession = driver.rxSession({
  bookmarks: [bookmark1FromPreviousSession, bookmark2FromPreviousSession]
})
against a Database
var rxSession = driver.rxSession({
  database: 'foo',
  defaultAccessMode: neo4j.session.WRITE
})

Executing Queries

Consuming Records with Streaming API

// Run a Cypher statement, reading the result in a streaming manner as records arrive:
session
  .run('MERGE (alice:Person {name : $nameParam}) RETURN alice.name AS name', {
    nameParam: 'Alice'
  })
  .subscribe({
    onKeys: keys => {
      console.log(keys)
    },
    onNext: record => {
      console.log(record.get('name'))
    },
    onCompleted: () => {
      session.close() // returns a Promise
    },
    onError: error => {
      console.log(error)
    }
  })

Subscriber API allows following combinations of onKeys, onNext, onCompleted and onError callback invocations:

  • zero or one onKeys,
  • zero or more onNext followed by onCompleted when operation was successful. onError will not be invoked in this case
  • zero or more onNext followed by onError when operation failed. Callback onError might be invoked after couple onNext invocations because records are streamed lazily by the database. onCompleted will not be invoked in this case.

Consuming Records with Promise API

// the Promise way, where the complete result is collected before we act on it:
session
  .run('MERGE (james:Person {name : $nameParam}) RETURN james.name AS name', {
    nameParam: 'James'
  })
  .then(result => {
    result.records.forEach(record => {
      console.log(record.get('name'))
    })
  })
  .catch(error => {
    console.log(error)
  })
  .then(() => session.close())

Consuming Records with Reactive API

rxSession
  .run('MERGE (james:Person {name: $nameParam}) RETURN james.name AS name', {
    nameParam: 'Bob'
  })
  .records()
  .pipe(
    map(record => record.get('name')),
    concatWith(rxSession.close())
  )
  .subscribe({
    next: data => console.log(data),
    complete: () => console.log('completed'),
    error: err => console.log(err)
  })

Transaction functions

// Transaction functions provide a convenient API with minimal boilerplate and
// retries on network fluctuations and transient errors. Maximum retry time is
// configured on the driver level and is 30 seconds by default:
// Applies both to standard and reactive sessions.
neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', 'password'), {
  maxTransactionRetryTime: 30000
})

Reading with Async Session

// It is possible to execute read transactions that will benefit from automatic
// retries on both single instance ('bolt' URI scheme) and Causal Cluster
// ('neo4j' URI scheme) and will get automatic load balancing in cluster deployments
var readTxResultPromise = session.readTransaction(txc => {
  // used transaction will be committed automatically, no need for explicit commit/rollback

  var result = txc.run('MATCH (person:Person) RETURN person.name AS name')
  // at this point it is possible to either return the result or process it and return the
  // result of processing it is also possible to run more statements in the same transaction
  return result
})

// returned Promise can be later consumed like this:
readTxResultPromise
  .then(result => {
    console.log(result.records)
  })
  .catch(error => {
    console.log(error)
  })
  .then(() => session.close())

Reading with Reactive Session

rxSession
  .readTransaction(txc =>
    txc
      .run('MATCH (person:Person) RETURN person.name AS name')
      .records()
      .pipe(map(record => record.get('name')))
  )
  .subscribe({
    next: data => console.log(data),
    complete: () => console.log('completed'),
    error: err => console.log(error)
  })

Writing with Async Session

// It is possible to execute write transactions that will benefit from automatic retries
// on both single instance ('bolt' URI scheme) and Causal Cluster ('neo4j' URI scheme)
var writeTxResultPromise = session.writeTransaction(async txc => {
  // used transaction will be committed automatically, no need for explicit commit/rollback

  var result = await txc.run(
    "MERGE (alice:Person {name : 'Alice'}) RETURN alice.name AS name"
  )
  // at this point it is possible to either return the result or process it and return the
  // result of processing it is also possible to run more statements in the same transaction
  return result.records.map(record => record.get('name'))
})

// returned Promise can be later consumed like this:
writeTxResultPromise
  .then(namesArray => {
    console.log(namesArray)
  })
  .catch(error => {
    console.log(error)
  })
  .then(() => session.close())

Writing with Reactive Session

rxSession
  .writeTransaction(txc =>
    txc
      .run("MERGE (alice:Person {name: 'James'}) RETURN alice.name AS name")
      .records()
      .pipe(map(record => record.get('name')))
  )
  .subscribe({
    next: data => console.log(data),
    complete: () => console.log('completed'),
    error: error => console.log(error)
  })

Explicit Transactions

With Async Session

// run statement in a transaction
const txc = session.beginTransaction()
try {
  const result1 = await txc.run(
    'MERGE (bob:Person {name: $nameParam}) RETURN bob.name AS name',
    {
      nameParam: 'Bob'
    }
  )
  result1.records.forEach(r => console.log(r.get('name')))
  console.log('First query completed')

  const result2 = await txc.run(
    'MERGE (adam:Person {name: $nameParam}) RETURN adam.name AS name',
    {
      nameParam: 'Adam'
    }
  )
  result2.records.forEach(r => console.log(r.get('name')))
  console.log('Second query completed')

  await txc.commit()
  console.log('committed')
} catch (error) {
  console.log(error)
  await txc.rollback()
  console.log('rolled back')
} finally {
  await session.close()
}

With Reactive Session

rxSession
  .beginTransaction()
  .pipe(
    mergeMap(txc =>
      concatWith(
        txc
          .run(
            'MERGE (bob:Person {name: $nameParam}) RETURN bob.name AS name',
            {
              nameParam: 'Bob'
            }
          )
          .records()
          .pipe(map(r => r.get('name'))),
        of('First query completed'),
        txc
          .run(
            'MERGE (adam:Person {name: $nameParam}) RETURN adam.name AS name',
            {
              nameParam: 'Adam'
            }
          )
          .records()
          .pipe(map(r => r.get('name'))),
        of('Second query completed'),
        txc.commit(),
        of('committed')
      ).pipe(catchError(err => txc.rollback().pipe(throwError(() => err))))
    )
  )
  .subscribe({
    next: data => console.log(data),
    complete: () => console.log('completed'),
    error: error => console.log(error)
  })

Numbers and the Integer type

The Neo4j type system uses 64-bit signed integer values. The range of values is between -(264- 1) and (263- 1).

However, JavaScript can only safely represent integers between Number.MIN_SAFE_INTEGER -(253- 1) and Number.MAX_SAFE_INTEGER (253- 1).

In order to support the full Neo4j type system, the driver will not automatically convert to javascript integers. Any time the driver receives an integer value from Neo4j, it will be represented with an internal integer type by the driver.

Any javascript number value passed as a parameter will be recognized as Float type.

Writing integers

Numbers written directly e.g. session.run("CREATE (n:Node {age: $age})", {age: 22}) will be of type Float in Neo4j.

To write the age as an integer the neo4j.int method should be used:

var neo4j = require('neo4j-driver')

session.run('CREATE (n {age: $myIntParam})', { myIntParam: neo4j.int(22) })

To write an integer value that are not within the range of Number.MIN_SAFE_INTEGER -(253- 1) and Number.MAX_SAFE_INTEGER (253- 1), use a string argument to neo4j.int:

session.run('CREATE (n {age: $myIntParam})', {
  myIntParam: neo4j.int('9223372036854775807')
})

Reading integers

In Neo4j, the type Integer can be larger what can be represented safely as an integer with JavaScript Number.

It is only safe to convert to a JavaScript Number if you know that the number will be in the range Number.MIN_SAFE_INTEGER -(253- 1) and Number.MAX_SAFE_INTEGER (253- 1).

In order to facilitate working with integers the driver include neo4j.isInt, neo4j.integer.inSafeRange, neo4j.integer.toNumber, and neo4j.integer.toString.

var smallInteger = neo4j.int(123)
if (neo4j.integer.inSafeRange(smallInteger)) {
  var aNumber = smallInteger.toNumber()
}

If you will be handling integers that is not within the JavaScript safe range of integers, you should convert the value to a string:

var largeInteger = neo4j.int('9223372036854775807')
if (!neo4j.integer.inSafeRange(largeInteger)) {
  var integerAsString = largeInteger.toString()
}

Enabling native numbers

Starting from 1.6 version of the driver it is possible to configure it to only return native numbers instead of custom Integer objects. The configuration option affects all integers returned by the driver. Enabling this option can result in a loss of precision and incorrect numeric values being returned if the database contains integer numbers outside of the range [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]. To enable potentially lossy integer values use the driver's configuration object:

var driver = neo4j.driver(
  'neo4j://localhost',
  neo4j.auth.basic('neo4j', 'password'),
  { disableLosslessIntegers: true }
)

More Repositories

1

neo4j

Graphs for Everyone
Java
12,473
star
2

NaLLM

Repository for the NaLLM project
TypeScript
952
star
3

neo4j-python-driver

Neo4j Bolt driver for Python
Python
864
star
4

neo4j-browser

Neo4j Browser is the general purpose user interface for working with Neo4j. Query, visualize, administrate and monitor the database.
TypeScript
651
star
5

graph-data-science

Source code for the Neo4j Graph Data Science library of graph algorithms.
Java
585
star
6

graphql

A GraphQL to Cypher query execution layer for Neo4j and JavaScript GraphQL implementations.
TypeScript
485
star
7

neo4j-go-driver

Neo4j Bolt Driver for Go
Go
476
star
8

neo4j-java-driver

Neo4j Bolt driver for Java
Java
322
star
9

neo4j-ogm

Java Object-Graph Mapping Library for Neo4j
Java
322
star
10

docker-neo4j

Docker Images for the Neo4j Graph Database
Shell
307
star
11

neo4j-dotnet-driver

Neo4j Bolt driver for .NET
C#
218
star
12

graph-data-science-client

A Python client for the Neo4j Graph Data Science (GDS) library
Python
168
star
13

neo4j-documentation

Scala
99
star
14

trillion-graph

A scale demo of Neo4j Fabric spanning up to 1129 machines/shards running a 100TB (LDBC) dataset with 1.2tn nodes and relationships.
Java
89
star
15

cypher-shell

Cypher Shell has moved to https://github.com/neo4j/neo4j
Java
88
star
16

docker-neo4j-publish

Shell
82
star
17

sdn-rx

Nextgen Spring Data module for Neo4j supporting (not only) reactive data access and immutable support
Java
66
star
18

apoc

Java
63
star
19

helm-charts

Go
51
star
20

cypher-editor

Codemirror editor for Cypher, with syntax awareness and auto-completion
JavaScript
41
star
21

cypher-builder

A programmatic API for building Cypher queries for Neo4j.
TypeScript
35
star
22

neo4j-java-driver-spring-boot-starter

Automatic configuration of Neo4j's Java Driver for Spring Boot applications
Java
35
star
23

cypher-language-support

Neo4j's Cypher Language support
TypeScript
24
star
24

neo4j-example-auth-plugins

Example authentication and authorization plugins for Neo4j
Java
17
star
25

graphql-tracker-temp

This is a temporary repository for documentation and tracking issues for the @neo4j/graphql package until that repo is made public
12
star
26

graph-schema-introspector

This is a Proof of concept (PoC) for a Neo4j schema introspector that produces output in JSON format validating against graph-schema-json-js-utils.
Java
11
star
27

neo4j-ogm-quarkus

Quarkus extension to that allows proper usage of Neo4j-OGM inside Quarkus.
Java
10
star
28

docs-drivers

Neo4j Drivers Documentation
HTML
8
star
29

windows-wrapper

A service wrapper for windows
Java
8
star
30

neo4j.github.com

Web published resources
HTML
7
star
31

docs-cypher

Neo4j Cypher Documentation
JavaScript
7
star
32

docs-bolt

Neo4j Bolt Protocol Documentation
JavaScript
6
star
33

jsr311-api

Forked from revision 612
Java
6
star
34

dappr

Distributed Approximate Personalised PageRank
Jupyter Notebook
5
star
35

doctools

Perl
5
star
36

neo4j-jdbc

Official Neo4j JDBC Driver (EAP)
Java
5
star
37

github-action-traceability

TypeScript
4
star
38

graph-schema-json-js-utils

Utility library to work with the Graph Schema JSON representation
TypeScript
4
star
39

parents

Neo4j Build Configuration
4
star
40

docs-operations

Neo4j Operations documentation
JavaScript
3
star
41

docs-getting-started

JavaScript
3
star
42

docs-http-api

Documentation for Neo4j HTTP API
JavaScript
3
star
43

neo4j-aws-terraform

HCL
3
star
44

jbang-catalog

JBang catalog
Java
2
star
45

graphql-toolbox

TypeScript
2
star
46

import-spec

Java
2
star
47

docs-graphql

GraphQL docs
JavaScript
2
star
48

docs-maven-plugin

Java
2
star
49

ease-maven-plugin

Java
2
star
50

license-maven-plugin

Fork of http://code.google.com/p/maven-license-plugin/
Java
2
star
51

docs-status-codes

Documentation for Neo4j status codes
JavaScript
2
star
52

maven-skin

Neo4j Maven Skin
Java
2
star
53

docs-aura

Jupyter Notebook
2
star
54

azure-neo4j

Azure topology files
Shell
1
star
55

clirr-maven-plugin

Java
1
star
56

neo4jtester

neo4j tester
Go
1
star
57

docs-ops-manager

JavaScript
1
star