The official Neo4j driver for JavaScript applications, enabling connection to and interaction with Neo4j graph databases.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Session management for executing queries and managing database interactions with support for read/write modes and transaction handling.
Sessions are created from driver instances and provide the primary interface for query execution.
interface Driver {
/** Create a new session with optional configuration */
session(config?: SessionConfig): Session;
/** Create a new reactive session with optional configuration */
rxSession(config?: SessionConfig): RxSession;
}
interface SessionConfig {
/** Default access mode for the session */
defaultAccessMode?: SessionMode;
/** Bookmarks for causal consistency */
bookmarks?: string | string[] | Bookmarks;
/** Target database name (Neo4j 4.0+) */
database?: string;
/** User to impersonate for queries */
impersonatedUser?: string;
/** Bookmark manager for automatic bookmark handling */
bookmarkManager?: BookmarkManager;
/** Session-level notification filtering */
notificationFilter?: NotificationFilter;
/** Session-level authentication override */
auth?: AuthToken | AuthTokenManager;
}
type SessionMode = "READ" | "WRITE";Usage Examples:
import { driver, auth, session } from "neo4j-driver";
const neo4jDriver = driver("neo4j://localhost:7687", auth.basic("neo4j", "password"));
// Default session
const defaultSession = neo4jDriver.session();
// Read-only session
const readSession = neo4jDriver.session({
defaultAccessMode: session.READ,
database: "mydb"
});
// Session with bookmarks
const bookmarkedSession = neo4jDriver.session({
bookmarks: ["bookmark:12345"],
database: "analytics"
});Execute Cypher queries directly on sessions with parameter support.
interface Session {
/**
* Run a Cypher query with optional parameters
* @param query - The Cypher query string
* @param parameters - Query parameters as key-value pairs
* @returns Promise resolving to query result
*/
run(query: string, parameters?: Parameters): Promise<Result>;
/** Get the last bookmark for this session */
lastBookmark(): string;
/** Get all bookmarks for this session */
lastBookmarks(): string[];
/** Close the session and release resources */
close(): Promise<void>;
}
type Parameters = Record<string, any>;Usage Examples:
const session = neo4jDriver.session();
try {
// Simple query
const result1 = await session.run("MATCH (n:Person) RETURN n LIMIT 10");
// Parameterized query
const result2 = await session.run(
"CREATE (p:Person {name: $name, age: $age}) RETURN p",
{ name: "Alice", age: 30 }
);
// Complex query with multiple parameters
const result3 = await session.run(`
MATCH (p:Person {name: $name})
SET p.lastLogin = $timestamp
RETURN p
`, {
name: "Alice",
timestamp: new Date().toISOString()
});
console.log(`Created ${result2.summary.counters.nodesCreated} nodes`);
} finally {
await session.close();
}Managed transactions with automatic retry logic for robust database operations.
interface Session {
/**
* Execute a read transaction with automatic retry logic
* @param work - Function containing read operations
* @param config - Optional transaction configuration
* @returns Promise resolving to the work function result
*/
executeRead<T>(
work: (tx: ManagedTransaction) => Promise<T>,
config?: TransactionConfig
): Promise<T>;
/**
* Execute a write transaction with automatic retry logic
* @param work - Function containing write operations
* @param config - Optional transaction configuration
* @returns Promise resolving to the work function result
*/
executeWrite<T>(
work: (tx: ManagedTransaction) => Promise<T>,
config?: TransactionConfig
): Promise<T>;
}
interface ManagedTransaction {
/** Run a query within the managed transaction */
run(query: string, parameters?: Parameters): Promise<Result>;
}
interface TransactionConfig {
/** Transaction timeout in milliseconds */
timeout?: number;
/** Transaction metadata for monitoring */
metadata?: Record<string, any>;
}Usage Examples:
const session = neo4jDriver.session();
try {
// Read transaction
const people = await session.executeRead(async tx => {
const result = await tx.run("MATCH (p:Person) RETURN p.name AS name");
return result.records.map(record => record.get("name"));
});
// Write transaction with retry logic
const created = await session.executeWrite(async tx => {
const result = await tx.run(`
CREATE (p:Person {name: $name, id: randomUUID()})
RETURN p.id AS id
`, { name: "Bob" });
return result.records[0].get("id");
}, {
timeout: 30000, // 30 seconds
metadata: { operation: "create_person" }
});
console.log(`Created person with ID: ${created}`);
} finally {
await session.close();
}Manual transaction management with full control over commit and rollback.
interface Session {
/**
* Begin an explicit transaction
* @param config - Optional transaction configuration
* @returns Promise resolving to transaction instance
*/
beginTransaction(config?: TransactionConfig): Promise<Transaction>;
}
interface Transaction {
/** Run a query within the transaction */
run(query: string, parameters?: Parameters): Promise<Result>;
/** Commit the transaction */
commit(): Promise<void>;
/** Rollback the transaction */
rollback(): Promise<void>;
/** Check if the transaction is still open */
isOpen(): boolean;
}Usage Examples:
const session = neo4jDriver.session();
const tx = await session.beginTransaction();
try {
// Multiple operations in single transaction
await tx.run("CREATE (p:Person {name: $name})", { name: "Charlie" });
const result = await tx.run(`
MATCH (p:Person {name: $name})
CREATE (p)-[:WORKS_FOR]->(c:Company {name: $company})
RETURN c
`, { name: "Charlie", company: "Acme Corp" });
// Commit if all operations succeed
await tx.commit();
console.log("Transaction committed successfully");
} catch (error) {
// Rollback on any error
await tx.rollback();
console.error("Transaction rolled back:", error.message);
} finally {
await session.close();
}Query results provide access to records and execution metadata.
interface Result {
/** Array of result records */
records: Record[];
/** Query execution summary */
summary: ResultSummary;
/** Column keys from the query */
keys: string[];
}
interface Record {
/** Get field value by key */
get(key: string): any;
/** Get field value by index */
get(index: number): any;
/** Check if field exists */
has(key: string): boolean;
/** Get all field keys */
keys: string[];
/** Get record length */
length: number;
/** Convert record to plain object */
toObject(): Record<string, any>;
}
interface ResultSummary {
/** Query that was executed */
query: Query;
/** Query execution statistics */
counters: QueryStatistics;
/** Query execution plan (if available) */
plan?: Plan;
/** Profiled execution plan (if available) */
profile?: ProfiledPlan;
/** Execution notifications */
notifications: Notification[];
/** Server information */
server: ServerInfo;
/** Result availability information */
resultAvailableAfter: Integer;
/** Result consumption time */
resultConsumedAfter: Integer;
/** Database name where query was executed */
database: { name?: string };
}Usage Examples:
const session = neo4jDriver.session();
try {
const result = await session.run(`
MATCH (p:Person)
WHERE p.age > $minAge
RETURN p.name AS name, p.age AS age
ORDER BY p.age DESC
`, { minAge: 25 });
// Process records
result.records.forEach(record => {
console.log(`${record.get("name")} is ${record.get("age")} years old`);
// Alternative access methods
console.log(`${record.get(0)} is ${record.get(1)} years old`);
// Convert to object
const person = record.toObject();
console.log(person); // { name: "Alice", age: 30 }
});
// Examine summary
console.log(`Query returned ${result.records.length} records`);
console.log(`Query executed in ${result.summary.resultAvailableAfter} ms`);
if (result.summary.notifications.length > 0) {
result.summary.notifications.forEach(notification => {
console.warn(`Warning: ${notification.description}`);
});
}
} finally {
await session.close();
}Constants for controlling session read/write behavior.
declare const session: {
/** Read-only access mode */
READ: "READ";
/** Read-write access mode */
WRITE: "WRITE";
};