/neo4j-skills:neo4j-driver-java-skillfrom neo4j-skills
Guides Java/Kotlin Neo4j Driver v6 usage: lifecycle, Maven/Gradle setup, managed/explicit transactions, async/reactive patterns, error handling, type mapping, connection pool tuning, and causal consistency.
Ships in neo4j-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
CompletableFuture) or reactive (Project Reactor / RxJava) Neo4j accessneo4j-cypher-skillneo4j-migration-skill@Node, @Relationship, Neo4jRepository) → neo4j-spring-data-skill<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>6.3.0</version>
</dependency>
implementation 'org.neo4j.driver:neo4j-java-driver:6.3.0'
Check latest: https://central.sonatype.com/artifact/org.neo4j.driver/neo4j-java-driver
6.2.0 [2026-06]: Neo4j UUID type + Bolt 6.1 support; QueryProfile in result summary.
6.2.1 [2026-08]: fixes Value#asObject() on UUID values — required if reading UUID properties generically. Neo4j 2026.08 server bundles 6.2.1; 2026.07 bundles 6.2.0.
6.3.0 [2026-09]: Property Encryption preview — client-side envelope encryption of property values (driver.propertyEncryption()) → references/property-encryption.md.
Server-side UUID type and uuid() constructors ship in Neo4j 2026.08 — use driver >= 6.2.1 against those servers.
Standard pattern for connection config — never hardcode credentials:
String uri = System.getenv().getOrDefault("NEO4J_URI", "neo4j://localhost:7687");
String user = System.getenv().getOrDefault("NEO4J_USERNAME", "neo4j");
String password = System.getenv().getOrDefault("NEO4J_PASSWORD", "");
String database = System.getenv().getOrDefault("NEO4J_DATABASE", "neo4j");
Spring Boot: inject via @Value("${spring.neo4j.uri}") or application.properties:
spring.neo4j.uri=neo4j+s://xxx.databases.neo4j.io
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secret
One Driver per application — thread-safe, expensive to create. Implement AutoCloseable or use try-with-resources.
// Long-lived singleton
var driver = GraphDatabase.driver(
"neo4j+s://xxx.databases.neo4j.io", // Aura TLS+routing
AuthTokens.basic(user, password));
driver.verifyConnectivity(); // fail fast
// Short-lived (tests / CLI)
try (var driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password))) {
driver.verifyConnectivity();
// ...
}
URI schemes:
| URI | Use |
|---|---|
neo4j://localhost | Unencrypted, cluster routing |
neo4j+s://xxx.databases.neo4j.io | TLS + cluster routing (Aura) |
bolt://localhost:7687 | Unencrypted, single instance |
bolt+s://localhost:7687 | TLS, single instance |
Auth options: AuthTokens.basic(u,p) · AuthTokens.bearer(token) · AuthTokens.kerberos(b64) · AuthTokens.none()
| API | When | Auto-retry | Streaming |
|---|---|---|---|
driver.executableQuery() | Default for most queries | ✅ | ❌ eager |
session.executeRead/Write() | Large results, callback control | ✅ | ✅ |
session.beginTransaction() | Multi-method, external coordination | ❌ | ✅ |
session.run() | Self-managing queries (CALL IN TRANSACTIONS) | ⚠️ one-shot [6.1+] | ✅ |
driver.session(AsyncSession.class, cfg) | Non-blocking CompletableFuture | ✅ | ✅ |
driver.session(ReactiveSession.class, cfg) | Reactor/RxJava backpressure | ✅ | ✅ |
CALL { … } IN TRANSACTIONS and USING PERIODIC COMMIT self-manage their transaction — use session.run() only. executableQuery and executeRead/Write will fail for these queries.
session.run() retry [6.1+]: single immediate retry on idempotent errors only (enabled by default). Disable per driver or per session:
// Driver-level — disable for all sessions
var config = Config.builder().withAutoCommitRetriesDisabled(true).build();
// Session-level — overrides driver
var sessionConfig = SessionConfig.builder()
.withAutoCommitRetriesMode(AutoCommitRetriesMode.DISABLED) // DEFAULT = follow driver
.build();
executableQuery — Default// Read — route to replicas
var result = driver.executableQuery("""
MATCH (p:Person {name: $name})-[:KNOWS]->(friend)
RETURN friend.name AS name
""")
.withParameters(Map.of("name", "Alice"))
.withConfig(QueryConfig.builder()
.withDatabase("neo4j") // always specify — avoids home-db round-trip
.withRouting(RoutingControl.READ)
.build())
.execute();
result.records().forEach(r -> System.out.println(r.get("name").asString()));
long ms = result.summary().resultAvailableAfter(TimeUnit.MILLISECONDS);
// Write
driver.executableQuery("CREATE (p:Person {name: $name, age: $age})")
.withParameters(Map.of("name", "Bob", "age", 30))
.withConfig(QueryConfig.builder().withDatabase("neo4j").build())
.execute();
Never string-interpolate Cypher. Always .withParameters(Map.of(...)).
executeRead / executeWrite)Sessions are NOT thread-safe — one per request/thread, always close.
try (var session = driver.session(SessionConfig.builder()
.withDatabase("neo4j").build())) {
// Read → replica routing
var names = session.executeRead(tx -> {
var result = tx.run(
"MATCH (p:Person) WHERE p.name STARTS WITH $prefix RETURN p.name AS name",
Map.of("prefix", "Al"));
return result.stream().map(r -> r.get("name").asString()).toList(); // collect INSIDE
});
// Write → leader routing
session.executeWriteWithoutResult(tx ->
tx.run("CREATE (p:Person {name: $name})", Map.of("name", "Carol"))
);
}
Result is a lazy cursor tied to the open transaction. Transaction closes when callback returns — any read after that throws ResultConsumedException.
// ❌ Returns Result — already closed by the time caller uses it
var result = session.executeRead(tx ->
tx.run("MATCH (p:Person) RETURN p.name AS name"));
result.stream().forEach(...); // throws ResultConsumedException
// ✅ Collect to List inside callback
var names = session.executeRead(tx ->
tx.run("MATCH (p:Person) RETURN p.name AS name")
.stream().map(r -> r.get("name").asString()).toList());
Result before next tx.run() — multiple open cursors = undefined behaviour.MERGE (idempotent), not CREATE, for retry-safe writes.executeRead → replica; executeWrite → leader.var config = TransactionConfig.builder()
.withTimeout(Duration.ofSeconds(5))
.withMetadata(Map.of("app", "myService", "user", userId)) // visible in SHOW TRANSACTIONS
.build();
session.executeRead(tx -> { /* ... */ }, config);
Use when work spans multiple methods or requires external coordination. Not auto-retried.
try (var session = driver.session(SessionConfig.builder().withDatabase("neo4j").build())) {
var tx = session.beginTransaction();
try {
doPartA(tx);
doPartB(tx);
tx.commit();
} catch (Exception e) {
try { tx.rollback(); } catch (Exception rb) { e.addSuppressed(rb); }
throw e;
}
}
tx.rollback() is a network call — wrap in its own try/catch and use addSuppressed so the original exception is not lost.
Commit uncertainty: if tx.commit() throws ServiceUnavailableException, the commit may or may not have succeeded. Design writes as idempotent (MERGE + unique constraints) so retrying is safe.
Choose explicit vs managed:
executeRead / executeWritetx as parameter)try {
driver.executableQuery("...").execute();
} catch (ServiceUnavailableException e) {
// No servers — check connection
} catch (SessionExpiredException e) {
// Server closed session — open new one
} catch (TransientException e) {
// Managed txns retry automatically; explicit txns need manual retry
} catch (Neo4jException e) {
// Cypher/constraint error — e.code() gives GQL status code
}
Managed transactions auto-retry TransientException — no catch needed.
| Cypher type | Java accessor |
|---|---|
Integer | value.asLong() / value.asInt() |
Float | value.asDouble() |
String | value.asString() |
Boolean | value.asBoolean() |
List | value.asList() |
Map | value.asMap() |
Node | value.asNode() |
Relationship | value.asRelationship() |
Date | value.asLocalDate() |
DateTime | value.asZonedDateTime() |
UUID | value.asUUID() → java.util.UUID [6.2+, Neo4j 2026.08+] |
var record = result.records().get(0);
String name = record.get("name").asString();
long age = record.get("age").asLong();
var node = record.get("p").asNode();
String label = node.labels().iterator().next();
Map<String,Object> props = node.asMap();
| Situation | record.get(key) | .asString() |
|---|---|---|
| Key present, value non-null | the value | returns string |
| Key present, value is graph null | Values.NULL (.isNull() = true) | returns the string "null" — no throw |
| Key absent (typo / not projected) | Values.NULL (.isNull() = true) | returns the string "null" — no throw |
Primitive accessors (asLong(), asInt(), asDouble(), asBoolean()) on either null throw Uncoercible. No path throws NoSuchElementException.
// Graph null or absent key — default overload returns default for both:
String city = record.get("city").asString("Unknown");
// Distinguish absent key from graph null — check containsKey:
if (record.containsKey("city") && !record.get("city").isNull()) {
String city = record.get("city").asString();
}
Map query results to Java records/classes directly — eliminates manual accessor calls.
// Domain record — field names match RETURN aliases (case-sensitive)
public record Person(String name, long age) {}
// Map single record
var person = driver.executableQuery("MATCH (p:Person {name: $name}) RETURN p.name AS name, p.age AS age")
.withParameters(Map.of("name", "Alice"))
.withConfig(QueryConfig.builder().withDatabase("neo4j").build())
.execute()
.records()
.stream()
.map(r -> r.get("name").asString()) // String only; for Person use r.as(Person.class) below
.findFirst()
.orElseThrow();
// record.as(Person.class) — maps RETURN keys to record fields by name
var person2 = driver.executableQuery("""
MATCH (p:Person {name: $name})
RETURN p.name AS name, p.age AS age
""")
.withParameters(Map.of("name", "Tom Hanks"))
.withConfig(QueryConfig.builder().withDatabase("neo4j").build())
.execute()
.records()
.stream()
.map(record -> record.as(Person.class)) // NOT record.get("p") — no "p" key → NPE; get("p").as(...) only after RETURN p
.findFirst()
.orElseThrow(() -> new RuntimeException("Person not found"));
Nested mapping — return a map projection and include COLLECT {} for lists:
public record Movie(String title, List<Person> actors) {}
var movieCypher = """
MATCH (movie:Movie)
LIMIT 1
RETURN movie {
.title,
actors: COLLECT {
MATCH (actor:Person)-[:ACTED_IN]->(movie)
RETURN actor
}
}
""";
var movie = driver.executableQuery(movieCypher)
.withConfig(QueryConfig.builder().withDatabase("neo4j").build())
.execute()
.records()
.stream()
.map(r -> r.get("movie").as(Movie.class))
.findFirst()
.orElseThrow();
Only mapped properties defined in the record are populated — extra properties returned by Cypher are ignored.
Always specify database — omitting triggers home-db round-trip on every call.
Route reads to replicas — RoutingControl.READ in QueryConfig or use executeRead.
Batch writes with UNWIND — pass List<Map<String,Object>> (plain maps only; custom objects fail):
List<Map<String, Object>> rows = people.stream()
.map(p -> Map.<String, Object>of("name", p.name(), "age", p.age()))
.toList();
driver.executableQuery("UNWIND $items AS item MERGE (p:Person {name: item.name}) SET p.age = item.age")
.withParameters(Map.of("items", rows))
.withConfig(QueryConfig.builder().withDatabase("neo4j").build())
.execute();
Allowed leaf types in parameter maps: String, Long/Integer/Short/Byte, Double/Float, Boolean, List<?>, Map<String,?>, null. Custom objects and LocalDate must be converted first.
Group writes in one transaction — one executeWrite with a loop, not one executeWrite per iteration.
Connection pool — default 100 connections. Tune if exhausted:
Config.builder()
.withMaxConnectionPoolSize(50)
.withConnectionAcquisitionTimeout(30, TimeUnit.SECONDS)
.build()
| Mistake | Fix |
|---|---|
| String-interpolate Cypher params | .withParameters(Map.of(...)) always |
| Omit database name | Set in QueryConfig / SessionConfig every time |
New Driver per request | Create once at startup; share everywhere |
Share Session across threads | One session per request/thread |
Return Result from tx callback | Collect to List/Map inside callback |
Leave Result open before next tx.run() | Consume before next call |
| Side effects in managed tx callback | Move outside — callback may retry |
| Pass custom objects to UNWIND params | Convert to List<Map<String,Object>> |
asString() on graph null / absent key (returns "null"); asLong() etc. throw Uncoercible | .asString("default") / .asLong(0) or check .isNull() |
| Treat absent key as graph null | containsKey() to tell them apart |
Naked tx.rollback() in catch | Wrap in try/catch; use addSuppressed |
Assume commit() failure = no commit | Commit uncertainty — design writes idempotent |
Block inside async callback (.join()) | Chain with thenCompose |
| Skip session close in async error path | exceptionallyCompose to close then re-throw |
| One transaction per write in loop | Batch with UNWIND or group in one callback |
executeWrite for a read | Use executeRead — routes to replica |
Load on demand:
CompletableFuture patterns, reactive ReactiveSession with Flux.usingWhen, deadlock avoidanceConfig.builder() options, TLS, notification filtering, session-level auth, user impersonation, cross-session bookmarks, spatial types (Values.point/WGS-84/Cartesian)Docs:
Driver instance created at startup; closed on shutdownverifyConnectivity() called after driver creationQueryConfig / SessionConfigResult consumed inside managed transaction callbackexecuteRead/Write callbacksexceptionallyCompose)ServiceUnavailableException on commit handled as commit-uncertainUNWIND params are List<Map<String,Object>> (no custom objects)containsKey() checked before accessing optional result columnsWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub neo4j/agent-skills --plugin neo4j-skills30 skills in this plugin
/neo4j-agent-memory-skillAuthoritative reference for the neo4j-agent-memory Python package — a graph-native memory system for AI agents built on Neo4j — and for the hosted service (NAMS) at memory.neo4jlabs.com. Use this skill whenever the user mentions neo4j-agent-memory, agent memory with Neo4j, context graphs, the POLE+O model, MemoryClient/MemorySettings, the memory MCP server, or any of the framework integrations (LangChain, PydanticAI, CrewAI, AWS Strands, Google ADK, Microsoft Agent Framework, OpenAI Agents, LlamaIndex). Also use when the user mentions the hosted service at memory.neo4jlabs.com, NAMS, the Neo4j Agent Memory Service, the `nams_` API key prefix, or the hosted MCP endpoint. Also use when writing documentation, blog posts, tutorials, PRDs, or code samples for the project, when comparing agent memory approaches, or when positioning graph-native memory against vector-only approaches — even if the user doesn't explicitly name the package. Does NOT handle GraphRAG pipelines — use neo4j-graphrag-skill./neo4j-aura-agent-skillManages Neo4j Aura Agents via the v2beta1 REST API — create, list, get, update, delete, and invoke Aura agents backed by an AuraDB instance. Use when configuring Aura Agent tools (CypherTemplate, SimilaritySearch, Text2Cypher), setting system prompts, deploying agents to REST or MCP endpoints, invoking agents with natural language queries, or generating evaluation datasets (max 50 questions) for the Aura Agent evaluation feature. Covers OAuth2 auth, organization/project scoping, tool parameter schemas, and InvokeAgentResponse format. Does NOT cover AuraDB instance provisioning — use neo4j-aura-provisioning-skill. Does NOT cover vector index creation — use neo4j-vector-index-skill./neo4j-aura-graph-analytics-skillServerless Aura Graph Analytics (AGA) GDS Sessions — covers GdsSessions, AuraGraphDataScience, AuraAPICredentials, DbmsConnectionInfo, SessionMemory, get_or_create, remote graph projection with gds.graph.project.cypher and gds.graph.project.remote, gds.graph.project.native, gds.graph.construct, graphdatascience client 2.0 session endpoints, async compute and gds.jobs, AuraDB Cypher API memory/sessionId projection, algorithms, write-back, and session lifecycle. Use for AuraDB-connected, self-managed Neo4j, or standalone DataFrame/Spark session workloads. Does NOT cover the embedded GDS plugin on Aura Pro or self-managed Neo4j — use neo4j-gds-skill. Does NOT handle Cypher authoring — use neo4j-cypher-skill. Does NOT cover Snowflake Graph Analytics — use neo4j-snowflake-graph-analytics-skill./neo4j-aura-provisioning-skillProvisions and manages Neo4j Aura instances via CLI (aura-cli v1.7+) or REST API. Use when creating, pausing, resuming, resizing, or deleting AuraDB Free/Professional/Business Critical/VDC instances; downloading credentials; scripting CI/CD pipelines; polling async status; or using the Terraform neo4j-labs/neo4jaura provider. Covers auth setup (client credentials OAuth2), credential lifecycle (download once — never recoverable), instance type selection, region codes, and Python provisioning scripts. Does NOT handle Cypher queries — use neo4j-cypher-skill. Does NOT cover Graph Data Science algorithms — use neo4j-gds-skill or neo4j-aura-graph-analytics-skill. Does NOT cover neo4j-admin/cypher-shell — use neo4j-cli-tools-skill./neo4j-cli-tools-skillUse when working with Neo4j command-line tools — neo4j-cli (modern unified CLI — Cypher via Bolt, schema inspection, Aura management, Docker containers, credential management, agent skill catalog install; install with curl -sSfL https://neo4j.sh/install.sh | bash), neo4j-admin (backup, restore, import, memory sizing), cypher-shell (ad-hoc queries, scripting, CI/CD), or neo4j-mcp (quick MCP server install). Does NOT cover Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver upgrades — use neo4j-migration-skill. Does NOT cover full MCP editor configuration — use neo4j-mcp-skill. Does NOT cover the relate embedded engine (relatedb.ai) — use the relate skill; choice guide in neo4j-getting-started-skill./neo4j-cypher-skillGenerates, optimizes, and validates Cypher 25 queries for Neo4j 2025.x and 2026.x. Use when writing new Cypher queries, optimizing slow queries, graph pattern matching, vector or fulltext search, subqueries, or batch writes. Covers MATCH, MERGE, CREATE, WITH, RETURN, CALL, UNWIND, FOREACH, LOAD CSV, SEARCH, expressions, functions, indexes, and subqueries. Does NOT handle driver migration or API changes — use neo4j-migration-skill. Does NOT cover DB administration or server ops — use neo4j-cli-tools-skill. Does NOT cover Cypher on the relate embedded engine — use the relate skill.Other plugins' skills for the same job