Logo di Neo4j Driver Go Skill

Neo4j Driver Go Skill

Organizzazione
neo4j
neo4j-driver-go-skill

Covers the Neo4j Go Driver v6 — driver lifecycle, ExecuteQuery, managed and explicit transactions, session config, error handling, data type mapping, and connection tuning. Use when writing Go code that connects to Neo4j, setting up NewDriver or ExecuteQuery, or debugging sessions/transactions/result handling. Triggers on NewDriver, ExecuteQuery, SessionConfig, ManagedTransaction, neo4j-go-driver. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver version migration steps — use neo4j-migration-skill.

Panoramica

Pubblicato daneo4j
Repositoryagent-skills
Nome della skillneo4j-driver-go-skill
Stelle
127
Fork
44
File inclusi
3
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • File inclusi: 3

    Script, template e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da neo4j su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Neo4j Driver Go Skill in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/neo4j/agent-skills/tree/main/neo4j-driver-go-skill
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/neo4j/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/neo4j-driver-go-skill .claude/skills/neo4j-driver-go-skill
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Neo4j Driver Go Skill in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Neo4j Driver Go Skill non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Neo4j Driver Go Skill non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

When to Use

  • Writing Go code that connects to Neo4j
  • Setting up neo4j.NewDriver(), ExecuteQuery(), or session/transaction patterns
  • Debugging connection errors, result iteration, type assertions, causal consistency

When NOT to Use

  • Writing/optimizing Cypher → neo4j-cypher-skill
  • v5→v6 migration steps → neo4j-migration-skill

Installation

bash
go get github.com/neo4j/neo4j-go-driver/v6

Import: github.com/neo4j/neo4j-go-driver/v6/neo4j

v5→v6 rename (deprecated aliases still compile, remove before v7):

v5v6
neo4j.NewDriverWithContext(...)neo4j.NewDriver(...)
neo4j.DriverWithContextneo4j.Driver

Environment Variables

go
import "os"

uri      := getEnv("NEO4J_URI",      "neo4j://localhost:7687")
user     := getEnv("NEO4J_USERNAME", "neo4j")
password := getEnv("NEO4J_PASSWORD", "")
database := getEnv("NEO4J_DATABASE", "neo4j")

func getEnv(key, fallback string) string {
    if v := os.Getenv(key); v != "" { return v }
    return fallback
}

Use godotenv to load .env in dev: godotenv.Load(). .env in .gitignore.


Driver Lifecycle

One Driver per application. Goroutine-safe, connection-pooled, expensive to create.

go
func NewNeo4jDriver(uri, user, password string) (neo4j.Driver, error) {
    driver, err := neo4j.NewDriver(
        uri, // "neo4j+s://xxx.databases.neo4j.io" for Aura
        neo4j.BasicAuth(user, password, ""),
    )
    if err != nil {
        return nil, fmt.Errorf("create driver: %w", err)
    }
    ctx := context.Background()
    if err := driver.VerifyConnectivity(ctx); err != nil {
        driver.Close(ctx)
        return nil, fmt.Errorf("verify connectivity: %w", err)
    }
    return driver, nil
}

// In main / app teardown:
defer driver.Close(ctx)

❌ Never create driver per-request. Create once at startup; share across goroutines.

URI schemes: neo4j+s:// (Aura/TLS+routing), neo4j:// (plain+routing), bolt+s:// (TLS+single), bolt:// (plain+single).


Choosing the Right API

APIUse whenAuto-retryLazy results
neo4j.ExecuteQuery()Most queries — simple default✅❌ eager
session.ExecuteRead/Write()Large result sets / streaming✅✅
session.BeginTransaction()Spans multiple functions / ext coordination❌✅
session.Run()CALL IN TRANSACTIONS / auto-commit only❌✅

CALL { … } IN TRANSACTIONS and USING PERIODIC COMMIT manage their own transactions — use session.Run(). They fail inside managed transactions.


ExecuteQuery (Recommended Default)

Manages sessions, transactions, retries, and bookmarks automatically.

go
result, err := neo4j.ExecuteQuery(ctx, driver,
    `MATCH (p:Person {name: $name})-[:KNOWS]->(friend)
     RETURN friend.name AS name`,
    map[string]any{"name": "Alice"},
    neo4j.EagerResultTransformer,
    neo4j.ExecuteQueryWithDatabase("neo4j"),       // always specify
    neo4j.ExecuteQueryWithReadersRouting(),         // for read queries
)
if err != nil {
    return fmt.Errorf("query people: %w", err)
}

for _, record := range result.Records {
    name, _ := record.Get("name")
    fmt.Println(name)
}
fmt.Println(result.Summary.Counters().NodesCreated())

Key options:

go
neo4j.ExecuteQueryWithDatabase("mydb")          // required for performance
neo4j.ExecuteQueryWithReadersRouting()           // route reads to replicas
neo4j.ExecuteQueryWithImpersonatedUser("jane")  // impersonate
neo4j.ExecuteQueryWithoutBookmarkManager()       // opt out of causal consistency

❌ Never concatenate user input into query strings. Always use map[string]any parameters.

Struct parameters [v6.2.0+, Object Mapping preview] — a struct (or pointer) in params is sent as a Cypher map; same rules in Session.Run, ManagedTransaction.Run, ExplicitTransaction.Run:

go
type Person struct {
    Name     string `neo4j:"name"`
    Age      int    `neo4j:"age,omitempty"`  // zero value dropped
    Internal string `neo4j:"-"`              // never sent
}
_, err := neo4j.ExecuteQuery(ctx, driver,
    "MERGE (p:Person {name: $person.name}) SET p += $person",
    map[string]any{"person": Person{Name: "Alice", Age: 30}},
    neo4j.EagerResultTransformer,
    neo4j.ExecuteQueryWithDatabase("neo4j"),
)

Managed Transactions (Session-Based)

Use for lazy streaming (large result sets) or callback-level control.

go
session := driver.NewSession(ctx, neo4j.SessionConfig{
    DatabaseName: "neo4j", // always specify
    AccessMode:   neo4j.AccessModeRead,
})
defer session.Close(ctx)

result, err := session.ExecuteRead(ctx,
    func(tx neo4j.ManagedTransaction) (any, error) {
        res, err := tx.Run(ctx,
            `MATCH (p:Person) RETURN p.name AS name LIMIT $limit`,
            map[string]any{"limit": 100},
        )
        if err != nil {
            return nil, err
        }
        var names []string
        for res.Next(ctx) { // lazy — don't Collect() on large sets
            name, _ := res.Record().Get("name")
            names = append(names, name.(string))
        }
        return names, res.Err()
    },
)

❌ No side effects in callback — retried on transient failures. ExecuteRead → replicas. ExecuteWrite → cluster leader.


Explicit Transactions

Use when transaction work spans multiple functions or requires external coordination.

go
session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: "neo4j"})
defer session.Close(ctx)

tx, err := session.BeginTransaction(ctx)
if err != nil {
    return err
}
if err := doPartA(ctx, tx); err != nil {
    tx.Rollback(ctx)
    return err
}
if err := doPartB(ctx, tx); err != nil {
    tx.Rollback(ctx)
    return err
}
return tx.Commit(ctx)

❌ Not auto-retried. Caller handles retry. Prefer managed transactions unless you need explicit control.


Error Handling

go
result, err := neo4j.ExecuteQuery(...)
if err != nil {
    var neo4jErr *neo4j.Neo4jError
    if errors.As(err, &neo4jErr) {
        slog.Error("database error", "code", neo4jErr.Code, "msg", neo4jErr.Msg)
    }
    var connErr *neo4j.ConnectivityError
    if errors.As(err, &connErr) {
        slog.Error("connectivity error", "err", connErr)
    }
    return fmt.Errorf("execute query: %w", err)
}

Helpers:

go
neo4j.IsNeo4jError(err)                // server-side Cypher/database error
neo4j.IsTransactionExecutionLimit(err) // managed tx retries exhausted

In managed tx callback: return error → driver retries if transient. ConnectivityError at startup: check URI scheme, credentials, firewall.


Data Types

CypherGo
Integerint64
Floatfloat64
Stringstring
Booleanbool
List[]any
Mapmap[string]any
Nodeneo4j.Node
Relationshipneo4j.Relationship
Pathneo4j.Path
Dateneo4j.Date
DateTimetime.Time
LocalDateTimeneo4j.LocalDateTime
Timeneo4j.Time (= dbtype.Time, alias OffsetTime)
LocalTimeneo4j.LocalTime
Pointneo4j.Point2D / neo4j.Point3D
Durationneo4j.Duration
UUIDneo4j.UUID (= dbtype.UUID, [16]byte RFC 9562) — v6.2.0+, Bolt 6.1; parse with dbtype.ParseUUID(s), render with .String()
nullnil

Pin v6.4.0+ for temporal writes: earlier sends pre-1970 Date as next day, dbtype.Time an hour off on DST change days, time.Time with wrong offset when zone name resolves differently at that instant.

go
// Typed extraction (v6+, preferred):
neo4j.GetRecordValue[string](record, "name")

// Manual extraction:
rawAge, ok := record.Get("age")
if !ok { return errors.New("missing 'age' field") }
age := rawAge.(int64) // Neo4j integers → int64

// Node access:
rawNode, _ := record.Get("p")
node := rawNode.(neo4j.Node)
name := node.Props["name"].(string)
labels := node.Labels // []string

❌ Always check ok from record.Get() before type-asserting — panics on missing key. ❌ After lazy for res.Next(ctx) loop, always check res.Err().


Key Patterns

Context — always propagate

go
ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel()
// pass ctx to all driver calls

context.Background() has no deadline — slow queries block indefinitely.

Batching Writes

go
// Bad: one transaction per record
for _, item := range items {
    neo4j.ExecuteQuery(ctx, driver, writeQuery, item, ...)
}

// Good: UNWIND batch in one transaction
neo4j.ExecuteQuery(ctx, driver,
    `UNWIND $items AS item
     MERGE (n:Node {id: item.id})
     SET n += item`,
    map[string]any{"items": items},
    neo4j.EagerResultTransformer,
    neo4j.ExecuteQueryWithDatabase("neo4j"),
)

Generic Helpers (v6+)

Prefer type-safe helpers over manual assertions:

go
// GetRecordValue[T] — extract + cast in one call
name, isNil, err := neo4j.GetRecordValue[string](record, "name")
// isNil=true when OPTIONAL MATCH returned null; err != nil when key absent or wrong type

// CollectTWithContext — map all records to a slice
people, err := neo4j.CollectTWithContext(ctx, result, func(record *neo4j.Record) (Person, error) {
    name, _, err := neo4j.GetRecordValue[string](record, "name")
    age, _, _   := neo4j.GetRecordValue[int64](record, "age")
    return Person{Name: name, Age: int(age)}, err
})

// SingleTWithContext — expect exactly one record (error if 0 or 2+)
person, err := neo4j.SingleTWithContext(ctx, result, func(record *neo4j.Record) (Person, error) {
    name, _, _ := neo4j.GetRecordValue[string](record, "name")
    return Person{Name: name}, nil
})

// GetProperty — typed property from Node or Relationship
node, _, _ := neo4j.GetRecordValue[neo4j.Node](record, "p")
nameVal, err := neo4j.GetProperty[string](node, "name")

Result mapping [v6.3.0+, Object Mapping preview] — map records onto neo4j-tagged structs (same tags as struct parameters):

go
type Person struct {
    Name string `neo4j:"name"`
    Age  int    `neo4j:"age"`   // INTEGER converted; lossy conversion → error, not truncation
}

// EagerResult from ExecuteQuery
res, err := neo4j.ExecuteQuery(ctx, driver,
    "MATCH (p:Person) RETURN p.name AS name, p.age AS age LIMIT 25",
    nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
people, err := neo4j.CollectRecordsAs[Person](res.Records)

// Streaming Result inside a transaction
all, err := neo4j.CollectAs[Person](ctx, result)      // all records
person, err := neo4j.SingleAs[Person](ctx, result)    // exactly one record
p, err := neo4j.As[Person](record)                    // single record

Mapping rules: one column holding a node, relationship, or map → its properties map to fields; otherwise columns map by name. Missing/null → zero value; extra columns ignored.

Spatial Types

go
// 2D Cartesian (SRID 7203), 3D Cartesian (SRID 9157)
pt2d := neo4j.Point2D{X: 1.23, Y: 4.56, SpatialRefId: 7203}
pt3d := neo4j.Point3D{X: 1.23, Y: 4.56, Z: 7.89, SpatialRefId: 9157}

// 2D WGS-84 (SRID 4326), 3D WGS-84 (SRID 4979)
london := neo4j.Point2D{X: -0.118092, Y: 51.509865, SpatialRefId: 4326}
shard  := neo4j.Point3D{X: -0.0865, Y: 51.5045, Z: 310, SpatialRefId: 4979}

// Pass as parameter
result, err := neo4j.ExecuteQuery(ctx, driver,
    "CREATE (p:Place {location: $loc})",
    map[string]any{"loc": london},
    neo4j.EagerResultTransformer,
    neo4j.ExecuteQueryWithDatabase("neo4j"),
)

// Read from result — assert to Point2D or Point3D
raw, _ := record.Get("location")
if p2d, ok := raw.(neo4j.Point2D); ok {
    fmt.Printf("lon=%f lat=%f srid=%d\n", p2d.X, p2d.Y, p2d.SpatialRefId)
}

// Distance (same SRID only)
result, _ = neo4j.ExecuteQuery(ctx, driver,
    "RETURN point.distance($p1, $p2) AS distance",
    map[string]any{"p1": pt2d, "p2": neo4j.Point2D{X: 10, Y: 10, SpatialRefId: 7203}},
    neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"),
)
dist, _ := result.Records[0].Get("distance")
fmt.Println(dist.(float64))

Always Specify Database

go
neo4j.ExecuteQueryWithDatabase("neo4j")    // in ExecuteQuery
neo4j.SessionConfig{DatabaseName: "neo4j"} // in sessions

Omitting costs a network round-trip per call to resolve home database.

Causal Consistency

ExecuteQuery manages bookmarks automatically — no action needed for sequential calls. Cross-session (parallel workers): combine bookmarks explicitly — see references/repository-pattern.md.


Common Errors

Error / SymptomCauseFix
ConnectivityError at startupURI wrong / TLS mismatch / firewallCheck scheme (neo4j+s:// for Aura), credentials, port 7687
ConnectivityError mid-runPool exhaustedIncrease MaxConnectionPoolSize; check for leaked sessions
Panic on type assertionrecord.Get() returned nil/wrong typeUse neo4j.GetRecordValue[T]() or check ok first
res.Err() non-nil after loopNetwork error mid-streamHandle error; re-run transaction
Callback retried unexpectedlySide effect inside managed txMove side effects outside callback
Context deadline exceededNo timeout on contextUse context.WithTimeout
0 results, query looks correctWrong DatabaseNameAlways set DatabaseName in config
CALL IN TRANSACTIONS failsRun inside managed txUse session.Run() (auto-commit)

References

Load on demand:

  • references/advanced-config.md — connection pool tuning, custom address resolver, notification config, Bolt logging, auth options, URI scheme table, deprecated result-summary accessors (Profile() → QueryProfile())
  • references/repository-pattern.md — repository wrapper pattern, cross-session causal consistency with bookmarks
  • references/property-encryption.md — Property Encryption preview [v6.4.0+]: EnvelopeProfile, local key encapsulation, user key repository, EncryptWithAAD / DecryptWithAAD

WebFetch

NeedURL
Go driver manualhttps://neo4j.com/docs/go-manual/current/
API referencehttps://pkg.go.dev/github.com/neo4j/neo4j-go-driver/v6/neo4j

Checklist

  • One driver created at startup; shared across goroutines; defer driver.Close(ctx)
  • driver.VerifyConnectivity(ctx) called at startup
  • DatabaseName set in all SessionConfig / ExecuteQueryWithDatabase
  • context.WithTimeout used for production queries
  • map[string]any parameters used — no string interpolation
  • ExecuteQueryWithReadersRouting() on read-only ExecuteQuery calls
  • res.Err() checked after lazy for result.Next(ctx) loop
  • Type assertions guarded (use GetRecordValue[T] or check ok)
  • No side effects inside managed transaction callbacks
  • session.Run() used for CALL IN TRANSACTIONS / auto-commit queries
  • Sessions closed with defer session.Close(ctx)

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA Neo4j Driver Go Skill?

Covers the Neo4j Go Driver v6 — driver lifecycle, ExecuteQuery, managed and explicit transactions, session config, error handling, data type mapping, and connection tuning. Use when writing Go code that connects to Neo4j, setting up NewDriver or ExecuteQuery, or debugging sessions/transactions/result handling. Triggers on NewDriver, ExecuteQuery, SessionConfig, ManagedTransaction, neo4j-go-driver. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver version migration steps — use neo4j-migration-skill.

Perché usare Neo4j Driver Go Skill su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Neo4j Driver Go Skill è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Neo4j Driver Go Skill in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/neo4j/agent-skills/tree/main/neo4j-driver-go-skill. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Neo4j Driver Go Skill?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Neo4j Driver Go Skill?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Neo4j Driver Go Skill: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Neo4j Driver Go Skill è gratuita?

Sì. È pubblicata su GitHub da neo4j con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇