Skip to content

Neo4j with the Python driver

Uses neo4j 6.4. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

neo4j://neo4j.example.com:7687
neo4j://machnosql.example.com:7687

The address comes from the environment variable NEO4J_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export NEO4J_URI='neo4j://machnosql.example.com:7687'
pip install -r requirements.txt
python app.py

Credentials come from NEO4J_USERNAME and NEO4J_PASSWORD.

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.py
"""Friends of friends on Neo4j, unchanged on MachNoSQL."""
import os
from neo4j import GraphDatabase
auth = (os.environ["NEO4J_USERNAME"], os.environ["NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["NEO4J_URI"], auth=auth) as driver:
driver.verify_connectivity()
driver.execute_query(
"UNWIND $pairs AS pair MERGE (a:Person {name: pair[0]}) MERGE (b:Person {name: pair[1]}) MERGE (a)-[:KNOWS]->(b)",
pairs=[["ada", "grace"], ["grace", "linus"], ["grace", "margaret"], ["linus", "ken"]],
)
records, _, _ = driver.execute_query(
"MATCH (p:Person {name: $name})-[:KNOWS]->()-[:KNOWS]->(fof) WHERE fof <> p RETURN DISTINCT fof.name AS name ORDER BY name",
name="ada",
)
print([record["name"] for record in records])
requirements.txt
neo4j==6.4.1