Using the Neo4j Python Driver (How to connect and operate Neo4j in Python)

Neo4j is a graph database that supports high-performance, high-reliability, and highly scalable data storage and retrieval. Python is a very popular programming language that can be used to interact with Neo4j.

1. Install Neo4j Python Driver

First, you need to install the Neo4j Python driver. The most common methods are as follows:

  • You can use pip to install: pip install neo4j
  • Or use conda to install: conda install -c neo4j neo4j

2. Configure Neo4j Connection Information

After installing the Neo4j Python driver, you need to configure the Neo4j connection information. Here is an example code:

from neo4j import GraphDatabase

# Neo4j connection information
neo4j_username = "neo4j"
neo4j_password = "password"
neo4j_address = "bolt://localhost:7687"

# Establish connection
driver = GraphDatabase.driver(neo4j_address, auth=(neo4j_username, neo4j_password))

3. Use Neo4j Python Driver to Create Nodes and Relationships

Using the Neo4j Python driver, you can create nodes (such as users, products, etc.) and relationships.

def create_node(driver, node_type, properties):
    with driver.session() as session:
        result = session.run("CREATE (n:%s { %s })", node_type, ", ".join([f"{key}: {value}" for key, value in properties.items()]))

def create_relationship(driver, start_node, end_node, relationship_type):
    with driver.session() as session:
        result = session.run("""
            MATCH (a:%s)
            MATCH (b:%s)
            CREATE (a)-[:%s]->(b)
        """, start_node, end_node, relationship_type)

4. Use Neo4j Python Driver to Match Nodes and Relationships

Using the Neo4j Python driver, you can match nodes and relationships.

def find_all_nodes_by_label(driver, label):
    with driver.session() as session:
        result = session.run("MATCH (n:%s) RETURN n", label)

def find_all_relationships_between_two_nodes(driver, start_node, end_node):
    with driver.session() as session:
        result = session.run("""
            MATCH (a:%s)
            MATCH (b:%s)
            RETURN a, b
        """, start_node, end_node)

5. Close Neo4j Connection

Finally, you need to close the Neo4j connection.

# Close connection
driver.close()

Final Example

The following is a complete example of creating nodes and relationships in Neo4j:

from neo4j import GraphDatabase

# Neo4j connection information
neo4j_username = "neo4j"
neo4j_password = "password"
neo4j_address = "bolt://localhost:7687"

def main():
    driver = GraphDatabase.driver(neo4j_address, auth=(neo4j_username, neo4j_password))

    create_node(driver, "User", {"name": "John Doe", "age": 30})
    create_node(driver, "Product", {"name": "Apple iPhone", "price": 999.99})

    create_relationship(driver, "User", "Product", "PURCHASED")

    result = driver.session().run("MATCH (u:User)-[r:Purchased]->(p:Product) RETURN u, r, p")
    for record in result:
        print(record["u"], record["r"], record["p"])

    driver.close()

if __name__ == "__main__":
    main()

The Neo4j Python driver provides a high-level, easy-to-use interface that can help you connect to and operate Neo4j in Python. It supports creating nodes and relationships, matching nodes and relationships, closing connections, and other functions.