### Retrieve and Traverse a Path with .NET Driver Source: https://github.com/neo4j/docs-drivers/blob/dev/dotnet-manual/modules/ROOT/pages/data-types.adoc This example demonstrates how to retrieve a path from the database and then iterate through its nodes and relationships to extract specific information. It includes setup for the driver and sample data creation. ```csharp using Neo4j.Driver; const string dbUri = ""; const string dbUser = ""; const string dbPassword = ""; await using var driver = GraphDatabase.Driver(dbUri, AuthTokens.Basic(dbUser, dbPassword)); await driver.VerifyConnectivityAsync(); // Create some :Person nodes linked by :KNOWS relationships await addFriend(driver, "Alice", "BFF", "Bob"); await addFriend(driver, "Bob", "Fiends", "Sofia"); await addFriend(driver, "Sofia", "Acquaintances", "Alice"); // Follow :KNOWS relationships outgoing from Alice three times, return as path var result = await driver.ExecutableQuery @" MATCH path=(:Person {name: $name})-[:KNOWS*3]->(:Person) RETURN path AS friendshipChain " .WithParameters(new { name = "Alice" }) .WithConfig(new QueryConfig(database: "")) .ExecuteAsync(); // Extract path from result var path = result.Result[0].Get("friendshipChain"); Console.WriteLine("-- Path breakdown --"); for (var i=0; i("name"), path.Nodes[i+1].Get("name"), path.Relationships[i].Get("status") ); } /* -- Path breakdown -- Alice knows Bob (BFF). Bob knows Sofia (Fiends). Sofia knows Sofia (Acquaintances). */ async Task addFriend(IDriver driver, string name, string status, string friendName) { await driver.ExecutableQuery @" MERGE (p:Person {name: $name}) MERGE (friend:Person {name: $friendName}) MERGE (p)-[r:KNOWS {status: $status, since: date()}]->(friend) " .WithParameters(new { name = name, status = status, friendName = friendName }) .WithConfig(new QueryConfig(database: "")) .ExecuteAsync(); } ``` -------------------------------- ### Full Example: Creating Nodes and Relationships Source: https://github.com/neo4j/docs-drivers/blob/dev/dotnet-manual/modules/ROOT/pages/query-simple.adoc This comprehensive example demonstrates initializing the driver, creating nodes with properties, establishing relationships, and querying data. It includes error handling for Neo4j exceptions. ```csharp using Neo4j.Driver; // URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io" const string dbUri = ""; const string dbUser = ""; const string dbPassword = ""; await using var driver = GraphDatabase.Driver(dbUri, AuthTokens.Basic(dbUser, dbPassword)); await driver.VerifyConnectivityAsync(); Console.WriteLine("Connection established."); // Toy dataset var people = new List>(); people.Add( new Dictionary() {{"name", "Alice"}, {"age", 42}, {"friends", new List(){"Bob", "Peter", "Anna"}}, } ); people.Add( new Dictionary() {{"name", "Bob"}, {"age", 19}, } ); people.Add( new Dictionary() {{"name", "Peter"}, {"age", 50}, } ); people.Add( new Dictionary() {{"name", "Anna"}, {"age", 33}, } ); try { //Create some nodes foreach (var person in people) { await driver .ExecutableQuery("MERGE (:Person {name: $person.name, age: $person.age})") .WithConfig(new QueryConfig(database: "")) .WithParameters(new { person = person }) .ExecuteAsync(); } // Create some relationships foreach (var person in people) { if (person.ContainsKey("friends")) { await driver.ExecutableQuery (@" MATCH (p:Person {name: $person.name}) UNWIND $person.friends AS friend_name MATCH (friend:Person {name: friend_name}) MERGE (p)-[:KNOWS]->(friend) ") .WithConfig(new QueryConfig(database: "")) .WithParameters(new { person = person }) .ExecuteAsync(); } } // Retrieve Alice's friends who are under 40 Console.WriteLine("Alice's friends under 40:"); var result = await driver.ExecutableQuery (@" MATCH (p:Person {name: $name})-[:KNOWS]-(friend:Person) WHERE friend.age < $age RETURN friend ") .WithConfig(new QueryConfig(database: "", routing: RoutingControl.Readers)) .WithParameters(new { name = "Alice", age = 40 }) .ExecuteAsync(); // Loop through results and do something with them foreach (var record in result.Result) { Console.WriteLine(record.Get("friend").Get("name")); } // Summary information var summary = result.Summary; Console.WriteLine($"The query `{summary.Query.Text}` returned {result.Result.Count()} results in {summary.ResultAvailableAfter.Milliseconds} ms."); } catch (Neo4jException e) { Console.WriteLine(e); Environment.Exit(1); } ``` -------------------------------- ### Full Example: Connect, Prepare, Query, and Process Data in Go Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/query-simple.adoc A comprehensive example showing how to establish a Neo4j connection, prepare data by creating nodes and relationships, execute a query to retrieve specific information, and process the results. ```go package main import ( "fmt" "context" "github.com/neo4j/neo4j-go-driver/v6/neo4j" ) func main() { ctx := context.Background() // Connection to database dbUri := "" dbUser := "" dbPassword := "" driver, err := neo4j.NewDriver( dbUri, neo4j.BasicAuth(dbUser, dbPassword, "")) if err != nil { panic(err) } defer driver.Close(ctx) err = driver.VerifyConnectivity(ctx) if err != nil { panic(err) } // Prepare data people := []map[string]any { {"name": "Alice", "age": 42, "friends": []string{"Bob", "Peter", "Anna"}}, {"name": "Bob", "age": 19}, {"name": "Peter", "age": 50}, {"name": "Anna", "age": 30}, } // Create some nodes for _, person := range people { _, err := neo4j.ExecuteQuery(ctx, driver, "MERGE (p:Person {name: $person.name, age: $person.age})", map[string]any{ "person": person, }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } // Create some relationships for _, person := range people { if person["friends"] != "" { _, err := neo4j.ExecuteQuery(ctx, driver, ` MATCH (p:Person {name: $person.name}) UNWIND $person.friends AS friend_name MATCH (friend:Person {name: friend_name}) MERGE (p)-[:KNOWS]->(friend) `, map[string]any{ "person": person, }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } } // Retrieve Alice's friends who are under 40 result, err := neo4j.ExecuteQuery(ctx, driver, ` MATCH (p:Person {name: $name})-[:KNOWS]-(friend:Person) WHERE friend.age < $age RETURN friend `, map[string]any{ "name": "Alice", "age": 40, }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } // Loop through results and do something with them for _, record := range result.Records { person, _ := record.Get("friend") fmt.Println(person) // or // fmt.Println(record.AsMap()) } // Summary information fmt.Printf("\nThe query `%v` returned %v records in %+v.\n", result.Summary.Query().Text(), len(result.Records), result.Summary.ResultAvailableAfter()) } ``` -------------------------------- ### Full Example: Data Manipulation and Retrieval Source: https://github.com/neo4j/docs-drivers/blob/dev/java-manual/modules/ROOT/pages/query-simple.adoc A comprehensive example demonstrating driver initialization, creating nodes and relationships, querying data, and handling potential Neo4j exceptions. ```java package demo; import java.util.Map; import java.util.List; import java.util.concurrent.TimeUnit; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Record; import org.neo4j.driver.QueryConfig; import org.neo4j.driver.RoutingControl; import org.neo4j.driver.exceptions.Neo4jException; public class App { private static final String dbUri = ""; private static final String dbUser = ""; private static final String dbPassword = ""; public static void main(String... args) { try (var driver = GraphDatabase.driver(dbUri, AuthTokens.basic(dbUser, dbPassword))) { List people = List.of( Map.of("name", "Alice", "age", 42, "friends", List.of("Bob", "Peter", "Anna")), Map.of("name", "Bob", "age", 19), Map.of("name", "Peter", "age", 50), Map.of("name", "Anna", "age", 30) ); try { //Create some nodes people.forEach(person -> { var result = driver.executableQuery("CREATE (p:Person {name: $person.name, age: $person.age})") .withConfig(QueryConfig.builder().withDatabase("").build()) .withParameters(Map.of("person", person)) .execute(); }); // Create some relationships people.forEach(person -> { if(person.containsKey("friends")) { var result = driver.executableQuery(""" MATCH (p:Person {name: $person.name}) UNWIND $person.friends AS friend_name MATCH (friend:Person {name: friend_name}) CREATE (p)-[:KNOWS]->(friend) """) .withConfig(QueryConfig.builder().withDatabase("").build()) .withParameters(Map.of("person", person)) .execute(); } }); // Retrieve Alice's friends who are under 40 var result = driver.executableQuery(""" MATCH (p:Person {name: $name})-[:KNOWS]-(friend:Person) WHERE friend.age < $age RETURN friend """) .withConfig(QueryConfig.builder() .withDatabase("") .withRouting(RoutingControl.READ) .build()) .withParameters(Map.of("name", "Alice", "age", 40)) .execute(); // Loop through results and do something with them result.records().forEach(r -> { System.out.println(r); }); // Summary information System.out.printf("The query %s returned %d records in %d ms.%n", result.summary().query(), result.records().size(), result.summary().resultAvailableAfter(TimeUnit.MILLISECONDS)); } catch (Neo4jException e) { if (e.gqlStatus().equals("42NFF")) { System.out.println("There was a permission issue. Make sure you have correct permissions and try again."); } else { System.out.println(e.getMessage()); System.exit(1); } } } } } ``` -------------------------------- ### Build and View Documentation Source: https://github.com/neo4j/docs-drivers/blob/dev/README.adoc Builds the documentation and starts a local server to view the HTML output. ```bash npm start ``` -------------------------------- ### Setup: Create a Person node Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/query-async.adoc This snippet is used for test setup to ensure data exists for subsequent operations. ```javascript await driver.executeQuery('CREATE (p:Person {name: "Piero Calzesporche"})') ``` -------------------------------- ### Install Manim Requirements Source: https://github.com/neo4j/docs-drivers/blob/dev/animations/README.md Set up a virtual environment and install project dependencies using pip. ```bash python -m venv virtualenvs/manim source virtualenvs/manim/bin/python pip install -r requirements.txt ``` -------------------------------- ### Install Neo4j Go Driver Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/install.adoc Install the Neo4j Go Driver v6.x using 'go get'. Ensure you are within an initialized Go module. ```bash go get github.com/neo4j/neo4j-go-driver/v6 ``` -------------------------------- ### Full Example: Connect, Create, and Query Data Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/query-simple.adoc A comprehensive example demonstrating how to connect to a Neo4j database, create nodes and relationships, retrieve specific data, and log query summary information. ```javascript const neo4j = require('neo4j-driver'); (async () => { const URI = '' const USER = '' const PASSWORD = '' let driver, result let people = [{name: 'Alice', age: 42, friends: ['Bob', 'Peter', 'Anna']}, {name: 'Bob', age: 19}, {name: 'Peter', age: 50}, {name: 'Anna', age: 30}] // Connect to database try { driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD)) await driver.verifyConnectivity() } catch(err) { console.log(`Connection error\n${err}\nCause: ${err.cause}`) await driver.close() return } // Create some nodes for(let person of people) { await driver.executeQuery( 'MERGE (p:Person {name: $person.name, age: $person.age})', { person: person }, { database: '' } ) } // Create some relationships for(let person of people) { if(person.friends != undefined) { await driver.executeQuery(` MATCH (p:Person {name: $person.name}) UNWIND $person.friends AS friendName MATCH (friend:Person {name: friendName}) MERGE (p)-[:KNOWS]->(friend) `, { person: person }, { database: '' } ) } } // Retrieve Alice's friends who are under 40 result = await driver.executeQuery(` MATCH (p:Person {name: $name})-[:KNOWS]-(friend:Person) WHERE friend.age < $age RETURN friend `, { name: 'Alice', age: 40 }, { database: '' } ) // Loop through results and do something with them for(let person of result.records) { // `person.friend` is an object of type `Node` console.log(person.get('friend')) } // Summary information console.log( `The query `${result.summary.query.text}` ` + `returned ${result.records.length} records ` + `in ${result.summary.resultAvailableAfter} ms.` ) await driver.close() })(); ``` -------------------------------- ### Install Node.js Packages Source: https://github.com/neo4j/docs-drivers/blob/dev/README.adoc Installs the required node.js packages for building the documentation. ```bash npm install ``` -------------------------------- ### Connect and Query Neo4j from Browser Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/browser-websockets.adoc Example of connecting to a Neo4j database using the globally available `neo4j` object after including the driver via a script tag. This demonstrates getting server info and closing the driver. ```javascript const URI = '' const USER = '' const PASSWORD = '' const driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD)) const serverInfo = await driver.getServerInfo() // use driver to run queries await driver.close() ``` -------------------------------- ### Install Neo4j Driver on Air-Gapped Machine Source: https://github.com/neo4j/docs-drivers/blob/dev/python-manual/modules/ROOT/pages/install.adoc For air-gapped environments, download the driver tarball from PyPI and install it using pip. ```bash pip install neo4j-.tar.gz ``` -------------------------------- ### Initialize a Go Module Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/install.adoc Use this command to initialize a new Go module for your project. This is the first step before installing any external packages. ```bash mkdir neo4j-app cd neo4j-app go mod init neo4j-app ``` -------------------------------- ### Set up Python virtual environment for migration assistant Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/upgrade.adoc Installs the necessary Python packages for the Neo4j drivers migration assistant within a virtual environment. ```bash python3 -m venv virtualenvs/neo4j-migration source virtualenvs/neo4j-migration/bin/activate pip3 install -r requirements.txt ``` -------------------------------- ### Async driver example with execute_query Source: https://github.com/neo4j/docs-drivers/blob/dev/python-manual/modules/ROOT/pages/concurrency.adoc Demonstrates executing a query using the asynchronous driver. Ensure to use `await` for all async calls and define functions as `async`. ```python import asyncio from neo4j import AsyncGraphDatabase URI = "" AUTH = ("", "") async def main(): async with AsyncGraphDatabase.driver(URI, auth=AUTH) as driver: records, summary, keys = await driver.execute_query( "MATCH (a:Person) RETURN a.name AS name", database_="" ) names = [record["name"] for record in records] print(names) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Log Output Example Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/query-advanced.adoc This is an example of the log output generated when a Neo4j driver connects and establishes a connection with the server, showing routing and connection details. ```log 1681215847749 INFO Routing driver 0 created for server address localhost:7687 1681215847765 INFO Routing table is stale for database: "neo4j" and access mode: "WRITE": RoutingTable[database=neo4j, expirationTime=0, currentTime=1681215847765, routers=[], readers=[], writers=[]] 1681215847773 DEBUG Connection [0][] created towards localhost:7687(127.0.0.1) 1681215847773 DEBUG Connection [0][] C: HELLO {user_agent: 'neo4j-javascript/5.3.0', ...} 1681215847778 DEBUG Connection [0][] S: SUCCESS {"signature":112,"fields":[{"server":"Neo4j/5.8.0","connection_id":"bolt-1782","hints":{"connection.recv_timeout_seconds":{"low":120,"high":0}}}]} 1681215847778 DEBUG Connection [0][bolt-1782] created for the pool localhost:7687 1681215847778 DEBUG Connection [0][bolt-1782] acquired from the pool localhost:7687 1681215847779 DEBUG Connection [0][bolt-1782] C: ROUTE {"address":"localhost:7687"} [] {"db":"neo4j"} 1681215847781 DEBUG Connection [0][bolt-1782] S: SUCCESS {"signature":112,"fields":[{"rt":{"servers":[{"addresses":["localhost:7687"],"role":"WRITE"},{"addresses":["localhost:7687"],"role":"READ"},{"addresses":["localhost:7687"],"role":"ROUTE"}],"ttl":{"low":300,"high":0},"db":"neo4j"}}]} ``` -------------------------------- ### Example of Path Creation, Retrieval, and Processing Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/data-types.adoc Illustrates how to establish a database connection, add relationships, query for a path of a specific length, and then iterate through the path's nodes and relationships to extract information. ```go package main import ( "fmt" "context" "github.com/neo4j/neo4j-go-driver/v6/neo4j" ) func main() { ctx := context.Background() // Connection to database dbUri := "" dbUser := "" dbPassword := "" driver, err := neo4j.NewDriver( dbUri, neo4j.BasicAuth(dbUser, dbPassword, "")) defer driver.Close(ctx) if err != nil { panic(err) } // Create some :Person nodes linked by :KNOWS relationships addFriend(ctx, driver, "Alice", "BFF", "Bob") addFriend(ctx, driver, "Bob", "Fiends", "Sofia") addFriend(ctx, driver, "Sofia", "Acquaintances", "Sofia") // Follow :KNOWS relationships outgoing from Alice three times, return as path result, err := neo4j.ExecuteQuery(ctx, driver, ` MATCH path=(:Person {name: $name})-[:KNOWS*3]->(:Person) RETURN path AS friendshipChain `, map[string]any{ "name": "Alice", }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } path := result.Records[0].AsMap()["friendshipChain"].(neo4j.Path) fmt.Println("-- Path breakdown --") for i := range path.Relationships { name := path.Nodes[i].Props["name"] status := path.Relationships[i].Props["status"] friendName := path.Nodes[i+1].Props["name"] fmt.Printf("%s is friends with %s (%s)\n", name, friendName, status) } } func addFriend(ctx context.Context, driver neo4j.Driver, name string, status string, friendName string) { _, err := neo4j.ExecuteQuery(ctx, driver, ` MERGE (p:Person {name: $name}) MERGE (p)-[r:KNOWS {status: $status, since: date()}]->(friend:Person {name: $friendName}) `, map[string]any{ "name": name, "status": status, "friendName": friendName, }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } ``` -------------------------------- ### Coordinate Multiple Sessions using Bookmarks Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/bookmarks.adoc This example demonstrates how to use bookmarks to coordinate transactions across multiple sessions, ensuring that `sessionC` waits for `sessionA` and `sessionB` to complete before proceeding. ```javascript const neo4j = require('neo4j-driver'); (async () => { const URI = '' const USER = '' const PASSWORD = '' let driver try { driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD)) await driver.verifyConnectivity() } catch(err) { console.log(`-- Connection error --\n${err}\n-- Cause --\n${err.cause}`) return } await createFriends(driver) })() async function createFriends(driver) { let savedBookmarks = [] // To collect the sessions' bookmarks // Create the first person and employment relationship. const sessionA = driver.session({database: ''}) try { await createPerson(sessionA, 'Alice') await employPerson(sessionA, 'Alice', 'Wayne Enterprises') savedBookmarks.concat(sessionA.lastBookmarks()) // <1> } finally { sessionA.close() } // Create the second person and employment relationship. const sessionB = driver.session({database: ''}) try { await createPerson(sessionB, 'Bob') await employPerson(sessionB, 'Bob', 'LexCorp') savedBookmarks.concat(sessionB.lastBookmarks()) // <1> } finally { sessionB.close() } // Create (and show) a friendship between the two people created above. const sessionC = driver.session({ database: '', bookmarks: savedBookmarks // <2> }) try { await createFriendship(sessionC, 'Alice', 'Bob') await printFriendships(sessionC) } finally { sessionC.close() } } // Create a person node. async function createPerson(session, name) { await session.executeWrite(async tx => { await tx.run('CREATE (:Person {name: $name})', { name: name }) }) } // Create an employment relationship to a pre-existing company node. // This relies on the person first having been created. async function employPerson(session, personName, companyName) { await session.executeWrite(async tx => { await tx.run(` MATCH (person:Person {name: $personName}) MATCH (company:Company {name: $companyName}) CREATE (person)-[:WORKS_FOR]->(company)`, { personName: personName, companyName: companyName } ) }) } // Create a friendship between two people. async function createFriendship(session, nameA, nameB) { await session.executeWrite(async tx => { await tx.run(` MATCH (a:Person {name: $nameA}) ``` -------------------------------- ### Full example of explicit transaction with external API interaction Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/transactions.adoc This example demonstrates a complete application flow involving database operations within an explicit transaction, including interaction with external APIs. It highlights the need for careful transaction management when external operations are involved. ```go package main import ( "fmt" "context" "github.com/neo4j/neo4j-go-driver/v6/neo4j" ) func main() { ctx := context.Background() // Connection to database dbUri := "" dbUser := "" dbPassword := "" driver, err := neo4j.NewDriver( dbUri, neo4j.BasicAuth(dbUser, dbPassword, "")) if err != nil { panic(err) } defer driver.Close(ctx) err = driver.VerifyConnectivity(ctx) if err != nil { panic(err) } customerId, err := createCustomer(ctx, driver) if err != nil { panic(err) } otherBankId := 42 transferToOtherBank(ctx, driver, customerId, otherBankId, 999) } func createCustomer(ctx context.Context, driver neo4j.Driver) (string, error) { result, err := neo4j.ExecuteQuery(ctx, driver, ` MERGE (c:Customer {id: randomUUID()}) RETURN c.id AS id `, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { return "", err } customerId, _ := result.Records[0].Get("id") return customerId.(string), err } func transferToOtherBank(ctx context.Context, driver neo4j.Driver, customerId string, otherBankId int, amount float32) { session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: ""}) defer session.Close(ctx) tx, err := session.BeginTransaction(ctx) if err != nil { panic(err) } if ! customerBalanceCheck(ctx, tx, customerId, amount) { // give up return } otherBankTransferApi(ctx, customerId, otherBankId, amount) // Now the money has been transferred => can't rollback anymore ``` -------------------------------- ### Add Neo4j.Driver.Reactive package Source: https://github.com/neo4j/docs-drivers/blob/dev/dotnet-manual/modules/ROOT/pages/reactive.adoc Install the Neo4j.Driver.Reactive NuGet package using the .NET CLI to enable reactive features. ```bash dotnet add package Neo4j.Driver.Reactive ``` -------------------------------- ### Run Neo4j Docker Container Source: https://github.com/neo4j/docs-drivers/blob/dev/common-content/modules/ROOT/partials/install.adoc Use this command to start a Neo4j instance in a Docker container. It forwards the necessary ports and sets the admin credentials. ```bash docker run \ -p7474:7474 \ -p7687:7687 \ -d \ -e NEO4J_AUTH=neo4j/secretgraph \ neo4j:latest ``` -------------------------------- ### Create Example Graph with Parameters Source: https://github.com/neo4j/docs-drivers/blob/dev/java-manual/modules/ROOT/partials/quickstart.adoc Create nodes and relationships using Cypher with parameterized queries to prevent injection vulnerabilities. Use .withParameters() for values and .withConfig() to specify the database. ```java // import java.util.Map; // import java.util.concurrent.TimeUnit; // import org.neo4j.driver.QueryConfig; var result = driver.executableQuery(""" CREATE (a:Person {name: $name}) CREATE (b:Person {name: $friendName}) CREATE (a)-[:KNOWS]->(b) """) .withParameters(Map.of("name", "Alice", "friendName", "David")) .withConfig(QueryConfig.builder().withDatabase("").build()) .execute(); // Summary information var summary = result.summary(); System.out.printf("Created %d records in %d ms.%n", summary.counters().nodesCreated(), summary.resultAvailableAfter(TimeUnit.MILLISECONDS)); ``` -------------------------------- ### Async driver example with transaction functions Source: https://github.com/neo4j/docs-drivers/blob/dev/python-manual/modules/ROOT/pages/concurrency.adoc Shows how to use transaction functions for read operations with the asynchronous driver. This pattern is useful for managing transactional logic. ```python import asyncio from neo4j import AsyncGraphDatabase URI = "" AUTH = ("", "") async def main(): async with AsyncGraphDatabase.driver(URI, auth=AUTH) as driver: async with driver.session(database="") as session: records = await session.execute_read(get_people) print(records) async def get_people(tx): result = await tx.run("MATCH (a:Person) RETURN a.name AS name") records = await result.values() return records if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create Example Graph in Neo4j Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/partials/quickstart.adoc Create nodes and relationships in Neo4j using Driver.executeQuery(). Use placeholders for parameters and specify them as key-value pairs to avoid hardcoding. ```javascript let { records, summary } = await driver.executeQuery(` CREATE (a:Person {name: $name}) CREATE (b:Person {name: $friendName}) CREATE (a)-[:KNOWS]->(b) `, { name: 'Alice', friendName: 'David' }, { database: '' }) console.log( `Created ${summary.counters.updates().nodesCreated} nodes ` + `in ${summary.resultAvailableAfter} ms.` ) ``` -------------------------------- ### Get Query Plan with EXPLAIN Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/performance.adoc Use `EXPLAIN` to retrieve the query execution plan without running the query. The plan details are accessible via `result.Summary.Plan().Arguments()`. ```go result, _ := neo4j.ExecuteQuery(ctx, driver, "EXPLAIN MATCH (p {name: $name}) RETURN p", map[string]any{ "name": "Alice", }, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) fmt.Println(result.Summary.Plan().Arguments()["string-representation"]) ``` -------------------------------- ### Example Log Output on Driver Connection Source: https://github.com/neo4j/docs-drivers/blob/dev/java-manual/modules/ROOT/pages/connect-advanced.adoc This log output demonstrates the detailed information captured when the Neo4j driver establishes a connection to the database. It includes Netty and driver-specific events. ```log 2023-12-22T10:36:39.997882867 INFO org.neo4j.driver.internal.DriverFactory - Routing driver instance 1651855867 created for server address localhost:7687 2023-12-22T10:36:40.03430944 FINE io.netty.channel.DefaultChannelId - -Dio.netty.processId: 23665 (auto-detected) 2023-12-22T10:36:40.036871656 FINE io.netty.util.NetUtil - -Djava.net.preferIPv4Stack: false 2023-12-22T10:36:40.037023871 FINE io.netty.util.NetUtil - -Djava.net.preferIPv6Addresses: false 2023-12-22T10:36:40.03827624 FINE io.netty.util.NetUtilInitializations - Loopback interface: lo (lo, 0:0:0:0:0:0:0:1%lo) 2023-12-22T10:36:40.038877108 FINE io.netty.util.NetUtil - /proc/sys/net/core/somaxconn: 4096 2023-12-22T10:36:40.03958947 FINE io.netty.channel.DefaultChannelId - -Dio.netty.machineId: 04:cf:4b:ff:fe:0e:ee:99 (auto-detected) 2023-12-22T10:36:40.04531968 FINE io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple 2023-12-22T10:36:40.045471749 FINE io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.targetRecords: 4 2023-12-22T10:36:40.059848221 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 40 2023-12-22T10:36:40.060000842 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 40 2023-12-22T10:36:40.060113675 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192 2023-12-22T10:36:40.060219802 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 9 2023-12-22T10:36:40.060324679 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 4194304 2023-12-22T10:36:40.060442554 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256 2023-12-22T10:36:40.060547232 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64 2023-12-22T10:36:40.060648929 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768 2023-12-22T10:36:40.060750268 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192 2023-12-22T10:36:40.060858214 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimIntervalMillis: 0 2023-12-22T10:36:40.060965492 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.useCacheForAllThreads: false 2023-12-22T10:36:40.061068878 FINE io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedByteBuffersPerChunk: 1023 2023-12-22T10:36:40.069792775 FINE io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled 2023-12-22T10:36:40.069957048 FINE io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 0 2023-12-22T10:36:40.070070891 FINE io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384 2023-12-22T10:36:40.102235419 FINE io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true 2023-12-22T10:36:40.102408774 FINE io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true 2023-12-22T10:36:40.103026138 FINE io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@1a67b908 2023-12-22T10:36:40.104721387 FINE org.neo4j.driver.internal.async.connection.ChannelConnectedListener - [0xb354eed2][localhost(127.0.0.1):7687][] C: [Bolt Handshake] [0x6060b017, 263173, 132100, 260, 3] 2023-12-22T10:36:40.106645202 FINE io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096 2023-12-22T10:36:40.106785483 FINE io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8 2023-12-22T10:36:40.106887674 FINE io.netty.util.Recycler - -Dio.netty.recycler.chunkSize: 32 2023-12-22T10:36:40.106993748 FINE io.netty.util.Recycler - -Dio.netty.recycler.blocking: false 2023-12-22T10:36:40.107096042 FINE io.netty.util.Recycler - -Dio.netty.recycler.batchFastThreadLocalOnly: true 2023-12-22T10:36:40.11603651 FINE org.neo4j.driver.internal.async.connection.HandshakeHandler - [0xb354eed2][localhost(127.0.0.1):7687][] S: [Bolt Handshake] 5.4 2023-12-22T10:36:40.128082306 FINE org.neo4j.driver.internal.async.outbound.OutboundMessageHandler - [0xb354eed2][localhost(127.0.0.1):7687][] C: HELLO {routing={address: "localhost:7687"}, bolt_agent={product: "neo4j-java/dev", language: "Java/17.0.9", language_details: "Optional[Eclipse Adoptium; OpenJDK 64-Bit Server VM; 17.0.9+9]", platform: "Linux; 5.15.0-91-generic; amd64"}, user_agent="neo4j-java/dev"} 2023-12-22T10:36:40.130350166 FINE org.neo4j.driver.internal.async.pool.NettyChannelTracker - Channel [0xb354eed2] created. Local address: /127.0.0.1:32794, remote address: /127.0.0.1:7687 ``` -------------------------------- ### Connect to Aura Instance using dotenv-java Source: https://github.com/neo4j/docs-drivers/blob/dev/java-manual/modules/ROOT/pages/connect.adoc This example demonstrates how to connect to a Neo4j Aura instance by loading connection details (URI, username, password) from a .env file using the dotenv-java library. ```java package demo; import io.github.cdimascio.dotenv.Dotenv; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.GraphDatabase; public class App { public static void main(String... args) { var dotenv = Dotenv.configure() //.directory("/path/to/env/file") .filename("Neo4j-a0a2fa1d-Created-2023-11-06.txt") .load(); final String dbUri = dotenv.get("NEO4J_URI"); final String dbUser = dotenv.get("NEO4J_USERNAME"); final String dbPassword = dotenv.get("NEO4J_PASSWORD"); try (var driver = GraphDatabase.driver(dbUri, AuthTokens.basic(dbUser, dbPassword))) { driver.verifyConnectivity(); System.out.println("Connection established."); } } } ``` -------------------------------- ### Upgrade Neo4j Go driver package Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/upgrade.adoc Updates the Neo4j Go driver to the latest version (v5 in this example) using the `go get` command. Ensure include directives are also updated. ```bash go get github.com/neo4j/neo4j-go-driver/v5 ``` -------------------------------- ### Retrieve and Display Relationship Details in Java Source: https://github.com/neo4j/docs-drivers/blob/dev/java-manual/modules/ROOT/pages/data-types.adoc This example shows how to fetch a relationship from Neo4j and print its type, properties, and the element IDs of its start and end nodes. Ensure the Neo4j driver is set up in your project. ```java package demo; import java.util.Map; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.QueryConfig; public class App { public static void main(String... args) { final String dbUri = ""; final String dbUser = ""; final String dbPassword = ""; try (var driver = GraphDatabase.driver(dbUri, AuthTokens.basic(dbUser, dbPassword))) { driver.verifyConnectivity(); // Get a relationship from the database var result = driver.executableQuery("\n MERGE (p:Person {name: $name})\n MERGE (p)-[r:KNOWS {status: $status, since: date()}]->(friend:Person {name: $friendName})\n RETURN r AS friendship\n ") .withParameters(Map.of("name", "Alice", "status", "BFF", "friendName", "Bob")) ``` -------------------------------- ### Install Neo4j Rust Extension Source: https://github.com/neo4j/docs-drivers/blob/dev/python-manual/modules/ROOT/pages/install.adoc Install the Rust extension for the Neo4j Python Driver for a significant speedup. This can be installed alongside or as a replacement for the standard driver. ```bash pip install neo4j-rust-ext ``` -------------------------------- ### Create a New .NET Project with Neo4j.Driver Source: https://github.com/neo4j/docs-drivers/blob/dev/dotnet-manual/modules/ROOT/pages/install.adoc Steps to create a new console application and add the Neo4j.Driver package using the .NET CLI. ```bash mkdir dotnet-neo4j && cd dotnet-neo4j dotnet new console dotnet install package Neo4j.Driver ``` -------------------------------- ### Install Neo4j JavaScript Driver with npm Source: https://github.com/neo4j/docs-drivers/blob/dev/javascript-manual/modules/ROOT/pages/install.adoc Use npm to install the Neo4j JavaScript Driver. This requires npm and any LTS version of Node.js. ```bash npm i neo4j-driver ``` -------------------------------- ### Create Session with Basic Authentication Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/transactions.adoc Establish a new session using basic authentication with a username and password. This method is more efficient than creating a new Driver object for user switching. ```go sessionAuth := neo4j.BasicAuth("", "", "") session := driver.NewSession(ctx, neo4j.SessionConfig{ DatabaseName: "", Auth: &sessionAuth, }) ``` -------------------------------- ### Install Neo4j Python Driver Source: https://github.com/neo4j/docs-drivers/blob/dev/python-manual/modules/ROOT/partials/quickstart.adoc Install the Neo4j Python driver using pip. This is the first step to enable interaction with a Neo4j database from your Python application. ```bash pip install neo4j ``` -------------------------------- ### Coordinating Multiple Sessions with Bookmarks (Go) Source: https://github.com/neo4j/docs-drivers/blob/dev/go-manual/modules/ROOT/pages/bookmarks.adoc This example demonstrates how to use bookmarks to ensure that sessionC waits for the results of sessionA and sessionB to propagate before executing its queries. Bookmarks are combined using neo4j.CombineBookmarks() and passed to the session configuration. ```go package main import ( "fmt" "context" "github.com/neo4j/neo4j-go-driver/v6/neo4j" ) func main() { ctx := context.Background() // Connection to database dbUri := "" dbUser := "" dbPassword := "" driver, err := neo4j.NewDriver( dbUri, neo4j.BasicAuth(dbUser, dbPassword, "")) if err != nil { panic(err) } defer driver.Close(ctx) err = driver.VerifyConnectivity(ctx) if err != nil { panic(err) } // Bookmarks holder var savedBookmarks neo4j.Bookmarks // All function calls below may return errors, // we don't catch them here for simplicity. // Create the first person and employment relationship sessionA := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: ""}) createPerson(ctx, sessionA, "Alice") employ(ctx, sessionA, "Alice", "Wayne Enterprises") savedBookmarks = neo4j.CombineBookmarks(savedBookmarks, sessionA.LastBookmarks()) // <1> sessionA.Close(ctx) // Create the second person and employment relationship sessionB := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: ""}) createPerson(ctx, sessionB, "Bob") employ(ctx, sessionB, "Bob", "LexCorp") savedBookmarks = neo4j.CombineBookmarks(savedBookmarks, sessionB.LastBookmarks()) // <1> sessionB.Close(ctx) // Create a friendship between the two people created above sessionC := driver.NewSession(ctx, neo4j.SessionConfig{ DatabaseName: "", Bookmarks: savedBookmarks, // <2> }) createFriendship(ctx, sessionC, "Alice", "Bob") printFriendships(ctx, sessionC) } // Create a Person node func createPerson(ctx context.Context, session neo4j.Session, name string) (any, error) { ```