KuzuDB Python Client

0.11.3 · active · verified Thu Apr 16

Kuzu is a highly scalable, extremely fast, and easy-to-use embedded property graph database, offering serverless integration into applications. It is optimized for complex analytical workloads on very large graphs, featuring a flexible Property Graph Data Model, Cypher query language support, native full-text search, and vector indices. Kuzu is actively developed and frequently releases minor updates and improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Kuzu database, define a schema with node and relationship tables, insert data, and execute Cypher queries using the Python API. It also shows how to retrieve results as a list of rows or a Pandas DataFrame. Remember to explicitly delete `Connection` and `Database` objects to ensure proper cleanup and data persistence, especially in scripts that exit immediately.

import kuzu

# Initialize a database and connection
db_path = 'my_graph_db'
db = kuzu.Database(db_path)
conn = kuzu.Connection(db)

# Define schema (Node Tables and Relationship Tables)
conn.execute("""
    CREATE NODE TABLE User(name STRING, age INT64, PRIMARY KEY (name));
    CREATE NODE TABLE City(name STRING, population INT64, PRIMARY KEY (name));
    CREATE REL TABLE LivesIn(FROM User TO City, start_date DATE);
""")

# Insert data
conn.execute("INSERT INTO User VALUES ('Alice', 30), ('Bob', 25);")
conn.execute("INSERT INTO City VALUES ('New York', 8000000), ('London', 9000000);")
conn.execute("INSERT INTO LivesIn VALUES ('Alice', 'New York', DATE('2020-01-01'));")
conn.execute("INSERT INTO LivesIn VALUES ('Bob', 'London', DATE('2021-03-15'));")

# Query data
result = conn.execute("MATCH (u:User)-[l:LivesIn]->(c:City) RETURN u.name, c.name, l.start_date;")

# Fetch and print results
for row in result.get_as_list():
    print(f"User: {row[0]}, City: {row[1]}, Lived Since: {row[2]}")

# Close the database connection (important to flush changes)
del conn
del db

# You can also fetch results as a Pandas DataFrame if pandas is installed
try:
    import pandas as pd
    db_df = kuzu.Database(db_path) # Re-open database
    conn_df = kuzu.Connection(db_df)
    df_result = conn_df.execute("MATCH (u:User) RETURN u.name, u.age;").get_as_df()
    print("\nResults as DataFrame:")
    print(df_result)
    del conn_df
    del db_df
except ImportError:
    print("\nInstall pandas (pip install pandas) to see DataFrame output.")

view raw JSON →