### Start Web Server Source: https://github.com/kuzudb/kuzu/blob/master/tools/wasm/examples/browser_persistent/README.md Start a local web server to serve the example application. Navigate to http://localhost:3000 in your browser to view the example. ```bash npm run serve ``` -------------------------------- ### Run Kuzu Node.js Example Source: https://github.com/kuzudb/kuzu/blob/master/tools/wasm/examples/nodejs/README.md Execute this command to start the Node.js example that interacts with the Kuzu WebAssembly module. ```bash npm start ``` -------------------------------- ### Run Example Project Source: https://github.com/kuzudb/kuzu/blob/master/tools/java_api/README.md Navigate to the example directory and run the example project using Gradle. ```bash cd example && gradle run ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/kuzudb/kuzu/blob/master/tools/wasm/examples/browser_persistent/README.md Install project dependencies using npm. This is a prerequisite for bootstrapping and running the example. ```bash npm i ``` -------------------------------- ### Quick Start: Initialize and Query Database (ES Modules) Source: https://github.com/kuzudb/kuzu/blob/master/tools/nodejs_api/README.md Initialize a Kuzu database, establish a connection, define schema, load data from CSV, and run a query. This example uses ES Modules for imports. ```javascript // Import the Kùzu module (ESM) import { Database, Connection } from "kuzu"; const main = async () => { // Initialize database and connection const db = new Database("./test"); const conn = new Connection(db); // Define schema await conn.query(` CREATE NODE TABLE User(name STRING, age INT64, PRIMARY KEY (name)); `); await conn.query(` CREATE NODE TABLE City(name STRING, population INT64, PRIMARY KEY (name)); `); await conn.query(` CREATE REL TABLE Follows(FROM User TO User, since INT64); `); await conn.query(` CREATE REL TABLE LivesIn(FROM User TO City); `); // Load data from CSV files await conn.query("COPY User FROM \"user.csv\""); await conn.query("COPY City FROM \"city.csv\""); await conn.query("COPY Follows FROM \"follows.csv\""); await conn.query("COPY LivesIn FROM \"lives-in.csv\""); // Run a query const result = await conn.query("MATCH (u:User) RETURN u.name, u.age;"); // Fetch all results const rows = await result.getAll(); // Output results for (const row of rows) { console.log(row); } }; main().catch(console.error); ``` -------------------------------- ### Run Kuzu Benchmark Source: https://github.com/kuzudb/kuzu/blob/master/benchmark/lsqb/README.md Execute the benchmark runner script to start the Kuzu benchmarks. Ensure Python 3 is installed and available in your PATH. ```bash python3 benchmark/lsqb/benchmark_runner.py ``` -------------------------------- ### Build and Install Kuzu from Source Source: https://github.com/kuzudb/kuzu/blob/master/scripts/pip-package/README.md Execute these commands to build the Kuzu package tarball and then install it using pip. Ensure you have the necessary build tools and dependencies installed. ```bash chmod +x package_tar.py ./package_tar.py pip install kuzu.tar.gz ``` -------------------------------- ### Install and Load KuzuDB Extensions Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates installing extensions from a local server and using pre-installed extensions like httpfs, fts, vector, and json. ```cypher -- Install from a local extension server (required for versions < 0.11.3 or non-bundled extensions) -- First start the server: docker run -d -p 8080:80 ghcr.io/kuzudb/extension-repo:latest INSTALL httpfs FROM 'http://localhost:8080/'; LOAD EXTENSION httpfs; -- Use an installed extension (e.g., query Parquet from S3) LOAD FROM 's3://my-bucket/data.parquet' RETURN *; -- Full-text search (pre-installed in v0.11.3+) CALL fts_create_index('Person', ['name', 'bio']); CALL query_fts_index('Person', 'Alice') RETURN node, score ORDER BY score DESC LIMIT 10; -- Vector index (pre-installed in v0.11.3+) CALL create_vector_index('Person', 'embedding', 'cosine'); CALL query_vector_index('Person', 'embedding', $query_vector, 10) YIELD node, distance RETURN node.name, distance ORDER BY distance; -- JSON extension usage (pre-installed in v0.11.3+) LOAD FROM 'data.json' RETURN json_extract(*, '$.name') AS name; -- DuckDB integration extension INSTALL duckdb FROM 'http://localhost:8080/'; LOAD EXTENSION duckdb; ATTACH 'mydb.duckdb' AS ddb (dbtype duckdb); MATCH (p:Person) RETURN p.name; ``` -------------------------------- ### Build and Install Brotli using CMake Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/README.md Builds and installs Brotli using CMake with a Release build type and a specified installation prefix. Ensure CMake is installed. ```bash mkdir out && cd out cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./installed .. cmake --build . --config Release --target install ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/kuzudb/kuzu/blob/master/tools/nodejs_api/README.md Install development dependencies for local development and contribution. ```bash npm install --include=dev ``` -------------------------------- ### Install Brotli using vcpkg Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/README.md Installs Brotli using the vcpkg dependency manager. Ensure vcpkg is bootstrapped and integrated with your system. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install brotli ``` -------------------------------- ### Install Man Page Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/CMakeLists.txt Installs the brotli man page if the BROTLI_BUILD_TOOLS option is enabled. ```cmake if (BROTLI_BUILD_TOOLS) install(FILES "docs/brotli.1" DESTINATION "${CMAKE_INSTALL_FULL_MANDIR}/man1") endif() ``` -------------------------------- ### Install Pkg-Config Files Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/CMakeLists.txt Installs the generated pkg-config files for brotli libraries to the appropriate system directory, provided BROTLI_BUNDLED_MODE is not enabled. ```cmake if(NOT BROTLI_BUNDLED_MODE) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libbrotlicommon.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libbrotlidec.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libbrotlienc.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif() # BROTLI_BUNDLED_MODE ``` -------------------------------- ### Install Kuzu Node.js Package Source: https://github.com/kuzudb/kuzu/blob/master/tools/nodejs_api/README.md Install the Kuzu Node.js package using npm. ```bash npm install kuzu ``` -------------------------------- ### Install Brotli Executable Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/CMakeLists.txt Installs the brotli executable to the runtime destination if BROTLI_BUILD_TOOLS is enabled and BROTLI_BUNDLED_MODE is not active. This makes the command-line tool available after installation. ```cmake if(NOT BROTLI_BUNDLED_MODE) if (BROTLI_BUILD_TOOLS) install( TARGETS brotli RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) endif() install( TARGETS ${BROTLI_LIBRARIES_CORE} ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) install( DIRECTORY ${BROTLI_INCLUDE_DIRS}/brotli DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) endif() # BROTLI_BUNDLED_MODE ``` -------------------------------- ### Install Kuzu Extension from Local Server Source: https://github.com/kuzudb/kuzu/blob/master/README.md This Cypher command installs a Kuzu extension from a locally hosted extension server. Ensure the server is running and accessible at the specified URL. ```cypher INSTALL FROM 'http://localhost:8080/'; ``` -------------------------------- ### Install Brotli Python Module (Tip-of-Tree) Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/README.md Installs the latest development version of the Brotli Python module directly from the GitHub repository using pip. This may install an unstable version. ```bash pip install --upgrade git+https://github.com/google/brotli ``` -------------------------------- ### Install kuzu-wasm with npm Source: https://github.com/kuzudb/kuzu/blob/master/tools/wasm/README.md Install the kuzu-wasm package using npm. This command is used for setting up the library in your project. ```bash npm i kuzu-wasm ``` -------------------------------- ### CMake Build Configuration for C++ Example Source: https://github.com/kuzudb/kuzu/blob/master/examples/cpp/CMakeLists.txt Configures the build for a C++ executable named 'example_cpp' using CMake. It links the Kuzu shared library and specifies include directories. Ensure 'single_file_header' is built before this target. ```cmake add_executable(example_cpp main.cpp) target_link_libraries(example_cpp kuzu_shared) target_include_directories(example_cpp PRIVATE ${CMAKE_BINARY_DIR}/src) add_dependencies(example_cpp single_file_header) ``` -------------------------------- ### Add Unity Catalog Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/unity_catalog/src/installer/CMakeLists.txt Configures the shared library for the Unity Catalog installer on non-Windows systems. It specifies the source files, including the main C++ file and the DuckDB installer source. ```cmake if (NOT WIN32) add_library(unity_catalog_installer SHARED unity_catalog_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(unity_catalog_installer unity_catalog_installer unity_catalog) endif () ``` -------------------------------- ### Install Brotli Python Module (Latest Release) Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/README.md Installs the latest stable release of the Brotli Python module using pip. Ensure pip is installed and up to date. ```bash pip install brotli ``` -------------------------------- ### Add Postgres Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/postgres/src/installer/CMakeLists.txt Adds the 'postgres_installer' shared library, including source files, when not on a Windows system. Sets extension properties for the 'postgres' extension. ```cmake if (NOT WIN32) add_library(postgres_installer SHARED postgres_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(postgres_installer postgres_installer postgres) endif () ``` -------------------------------- ### Configure Delta Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/delta/src/installer/CMakeLists.txt Defines the shared library for the delta installer on non-Windows systems, specifying source files and extension properties. ```cmake if (NOT WIN32) add_library(delta_installer SHARED delta_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(delta_installer delta_installer delta) endif () ``` -------------------------------- ### Configure SQLite Installer for Non-Windows Source: https://github.com/kuzudb/kuzu/blob/master/extension/sqlite/src/installer/CMakeLists.txt Defines the shared library for the SQLite installer and sets its properties when not on a Windows system. This includes source files and extension metadata. ```cmake if (NOT WIN32) add_library(sqlite_installer SHARED sqlite_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(sqlite_installer sqlite_installer sqlite) endif () ``` -------------------------------- ### Set Apple Dynamic Lookup for Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/unity_catalog/src/installer/CMakeLists.txt Enables dynamic lookup for the Unity Catalog installer library on Apple systems. This is necessary for proper loading and execution of the extension on macOS. ```cmake if (APPLE) set_apple_dynamic_lookup(unity_catalog_installer) endif () ``` -------------------------------- ### Configure Iceberg Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/iceberg/src/installer/CMakeLists.txt Defines the shared library for the Iceberg installer on non-Windows systems. It includes source files and sets extension properties. ```cmake if (NOT WIN32) add_library(iceberg_installer SHARED iceberg_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(iceberg_installer iceberg_installer iceberg) endif () ``` -------------------------------- ### Setup Coverage Target Source: https://github.com/kuzudb/kuzu/blob/master/third_party/brotli/CMakeLists.txt Configures a CMake target for code coverage analysis if the ENABLE_COVERAGE option is set to 'yes'. ```cmake if (ENABLE_COVERAGE STREQUAL "yes") setup_target_for_coverage(coverage test coverage) endif() ``` -------------------------------- ### Add Azure Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/azure/src/installer/CMakeLists.txt Conditionally adds the azure_installer library for shared builds on non-Windows systems. This includes specifying source files and setting extension properties. ```cmake if (NOT WIN32) add_library(azure_installer SHARED azure_install_func.cpp ${PROJECT_SOURCE_DIR}/extension/duckdb/src/installer/duckdb_installer.cpp) set_extension_properties(azure_installer azure_installer azure) endif () ``` -------------------------------- ### Register and Use Python User-Defined Functions (UDFs) Source: https://context7.com/kuzudb/kuzu/llms.txt Shows how to register Python callables as Kuzu scalar functions, making them usable within Cypher queries. Input and return types must be specified. Includes an example with exception handling for safe division. ```python import kuzu from kuzu import Type db = kuzu.Database(":memory:") conn = kuzu.Connection(db) # Register a Python function that trims and lowercases a string def normalize(s: str) -> str: return s.strip().lower() conn.create_function( "normalize", normalize, params_type=[Type.STRING], return_type=Type.STRING ) # Register a function with exception handling def safe_divide(a: float, b: float) -> float: return a / b # will return null if b == 0 due to catch_exceptions=True conn.create_function( "safe_divide", safe_divide, params_type=[Type.DOUBLE, Type.DOUBLE], return_type=Type.DOUBLE, catch_exceptions=True ) conn.execute("CREATE NODE TABLE Item(tag STRING, val DOUBLE, PRIMARY KEY(tag));") conn.execute("CREATE (:Item {tag: ' Hello ', val: 10.0});") conn.execute("CREATE (:Item {tag: ' World ', val: 0.0});") result = conn.execute("MATCH (i:Item) RETURN normalize(i.tag), safe_divide(100.0, i.val);") print(result.get_as_df()) # Output: # normalize(i.tag) safe_divide(100.0, i.val) # 0 hello 10.0 # 1 world NaN conn.remove_function("normalize") conn.remove_function("safe_divide") ``` -------------------------------- ### Configure Apple Dynamic Lookup Source: https://github.com/kuzudb/kuzu/blob/master/extension/delta/src/installer/CMakeLists.txt Enables dynamic lookup for the delta installer library on Apple platforms. ```cmake if (APPLE) set_apple_dynamic_lookup(delta_installer) endif () ``` -------------------------------- ### Enable Apple Dynamic Lookup for SQLite Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/sqlite/src/installer/CMakeLists.txt Enables dynamic lookup for the SQLite installer library on Apple systems. This is necessary for proper loading of dynamic libraries on macOS and iOS. ```cmake if (APPLE) set_apple_dynamic_lookup(sqlite_installer) endif () ``` -------------------------------- ### Set Apple Dynamic Lookup for Azure Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/azure/src/installer/CMakeLists.txt Enables dynamic lookup for the azure_installer library on Apple systems. This is typically required for extensions on macOS. ```cmake if (APPLE) set_apple_dynamic_lookup(azure_installer) endif () ``` -------------------------------- ### Set Apple Dynamic Lookup for Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/postgres/src/installer/CMakeLists.txt Enables dynamic lookup for the 'postgres_installer' library on Apple systems. This is typically used to resolve symbols at runtime. ```cmake if (APPLE) set_apple_dynamic_lookup(postgres_installer) endif () ``` -------------------------------- ### Parameterized Queries with Prepared Statements - Node.js Source: https://context7.com/kuzudb/kuzu/llms.txt Shows how to use prepared statements for parameterized queries in Node.js. Prepared statements are compiled once and can be executed multiple times with different parameter values, improving performance and security. Includes an example of a progress callback during query execution. ```javascript const kuzu = require("kuzu"); async function main() { const db = new kuzu.Database(":memory:"); const conn = new kuzu.Connection(db); await conn.query("CREATE NODE TABLE Product(id INT64, name STRING, price DOUBLE, PRIMARY KEY(id));"); // Prepare once const stmt = await conn.prepare( "CREATE (:Product {id: $id, name: $name, price: $price});" ); if (!stmt.isSuccess()) { throw new Error(stmt.getErrorMessage()); } // Execute with different parameters const products = [ { id: 1, name: "Gadget", price: 9.99 }, { id: 2, name: "Widget", price: 4.49 }, { id: 3, name: "Doohickey", price: 14.99 }, ]; for (const p of products) { await conn.execute(stmt, p); } // Query with progress callback const queryResult = await conn.query( "MATCH (p:Product) RETURN p.name, p.price ORDER BY p.price;", (progress, finished, total) => { console.log(`Progress: ${finished}/${total} pipelines`); } ); const rows = await queryResult.getAll(); console.log(rows); // Output: // [ { 'p.name': 'Widget', 'p.price': 4.49 }, // { 'p.name': 'Gadget', 'p.price': 9.99 }, // { 'p.name': 'Doohickey', 'p.price': 14.99 } ] await queryResult.close(); await conn.close(); await db.close(); } main().catch(console.error); ``` -------------------------------- ### Set Apple Dynamic Lookup for Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/duckdb/src/installer/CMakeLists.txt Configures dynamic lookup behavior for the DuckDB installer library on Apple systems. This ensures proper loading of dynamic symbols. ```cmake if (APPLE) set_apple_dynamic_lookup(duckdb_installer) endif () ``` -------------------------------- ### Add KuzuDB Subdirectory with CMake Source: https://github.com/kuzudb/kuzu/blob/master/examples/README.md Include this line in your CMakeLists.txt to integrate KuzuDB examples into your project. This is useful for development and testing. ```cmake add_subdirectory(examples/cpp) ``` -------------------------------- ### Initialize Database and Connection - Node.js Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates creating an in-memory database with a specified buffer pool size and establishing a connection with a set number of threads. Includes schema creation, data insertion, and querying with async result iteration. ```javascript const kuzu = require("kuzu"); async function main() { // Create an in-memory database with a 512MB buffer pool const db = new kuzu.Database(":memory:", 512 * 1024 * 1024); const conn = new kuzu.Connection(db, 4 /* numThreads */); // Create schema await conn.query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));"); await conn.query("CREATE REL TABLE Follows(FROM Person TO Person, since INT64);"); // Insert data await conn.query("CREATE (:Person {name: 'Alice', age: 25});"); await conn.query("CREATE (:Person {name: 'Bob', age: 30});"); await conn.query( "MATCH (a:Person {name:'Alice'}),(b:Person {name:'Bob'}) " + "CREATE (a)-[:Follows {since: 2021}]->(b);" ); // Query with async result iteration const result = await conn.query( "MATCH (a:Person)-[f:Follows]->(b:Person) RETURN a.name, f.since, b.name;" ); const rows = await result.getAll(); console.log(rows); // Output: [ { 'a.name': 'Alice', 'f.since': 2021, 'b.name': 'Bob' } ] console.log("Kuzu version:", kuzu.Database.getVersion()); await result.close(); await conn.close(); await db.close(); } main().catch(console.error); ``` -------------------------------- ### Node.js Kuzu WASM API Usage Source: https://context7.com/kuzudb/kuzu/llms.txt Example of using the Kuzu WebAssembly API in a Node.js environment for database operations, including schema setup, data insertion, and querying. ```javascript // Node.js usage with kuzu-wasm const kuzu = require("kuzu-wasm/nodejs"); async function main() { // In-memory database with 1GB buffer pool, 4 threads const db = new kuzu.Database(":memory:", 1 << 30); const conn = new kuzu.Connection(db, 4); // Schema setup const schemaLines = [ "CREATE NODE TABLE User(name STRING, age INT64, PRIMARY KEY(name));", "CREATE NODE TABLE City(name STRING, country STRING, PRIMARY KEY(name));", "CREATE REL TABLE LivesIn(FROM User TO City);" ]; for (const line of schemaLines) { const qr = await conn.query(line); await qr.close(); } // Insert data await (await conn.query("CREATE (:User {name: 'Alice', age: 25});")).close(); await (await conn.query("CREATE (:User {name: 'Bob', age: 30});")).close(); await (await conn.query("CREATE (:City {name: 'Waterloo', country: 'Canada'});")).close(); await (await conn.query( "MATCH (u:User {name:'Alice'}),(c:City {name:'Waterloo'}) CREATE (u)-[:LivesIn]->(c);" )).close(); // Query const result = await conn.query( "MATCH (u:User)-[:LivesIn]->(c:City) RETURN u.name, u.age, c.name, c.country;" ); // getAllObjects returns rows as plain JS objects keyed by column name const rows = await result.getAllObjects(); console.log(rows); // Output: // [ { 'u.name': 'Alice', 'u.age': 25, 'c.name': 'Waterloo', 'c.country': 'Canada' } ] await result.close(); await conn.close(); await db.close(); await kuzu.close(); } main().catch(console.error); ``` -------------------------------- ### Initialize and Query Database with C API Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates opening a database, establishing a connection, creating tables and data, and querying results using the C API. Manual memory management is required for all created objects. ```c #include #include #include "kuzu.h" int main() { kuzu_database db; kuzu_connection conn; // Open database and connection kuzu_database_init("/tmp/demodb", kuzu_default_system_config(), &db); kuzu_connection_init(&db, &conn); // Create schema and data kuzu_query_result result; kuzu_connection_query(&conn, "CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE (:Person {name: 'Alice', age: 25});", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE (:Person {name: 'Bob', age: 30});", &result); kuzu_query_result_destroy(&result); // Query and walk results kuzu_connection_query(&conn, "MATCH (p:Person) RETURN p.name AS name, p.age AS age;", &result); kuzu_flat_tuple tuple; kuzu_value value; while (kuzu_query_result_has_next(&result)) { kuzu_query_result_get_next(&result, &tuple); kuzu_flat_tuple_get_value(&tuple, 0, &value); char* name; kuzu_value_get_string(&value, &name); kuzu_flat_tuple_get_value(&tuple, 1, &value); int64_t age; kuzu_value_get_int64(&value, &age); printf("name=%s, age=% ``` -------------------------------- ### Database and Connection Initialization Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates how to create an in-memory database, establish a connection with a specified buffer pool size and number of threads, and execute DDL and DML statements. ```APIDOC ## Database and Connection ### Description Initializes an in-memory Kuzu database with a specified buffer pool size and establishes a connection with a given number of threads. This section shows how to create tables, insert data, and perform queries. ### Usage ```javascript const kuzu = require("kuzu"); async function main() { // Create an in-memory database with a 512MB buffer pool const db = new kuzu.Database(":memory:", 512 * 1024 * 1024); const conn = new kuzu.Connection(db, 4 /* numThreads */); // Create schema await conn.query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));"); await conn.query("CREATE REL TABLE Follows(FROM Person TO Person, since INT64);"); // Insert data await conn.query("CREATE (:Person {name: 'Alice', age: 25});"); await conn.query("CREATE (:Person {name: 'Bob', age: 30});"); await conn.query( "MATCH (a:Person {name:'Alice'}),(b:Person {name:'Bob'}) " + "CREATE (a)-[:Follows {since: 2021}]->(b);" ); // Query with async result iteration const result = await conn.query( "MATCH (a:Person)-[f:Follows]->(b:Person) RETURN a.name, f.since, b.name;" ); const rows = await result.getAll(); console.log(rows); // Output: [ { 'a.name': 'Alice', 'f.since': 2021, 'b.name': 'Bob' } ] console.log("Kuzu version:", kuzu.Database.getVersion()); await result.close(); await conn.close(); await db.close(); } main().catch(console.error); ``` ### Methods - `new kuzu.Database(path: string, bufferPoolSize: number)`: Constructor for creating a new database instance. - `new kuzu.Connection(db: Database, numThreads: number)`: Constructor for creating a new connection instance. - `conn.query(query: string)`: Executes a given query string asynchronously. - `result.getAll()`: Retrieves all rows from the query result asynchronously. - `result.close()`: Closes the query result. - `conn.close()`: Closes the database connection. - `db.close()`: Closes the database. - `kuzu.Database.getVersion()`: Returns the Kuzu database version. ``` -------------------------------- ### Create or Open Kuzu Database in C++ Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates creating an on-disk database with default settings or an in-memory database with custom system configurations like buffer pool size, thread count, and compression. ```cpp #include "kuzu.hpp" using namespace kuzu::main; int main() { // On-disk database with default system config auto database = std::make_unique("/path/to/mydb"); // In-memory database with custom config: 2GB buffer pool, 4 threads, compression on SystemConfig config( /*bufferPoolSize=*/ 2ULL * 1024 * 1024 * 1024, /*maxNumThreads=*/ 4, /*enableCompression=*/ true, /*readOnly=*/ false ); auto memDb = std::make_unique(":memory:", config); } ``` -------------------------------- ### Add DuckDB Installer Library (Non-Windows) Source: https://github.com/kuzudb/kuzu/blob/master/extension/duckdb/src/installer/CMakeLists.txt Adds the DuckDB installer as a shared library on non-Windows systems. This is typically used for building the installer component of DuckDB. ```cmake if (NOT WIN32) add_library(duckdb_installer SHARED duckdb_installer.cpp duckdb_install_func.cpp) set_extension_properties(duckdb_installer duckdb_installer duckdb) endif () ``` -------------------------------- ### kuzu_database_init / kuzu_connection_init / kuzu_connection_query (C Interface) Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates the initialization of a Kuzu database and connection, followed by schema creation, data insertion, and querying using the C API. Memory management is manual, requiring explicit destruction of created objects. ```APIDOC ## kuzu_database_init / kuzu_connection_init / kuzu_connection_query (C Interface) ### Description This section details the C API for interacting with KuzuDB, including database and connection initialization, schema creation, data insertion, and querying. It emphasizes manual memory management where objects must be explicitly destroyed. ### Functions - `kuzu_database_init(const char* path, kuzu_system_config config, kuzu_database* out_db)`: Initializes a Kuzu database at the specified path. - `kuzu_connection_init(kuzu_database* db, kuzu_connection* out_conn)`: Initializes a connection to the given Kuzu database. - `kuzu_connection_query(kuzu_connection* conn, const char* query, kuzu_query_result* out_result)`: Executes a Cypher query and returns the results. - `kuzu_query_result_destroy(kuzu_query_result* result)`: Destroys a query result object. - `kuzu_flat_tuple_get_value(kuzu_flat_tuple* tuple, uint64_t index, kuzu_value* out_value)`: Retrieves a value from a flat tuple at a given index. - `kuzu_value_get_string(kuzu_value* value, char** out_string)`: Retrieves a string value. - `kuzu_value_get_int64(kuzu_value* value, int64_t* out_int64)`: Retrieves an int64 value. - `kuzu_destroy_string(char* str)`: Destroys a string allocated by Kuzu. - `kuzu_flat_tuple_destroy(kuzu_flat_tuple* tuple)`: Destroys a flat tuple. - `kuzu_connection_destroy(kuzu_connection* conn)`: Destroys a connection object. - `kuzu_database_destroy(kuzu_database* db)`: Destroys a database object. ### Example ```c #include #include #include "kuzu.h" int main() { kuzu_database db; kuzu_connection conn; // Open database and connection kuzu_database_init("/tmp/demodb", kuzu_default_system_config(), &db); kuzu_connection_init(&db, &conn); // Create schema and data kuzu_query_result result; kuzu_connection_query(&conn, "CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE (:Person {name: 'Alice', age: 25});", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE (:Person {name: 'Bob', age: 30});", &result); kuzu_query_result_destroy(&result); // Query and walk results kuzu_connection_query(&conn, "MATCH (p:Person) RETURN p.name AS name, p.age AS age;", &result); kuzu_flat_tuple tuple; kuzu_value value; while (kuzu_query_result_has_next(&result)) { kuzu_query_result_get_next(&result, &tuple); kuzu_flat_tuple_get_value(&tuple, 0, &value); char* name; kuzu_value_get_string(&value, &name); kuzu_flat_tuple_get_value(&tuple, 1, &value); int64_t age; kuzu_value_get_int64(&value, &age); printf("name=%s, age=%%" PRIi64 "\n", name, age); kuzu_destroy_string(name); } kuzu_value_destroy(&value); kuzu_flat_tuple_destroy(&tuple); kuzu_query_result_destroy(&result); kuzu_connection_destroy(&conn); kuzu_database_destroy(&db); return 0; } ``` ``` -------------------------------- ### Parameterized Queries with Prepare and Execute Source: https://context7.com/kuzudb/kuzu/llms.txt Explains how to use prepared statements for executing parameterized queries efficiently, mapping parameter names to values using plain objects. ```APIDOC ## Connection.prepare and Connection.execute — Parameterized queries (Node.js) ### Description This section details the usage of `prepare` and `execute` methods for running parameterized queries in Node.js. Prepared statements allow for efficient execution of queries with varying parameters by compiling the query once and executing it multiple times with different values. ### Usage ```javascript const kuzu = require("kuzu"); async function main() { const db = new kuzu.Database(":memory:"); const conn = new kuzu.Connection(db); await conn.query("CREATE NODE TABLE Product(id INT64, name STRING, price DOUBLE, PRIMARY KEY(id));"); // Prepare once const stmt = await conn.prepare( "CREATE (:Product {id: $id, name: $name, price: $price});" ); if (!stmt.isSuccess()) { throw new Error(stmt.getErrorMessage()); } // Execute with different parameters const products = [ { id: 1, name: "Gadget", price: 9.99 }, { id: 2, name: "Widget", price: 4.49 }, { id: 3, name: "Doohickey", price: 14.99 }, ]; for (const p of products) { await conn.execute(stmt, p); } // Query with progress callback const queryResult = await conn.query( "MATCH (p:Product) RETURN p.name, p.price ORDER BY p.price;", (progress, finished, total) => { console.log(`Progress: ${finished}/${total} pipelines`); } ); const rows = await queryResult.getAll(); console.log(rows); // Output: // [ { 'p.name': 'Widget', 'p.price': 4.49 }, // { 'p.name': 'Gadget', 'p.price': 9.99 }, // { 'p.name': 'Doohickey', 'p.price': 14.99 } ] await queryResult.close(); await conn.close(); await db.close(); } main().catch(console.error); ``` ### Methods - `conn.prepare(query: string)`: Prepares a query string for execution, returning a statement object. - `stmt.isSuccess()`: Checks if the prepared statement was successfully created. - `stmt.getErrorMessage()`: Returns the error message if the statement preparation failed. - `conn.execute(statement: Statement, parameters: object)`: Executes a prepared statement with the provided parameters. - `conn.query(query: string, progressCallback?: function)`: Executes a query string and optionally accepts a progress callback function. ``` -------------------------------- ### Initialize KuzuDB and Execute Queries in Rust Source: https://context7.com/kuzudb/kuzu/llms.txt Demonstrates setting up a Kuzu database with custom configurations and executing DDL and DML statements. Results can be iterated as Vec rows. ```rust use kuzu::{Connection, Database, SystemConfig, Value}; use anyhow::Result; fn main() -> Result<()> { let temp_dir = tempfile::tempdir()?; // Build a SystemConfig using the builder pattern let config = SystemConfig::default() .buffer_pool_size(1 << 30) // 1GB buffer pool .max_num_threads(4) .enable_compression(true) .auto_checkpoint(true) .checkpoint_threshold(16 * 1024 * 1024); // 16MB WAL threshold let db = Database::new(temp_dir.path().join("demodb"), config)?; let conn = Connection::new(&db)?; // Create schema and data conn.query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));")?; conn.query("CREATE REL TABLE Knows(FROM Person TO Person, weight FLOAT);")?; conn.query("CREATE (:Person {name: 'Alice', age: 25});")?; conn.query("CREATE (:Person {name: 'Bob', age: 30});")?; conn.query("MATCH (a:Person {name:'Alice'}),(b:Person {name:'Bob'}) CREATE (a)-[:Knows {weight: 0.9}]->(b);")?; // Iterate results for row in conn.query("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age;")? { if let (Value::String(name), Value::Int64(age)) = (&row[0], &row[1]) { println!("{}: {}", name, age); } } // Output: // Alice: 25 // Bob: 30 temp_dir.close()?; Ok(()) } ``` -------------------------------- ### Configure Benchmark Executable Source: https://github.com/kuzudb/kuzu/blob/master/tools/benchmark/CMakeLists.txt Defines include directories, builds the benchmark executable, and links necessary libraries for the Kuzu benchmark. ```cmake include_directories( ./include ${PROJECT_SOURCE_DIR}/test/include/test_helper) add_executable(kuzu_benchmark benchmark.cpp benchmark_parser.cpp benchmark_runner.cpp main.cpp) target_link_libraries(kuzu_benchmark kuzu test_helper) ``` -------------------------------- ### Initialize and Populate Kuzu DB in Browser Source: https://github.com/kuzudb/kuzu/blob/master/tools/wasm/examples/browser_persistent/public/index.html This code runs on the first detection of a new session. It writes CSV data to the virtual filesystem, mounts IDBFS for persistence, creates and populates the Kuzu database, and then syncs the filesystem. ```javascript import kuzu from './index.js'; window.kuzu = kuzu; const appendOutput = (text) => { const output = document.getElementById("output"); output.innerText += text + "\n"; }; (async () => { const isFirstRun = window.localStorage.getItem("isFirstRun") !== "false"; if (isFirstRun) { appendOutput("First run detected. Setting up the database..."); // Write the data into WASM filesystem const userCSV = `Adam,30 Karissa,40 Zhang,50 Noura,25`; const cityCSV = `Waterloo,150000 Kitchener,200000 Guelph,75000`; const followsCSV = `Adam,Karissa,2020 Adam,Zhang,2020 Karissa,Zhang,2021 Zhang,Noura,2022`; const livesInCSV = `Adam,Waterloo Karissa,Waterloo Zhang,Kitchener Noura,Guelph`; await kuzu.FS.writeFile("/user.csv", userCSV); await kuzu.FS.writeFile("/city.csv", cityCSV); await kuzu.FS.writeFile("/follows.csv", followsCSV); await kuzu.FS.writeFile("/lives-in.csv", livesInCSV); // Make a persistent IDBFS directory await kuzu.FS.mkdir("/database"); await kuzu.FS.mountIdbfs("/database"); appendOutput("IDBFS mounted."); // Create an empty database and connect to it const db = new kuzu.Database("/database"); const conn = new kuzu.Connection(db); const queries = [ // Create the tables "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 Follows(FROM User TO User, since INT64)", "CREATE REL TABLE LivesIn(FROM User TO City)", // Load the data "COPY User FROM 'user.csv'", "COPY City FROM 'city.csv'", "COPY Follows FROM 'follows.csv'", "COPY LivesIn FROM 'lives-in.csv'", ]; appendOutput("Setting up the database..."); // Execute the queries to setup the database for (const query of queries) { appendOutput("Executing query: " + query); const queryResult = await conn.query(query); const outputString = await queryResult.toString(); appendOutput(outputString); await queryResult.close(); } appendOutput("Database setup complete."); // Close the connection await conn.close(); appendOutput("Connection closed."); // Close the database await db.close(); appendOutput("Database closed."); // Sync the filesystem await kuzu.FS.syncfs(false); appendOutput("Database persisted to IDBFS."); await kuzu.FS.unmount("/database"); appendOutput("IDBFS unmounted."); window.localStorage.setItem("isFirstRun", "false"); } else { appendOutput("Second or later run detected. Querying the database..."); // Make a persistent IDBFS directory await kuzu.FS.mkdir("/database"); await kuzu.FS.mountIdbfs("/database"); appendOutput("IDBFS mounted."); // Sync the filesystem await kuzu.FS.syncfs(true); appendOutput("Database loaded from IDBFS."); // Create a new database and connect to it const db = new kuzu.Database("/database"); const conn = new kuzu.Connection(db); // Query the database let queryString = "MATCH (u:User) -[f:Follows]-> (v:User) RETURN u.name, f.since, v.name"; appendOutput("Executing query: " + queryString); let queryResult = await conn.query(queryString); let rows = await queryResult.getAllObjects(); appendOutput("Query result:"); for (const row of rows) { appendOutput(`User ${row['u.name']} follows ${row['v.name']} since ${row['f.since']}`); } await queryResult.close(); appendOutput(""); queryString = "MATCH (u:User) -[l:LivesIn]-> (c:City) RETURN u.name, c.name"; appendOutput("Executing query: " + queryString); queryResult = await conn.query(queryString); rows = await queryResult.getAllObjects(); appendOutput("Query result:"); // Print the rows for (const row of rows) { appendOutput(`User ${row['u.name']} lives in ${row['c.name']}`); } await queryResult.close(); appendOutput(""); appendOutput("All queries executed successfully."); // Close the connection await conn.close(); appendOutput("Connection closed."); // Close the database await db.close(); appendOutput("Database closed."); // Unmount the IDBFS await kuzu.FS.unmount("/database"); appendOutput("IDBFS unmounted."); } })(); ``` -------------------------------- ### Set Apple Dynamic Lookup for Iceberg Installer Source: https://github.com/kuzudb/kuzu/blob/master/extension/iceberg/src/installer/CMakeLists.txt Enables dynamic lookup for the Iceberg installer library on Apple systems, which is necessary for certain linking behaviors. ```cmake if (APPLE) set_apple_dynamic_lookup(iceberg_installer) endif () ``` -------------------------------- ### Build Project Source: https://github.com/kuzudb/kuzu/blob/master/tools/nodejs_api/README.md Build the Kuzu Node.js project. ```bash npm run build ``` -------------------------------- ### Parameterized Queries with Kuzu in C++ Source: https://context7.com/kuzudb/kuzu/llms.txt Illustrates using `prepare` and `execute` for parameterized Cypher queries, which improves performance by avoiding repeated query planning for identical query structures with varying parameters. ```cpp #include "kuzu.hpp" using namespace kuzu::main; using namespace kuzu::common; int main() { auto db = std::make_unique("/tmp/demo"); auto conn = std::make_unique(db.get()); conn->query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));"); // Prepare once, execute many times auto stmt = conn->prepare("CREATE (:Person {name: $name, age: $age});"); if (!stmt->isSuccess()) { std::cerr << stmt->getErrorMessage() << std::endl; return 1; } // Execute with typed parameters conn->execute(stmt.get(), std::make_pair("name", Value("Charlie")), std::make_pair("age", Value((int64_t)22))); conn->execute(stmt.get(), std::make_pair("name", Value("Diana")), std::make_pair("age", Value((int64_t)28))); auto result = conn->query("MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age;"); std::cout << result->toString(); // Output: // p.name|p.age // Charlie|22 // Diana|28 } ``` -------------------------------- ### Package Prebuilt Binaries Source: https://github.com/kuzudb/kuzu/blob/master/tools/nodejs_api/README.md Package prebuilt binaries for distribution. Binaries should be placed in the 'prebuilt' directory with the naming convention kuzujs-${platform}-${arch}.node. ```bash node package ``` -------------------------------- ### Database Class - Create or Open a Database Source: https://context7.com/kuzudb/kuzu/llms.txt The `Database` class is the main entry point for the C++ API. It allows you to create or open a Kuzu database, either on-disk or in-memory, with configurable system settings. ```APIDOC ## Database ### Description The `Database` class is the primary entry point for the C++ API. It accepts a path (or `:memory:` for in-memory) along with a `SystemConfig` that controls buffer pool size, thread count, compression, read-only mode, WAL checkpointing, and checksums. ### Method `std::make_unique(path, config)` ### Parameters #### Path - **path** (string) - Required - The file path for the database or `:memory:` for an in-memory database. - **config** (SystemConfig) - Optional - Configuration settings for the database. ### SystemConfig Parameters - **bufferPoolSize** (uint64_t) - Optional - Size of the buffer pool. - **maxNumThreads** (uint64_t) - Optional - Maximum number of threads to use. - **enableCompression** (bool) - Optional - Whether to enable compression. - **readOnly** (bool) - Optional - Whether to open the database in read-only mode. ### Request Example ```cpp #include "kuzu.hpp" using namespace kuzu::main; int main() { // On-disk database with default system config auto database = std::make_unique("/path/to/mydb"); // In-memory database with custom config: 2GB buffer pool, 4 threads, compression on SystemConfig config( /*bufferPoolSize=*/ 2ULL * 1024 * 1024 * 1024, /*maxNumThreads=*/ 4, /*enableCompression=*/ true, /*readOnly=*/ false ); auto memDb = std::make_unique(":memory:", config); } ``` ```