Neo4j Primer — Part 5

ab1sh3k
2 min readApr 13, 2024

--

Detailed Integration Scenarios with Neo4j Drivers

Neo4j supports a range of programming languages through its official drivers, enhancing the ease of integration into various application architectures. This section provides a detailed breakdown of how these drivers facilitate robust and efficient interactions with Neo4j, coupled with comprehensive example scenarios illustrating their practical application.

Java Driver

Features

  • Full support for transaction management.
  • Asynchronous query execution.
  • Optimized communication via the Bolt protocol.
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;

public class Neo4jJavaExample {
public static void main(String[] args) {
Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "password"));
try (Session session = driver.session()) {
String greeting = session.writeTransaction(tx -> {
var result = tx.run("CREATE (a:Greeting) SET a.message = 'Hello, World' RETURN a.message + ', from Neo4j.'");
return result.single().get(0).asString();
});
System.out.println(greeting);
}
driver.close();
}
}

Scenario: This Java application creates a new node with a greeting message and retrieves it in a single transaction, demonstrating how to handle transactions and execute queries.

Python Driver

Features

  • Synchronous and asynchronous interfaces.
  • Comprehensive session and transaction handling.
from neo4j import GraphDatabase

class Neo4jConnection:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password))

def close(self):
self.driver.close()

async def get_friends(self, name):
async with self.driver.session() as session:
result = await session.run("MATCH (p:Person)-[:FRIENDS_WITH]->(friend) WHERE p.name = $name RETURN friend.name", name=name)
return [record["friend.name"] for record in result]

conn = Neo4jConnection("bolt://localhost:7687", "neo4j", "password")
friends = conn.get_friends("Alice")
print(friends)

Scenario: This Python script demonstrates asynchronous query execution to retrieve friends of a specified person, illustrating effective use of Neo4j for data retrieval tasks.

JavaScript Driver

Features

  • Usable in both Node.js and browser environments.
  • Supports reactive programming and result streaming.

Example Integration

const neo4j = require('neo4j-driver');
const uri = "bolt://localhost:7687";
const user = "neo4j";
const password = "password";
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password));

async function getEmployeeProjects(employeeId) {
const session = driver.session();
try {
const result = await session.run(
'MATCH (e:Employee {id: $employeeId})-[:WORKS_ON]->(p:Project) RETURN p.name', {employeeId}
);
return result.records.map(record => record.get('p.name'));
} finally {
session.close();
}
}

getEmployeeProjects('123').then(projects => console.log(projects));

Scenario: This Node.js application retrieves all projects associated with a specific employee, showcasing how to perform data access in a non-blocking manner.

Go Driver

Features

  • Robust transaction support and session management.
  • Ideal for high-concurrency applications due to native Go features.

Example Integration

package main

import (
"github.com/neo4j/neo4j-go-driver/v4/neo4j"
"log"
)

func main() {
uri := "bolt://localhost:7687"
username := "neo4j"
password := "password"
driver, err := neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, ""))
if err != nil {
log.Fatal(err)
}
defer driver.Close()
session := driver.NewSession(neo4j.SessionConfig{})
defer session.Close()
result, err := session.Run("MATCH (n) RETURN n LIMIT 10", nil)
if err != nil {
log.Fatal(err)
}
for result.Next() {
println(result.Record().Values[0].(neo4j.Node).Props["name"].(string))
}
}

Scenario — This Go application connects to Neo4j, runs a basic query, and prints out results, demonstrating Go’s capability for handling database operations efficiently in a concurrent environment.

--

--

No responses yet