Neo4j Rust Extensions

6.1.0.0 · active · verified Thu Apr 16

neo4j-rust-ext is an official Python library that provides Rust extensions to accelerate the Neo4j Bolt driver for Python. It offers significant performance improvements, often 3x to 10x faster, particularly for use-cases involving few but large records. The library is a drop-in replacement for the standard `neo4j` driver, currently at version 6.1.0.0, and typically releases in alignment with major `neo4j` driver versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates connecting to a Neo4j database and performing basic Cypher queries using the `neo4j` driver, which `neo4j-rust-ext` transparently enhances for performance. Ensure `NEO4J_URI`, `NEO4J_USERNAME`, and `NEO4J_PASSWORD` environment variables are set or modify the default values.

import os
from neo4j import GraphDatabase, RoutingControl

URI = os.environ.get('NEO4J_URI', 'bolt://localhost:7687')
USERNAME = os.environ.get('NEO4J_USERNAME', 'neo4j')
PASSWORD = os.environ.get('NEO4J_PASSWORD', 'password')
DATABASE = os.environ.get('NEO4J_DATABASE', 'neo4j')


class Neo4jApp:
    def __init__(self, uri, username, password):
        self.driver = GraphDatabase.driver(uri, auth=(username, password))
        self.driver.verify_connectivity()

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

    def add_friend(self, name, friend_name):
        # Queries are run against the default database unless specified.
        # Explicitly setting database_='neo4j' for clarity, adjust as needed.
        self.driver.execute_query(
            "MERGE (a:Person {name: $name}) "
            "MERGE (friend:Person {name: $friend_name}) "
            "MERGE (a)-[:KNOWS]->(friend)",
            name=name,
            friend_name=friend_name,
            database_=DATABASE,
        )

    def print_friends(self, name):
        records, _, _ = self.driver.execute_query(
            "MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name "
            "RETURN friend.name ORDER BY friend.name",
            name=name,
            database_=DATABASE,
            routing_=RoutingControl.READ,
        )
        for record in records:
            print(record["friend.name"])


if __name__ == "__main__":
    app = Neo4jApp(URI, USERNAME, PASSWORD)
    print("Adding friends...")
    app.add_friend("Arthur", "Guinevere")
    app.add_friend("Arthur", "Lancelot")
    app.add_friend("Arthur", "Merlin")

    print("Arthur's friends:")
    app.print_friends("Arthur")
    app.close()

view raw JSON →