Build applications with Neo4j and Go
The Neo4j Go driver is the official library to interact with a Neo4j instance through a Go application.
At the hearth of Neo4j lies Cypher, the query language to interact with a Neo4j database. While this guide does not require you to be a seasoned Cypher querier, it is going to be easier to focus on the Go-specific bits if you already know some Cypher. For this reason, although this guide does also provide a gentle introduction to Cypher along the way, consider checking out Getting started → Cypher for a more detailed walkthrough of graph databases modelling and querying if this is your first approach. You may then apply that knowledge while following this guide to develop your Go application.
Installation
From within a module, use go get
to install the Neo4j Go Driver:
go get github.com/neo4j/neo4j-go-driver/v5
Connect to the database
Connect to a database by creating a DriverWithContext object and providing a URL and an authentication token.
Once you have a DriverWithContext
instance, use the .VerifyConnectivity()
method to ensure that a working connection can be established.
package main
import (
"fmt"
"context"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)
func main() {
ctx := context.Background()
// URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io"
dbUri := "<URI for Neo4j database>"
dbUser := "<Username>"
dbPassword := "<Password>"
driver, err := neo4j.NewDriverWithContext(
dbUri,
neo4j.BasicAuth(dbUser, dbPassword, ""))
defer driver.Close(ctx)
err = driver.VerifyConnectivity(ctx)
if err != nil {
panic(err)
}
fmt.Println("Connection established.")
}
Query the database
Execute a Cypher statement with the function ExecuteQuery()
.
Do not hardcode or concatenate parameters: use placeholders and specify the parameters as keyword arguments.
// Get the name of all 42 year-olds
result, _ := neo4j.ExecuteQuery(ctx, driver,
"MATCH (p:Person {age: $age}) RETURN p.name AS name",
map[string]any{
"age": "42",
}, neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithDatabase("neo4j"))
// Loop through results and do something with them
for _, record := range result.Records {
fmt.Println(record.AsMap())
}
// Summary information
fmt.Printf("The query `%v` returned %v records in %+v.\n",
result.Summary.Query().Text(), len(result.Records),
result.Summary.ResultAvailableAfter())
Run your own transactions
For more advanced use-cases, you can run transactions.
Use the methods Session.ExecuteRead()
and Session.ExecuteWrite()
to run managed transactions.
package main
import (
"fmt"
"context"
"strconv"
"errors"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)
func main() {
ctx := context.Background()
var employeeThreshold int64 = 10 // Neo4j's integer maps to Go's int64
// Connection to database
dbUri := "<URI for Neo4j database>"
dbUser := "<Username>"
dbPassword := "<Password>"
driver, err := neo4j.NewDriverWithContext(
dbUri,
neo4j.BasicAuth(dbUser, dbPassword, ""))
if err != nil {
panic(err)
}
defer driver.Close(ctx)
err = driver.VerifyConnectivity(ctx)
if err != nil {
panic(err)
}
session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: "neo4j"})
defer session.Close(ctx)
// Create 100 people and assign them to various organizations
for i := 0; i < 100; i++ {
name := "Thor" + strconv.Itoa(i)
orgId, err := session.ExecuteWrite(ctx,
func(tx neo4j.ManagedTransaction) (any, error) {
var orgId string
// Create new Person node with given name, if not exists already
_, err := tx.Run(
ctx,
"MERGE (p:Person {name: $name})",
map[string]any{
"name": name,
})
if err != nil {
return nil, err
}
// Obtain most recent organization ID and the number of people linked to it
result, err := tx.Run(
ctx, `
MATCH (o:Organization)
RETURN o.id AS id, COUNT{(p:Person)-[r:WORKS_FOR]->(o)} AS employeesN
ORDER BY o.createdDate DESC
LIMIT 1
`, nil)
if err != nil {
return nil, err
}
org, err := result.Single(ctx)
// If no organization exists, create one and add Person to it
if org == nil {
orgId, _ = createOrganization(ctx, tx)
fmt.Println("No orgs available, created", orgId)
err = addPersonToOrganization(ctx, tx, name, orgId)
if err != nil {
return nil, errors.New("Failed to add person to new org")
// Transaction will roll back
// -> not even Person and/or Organization is created!
}
} else {
orgId = org.AsMap()["id"].(string)
if employeesN := org.AsMap()["employeesN"].(int64);
employeesN == 0 {
return nil, errors.New("Most recent organization is empty")
// Transaction will roll back
// -> not even Person is created!
}
// If org does not have too many employees, add this Person to it
if employeesN := org.AsMap()["employeesN"].(int64);
employeesN < employeeThreshold {
err = addPersonToOrganization(ctx, tx, name, orgId)
if err != nil {
return nil, err
// Transaction will roll back
// -> not even Person is created!
}
// Otherwise, create a new Organization and link Person to it
} else {
orgId, err = createOrganization(ctx, tx)
if err != nil {
return nil, err
// Transaction will roll back
// -> not even Person is created!
}
fmt.Println("Latest org is full, created", orgId)
err = addPersonToOrganization(ctx, tx, name, orgId)
if err != nil {
return nil, err
// Transaction will roll back
// -> not even Person and/or Organization is created!
}
}
}
// Return the Organization ID to which the new Person ends up in
return orgId, nil
})
if err != nil {
fmt.Println(err)
} else {
fmt.Println("User", name, "added to organization", orgId)
}
}
}
func createOrganization(ctx context.Context, tx neo4j.ManagedTransaction) (string, error) {
result, err := tx.Run(
ctx, `
CREATE (o:Organization {id: randomuuid(), createdDate: datetime()})
RETURN o.id AS id
`, nil)
if err != nil {
return "", err
}
org, err := result.Single(ctx)
if err != nil {
return "", err
}
orgId, _ := org.AsMap()["id"]
return orgId.(string), err
}
func addPersonToOrganization(ctx context.Context, tx neo4j.ManagedTransaction, personName string, orgId string) (error) {
_, err := tx.Run(
ctx, `
MATCH (o:Organization {id: $orgId})
MATCH (p:Person {name: $name})
MERGE (p)-[:WORKS_FOR]->(o)
`, map[string]any{
"orgId": orgId,
"name": personName,
})
return err
}
Close connections and sessions
Call the .close()
method on all DriverWithContext
and SessionWithContext
instances to release any resources still held by them.
The best practice is to call the methods with the defer
keyword as soon as you create new objects.
driver, err := neo4j.NewDriverWithContext(dbUri, neo4j.BasicAuth(dbUser, dbPassword, ""))
defer driver.Close(ctx)
session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: "neo4j"})
defer session.Close(ctx)
API documentation
For in-depth information about driver features, check out the API documentation.
Glossary
- LTS
-
A Long Term Support release is one guaranteed to be supported for a number of years. Neo4j 4.4 is LTS, and Neo4j 5 will also have an LTS version.
- Aura
-
Aura is Neo4j’s fully managed cloud service. It comes with both free and paid plans.
- Cypher
-
Cypher is Neo4j’s graph query language that lets you retrieve data from the database. It is like SQL, but for graphs.
- APOC
-
Awesome Procedures On Cypher (APOC) is a library of (many) functions that can not be easily expressed in Cypher itself.
- Bolt
-
Bolt is the protocol used for interaction between Neo4j instances and drivers. It listens on port 7687 by default.
- ACID
-
Atomicity, Consistency, Isolation, Durability (ACID) are properties guaranteeing that database transactions are processed reliably. An ACID-compliant DBMS ensures that the data in the database remains accurate and consistent despite failures.
- eventual consistency
-
A database is eventually consistent if it provides the guarantee that all cluster members will, at some point in time, store the latest version of the data.
- causal consistency
-
A database is causally consistent if read and write queries are seen by every member of the cluster in the same order. This is stronger than eventual consistency.
- NULL
-
The null marker is not a type but a placeholder for absence of value. For more information, see Cypher → Working with
null
. - transaction
-
A transaction is a unit of work that is either committed in its entirety or rolled back on failure. An example is a bank transfer: it involves multiple steps, but they must all succeed or be reverted, to avoid money being subtracted from one account but not added to the other.
- backpressure
-
Backpressure is a force opposing the flow of data. It ensures that the client is not being overwhelmed by data faster than it can handle.
- transaction function
-
A transaction function is a callback executed by an
ExecuteRead
orExecuteWrite
call. The driver automatically re-executes the callback in case of server failure. - DriverWithContext
-
A
DriverWithContext
object holds the details required to establish connections with a Neo4j database.