### Swift: Project Setup and Kuzu Interaction Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Guides through initializing a Swift project, adding the Kuzu client dependency, and performing schema creation, data loading, and querying. ```bash mkdir kuzu-swift-example cd kuzu-swift-example swift package init --type=executable ``` ```swift import Kuzu // Create an empty on-disk database and connect to it let db = try! Database("example.kuzu") let conn = try! Connection(db) // Create schema and load data let queries = [ "CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", "CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", "CREATE REL TABLE Follows(FROM User TO User, since INT64)", "CREATE REL TABLE LivesIn(FROM User TO City)", "COPY User FROM 'data/user.csv'", "COPY City FROM 'data/city.csv'", "COPY Follows FROM 'data/follows.csv'", "COPY LivesIn FROM 'data/lives-in.csv'", ] for query in queries { _ = try! conn.query(query) } // Execute Cypher query let res = try! conn.query("MATCH (a:User)-[e:Follows]->(b:User) RETURN a.name, e.since, b.name") for tuple in res { let dict = try! tuple.getAsDictionary() print(dict) } ``` ```bash swift build -c release ``` ```bash cp ./.build/arm64-apple-macosx/release/kuzu-swift-example . ``` ```bash ./kuzu-swift-example ``` -------------------------------- ### Install Kuzu Go Module Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Go module using 'go get'. This command fetches and installs the specified version of the Go module. ```bash go get github.com/kuzudb/go-kuzu@v${version} ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/kuzudb/docs/blob/main/README.md Installs all necessary dependencies for the project. Run this command in the project's root directory. ```bash npm install ``` -------------------------------- ### Download and Unzip Iceberg Example Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/iceberg.md This command downloads and unzips a sample dataset for testing the Iceberg extension. Ensure you have `wget` and `unzip` installed. ```shell cd /tmp wget https://kuzudb.github.io/data/iceberg-extension/iceberg_tables.zip unzip iceberg_tables.zip ``` -------------------------------- ### Install an Extension from a Local Server Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/index.mdx Install an extension from a local extension server. This command only needs to be run once per extension. ```cypher INSTALL FROM 'http://localhost:8080/'; ``` -------------------------------- ### Install deltalake and pandas Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/delta.md Install the necessary Python libraries for creating Delta tables. ```shell pip install deltalake pandas ``` -------------------------------- ### Start Local Server and Build Site Source: https://github.com/kuzudb/docs/blob/main/README.md Starts a local server and simultaneously builds the production site. This command is useful for testing the final build locally before deployment. ```bash npm start ``` -------------------------------- ### Compile and Run C Example (Linux/macOS/Windows) Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Instructions for compiling and running the C Kuzu API example on different operating systems, including setting linker paths. ```bash # On Linux: env LIBRARY_PATH=. LD_LIBRARY_PATH=. gcc main.c -lkuzu env LIBRARY_PATH=. LD_LIBRARY_PATH=. ./a.out # On macOS: env DYLD_LIBRARY_PATH=. LIBRARY_PATH=. clang main.c -lkuzu env DYLD_LIBRARY_PATH=. LIBRARY_PATH=. ./a.out # On Windows: cl main.c kuzu_shared.lib ./main.exe ``` -------------------------------- ### Install asyncpg Library Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/postgres.mdx Installs the asyncpg library, an asynchronous PostgreSQL client for Python, used for creating and populating a sample PostgreSQL database. ```bash pip install asyncpg ``` -------------------------------- ### Start Local Development Server Source: https://github.com/kuzudb/docs/blob/main/README.md Starts a local development server, typically at localhost:4321, for real-time previewing of changes. This command is essential for active development. ```bash npm run dev ``` -------------------------------- ### Run PostgreSQL Server with Docker Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/postgres.mdx Starts a local PostgreSQL server using Docker for development purposes. Note that this setup is not persistent and uses plain text passwords, making it unsuitable for production. ```sh docker run --rm --name kuzu-postgres \ -e POSTGRES_PASSWORD=testpassword \ -p 5432:5432 \ postgres:latest ``` -------------------------------- ### Install Kuzu Go API Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Go API, which wraps Kuzu's C API. Ensure your Go project has a go.mod file initialized. ```bash go get github.com/kuzudb/kuzu-go ``` -------------------------------- ### Set Up Unity Catalog Server Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/unity.md Clone the Unity Catalog repository and start the UC server. This is a prerequisite for attaching to a Unity Catalog. ```bash git clone https://github.com/unitycatalog/unitycatalog.git bin/start-uc-server ``` -------------------------------- ### Install Kuzu Python Client with uv Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Python client library using the 'uv' package manager. This command initializes uv and adds the kuzu package. ```bash uv init uv add kuzu ``` -------------------------------- ### Install Dependencies on Windows Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs Python 3, Make, and Ninja build system using Chocolatey on Windows. ```powershell choco install -y python3 make ninja ``` -------------------------------- ### Install yFiles Jupyter Graphs with uv Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/visualization/third-party-integrations/yfiles.mdx Installs the kuzu and yfiles-jupyter-graphs-for-kuzu packages using uv. Ensure kuzu is installed as a prerequisite. ```bash uv init uv add kuzu yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### Install Build Tools on Ubuntu Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs essential build tools including CMake, GCC, and Python on Ubuntu systems. ```bash apt update apt install -y build-essential cmake gcc g++ python3 ``` -------------------------------- ### Install Kuzu Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/python/index.mdx Install the Kuzu Python package using pip within a virtual environment. ```bash python -m venv .venv source .venv/bin/activate pip install kuzu ``` -------------------------------- ### Start On-Disk Database CLI Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/cli.mdx Opens an on-disk Kuzu database in read-write mode. If the directory does not exist, it will be created. ```bash $ kuzu example.kuzu ``` ```text Opened the database example.kuzu in read-write mode. Enter ":help" for usage hints. kuzu> ``` -------------------------------- ### Install Build Tools on AlmaLinux Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs necessary build tools such as CMake, GCC, and Python on AlmaLinux systems. ```bash dnf update dnf install -y cmake gcc gcc-c++ python3 ``` -------------------------------- ### KuzuDB Test File Example with Comments and Blocks Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/testing-framework.md An example of a KuzuDB test file demonstrating various features including buffer pool size, dataset loading, defining statement blocks, logging, and handling expected errors. ```kuzu # Header # We can add -SKIP here if we need to temporarily skip the whole file -BUFFER_POOL_SIZE 64000000 -CHECKPOINT_WAIT_TIMEOUT 10000 -DATASET PARQUET CSV_TO_PARQUET(tinysnb) -- -DEFINE_STATEMENT_BLOCK create_rel_set [ -STATEMENT MATCH (a:person), (b:person) WHERE a.ID=10 AND b.ID=20 CREATE (a)-[e:knows]->(b); ---- ok -STATEMENT MATCH (a:person), (b:person) WHERE a.ID=1 AND b.ID=2 CREATE (a)-[e:knows]->(b); ---- ok ] -CASE TestRelationSet -LOG Current Relation Test -STATEMENT MATCH (a:person)-[e:knows]->(b:person) RETURN COUNT(*); ---- 1 2 # This is also part of TestRelationSet test case -LOG Create Relation Set -INSERT_STATEMENT_BLOCK create_rel_set -STATEMENT MATCH (a:person)-[e:knows]->(b:person) RETURN COUNT(*); ---- 1 4 # This is also part of TestRelationSet test case -LOG Test Duplicated Primary Key -STATEMENT MATCH (a:person), (b:person) WHERE a.ID=1 AND b.ID=20 CREATE (a)-[e:knows]->(b); ---- error "Exception: Duplicate primary key" # New test case. Start a new database -CASE OrderCheck -CHECK_ORDER -PARALLELISM 1 -STATEMENT MATCH (a:person)-[:studyAt]->(b:organisation) WHERE b.name = "Waterloo" RETURN a.name, a.age ORDER BY a.age DESC; ---- 2 Karissa|40 Adam|30 # Read query results from a file to compare -CASE PersonOrganisationRelTest -STATEMENT MATCH (a:person)-[:studyAt]->(b:organisation) RETURN a.ID, b.ID; ---- 16 :person_study_at_answers.txt ``` -------------------------------- ### Update an Installed Extension Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/index.mdx Re-download an extension if it is not working properly or if you need the latest version. Running INSTALL again will not perform any action if the extension is already installed. ```cypher UPDATE ; ``` -------------------------------- ### Install Kuzu Node.js Client Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Node.js client library using npm. This command adds the kuzu package to your project's dependencies. ```bash npm install kuzu ``` -------------------------------- ### Java: Minimal build.gradle Configuration Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx The minimal build.gradle configuration required for the Java example. ```groovy plugins { id 'java' id 'application' } repositories { mavenCentral() } dependencies { implementation 'com.kuzudb:kuzu:0.3.0' } application { mainClass = 'Main' } ``` -------------------------------- ### Install Build Tools on Arch Linux Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs the base development tools, CMake, GCC, and Python required for building Kuzu on Arch Linux. ```bash pacman -Syu pacman -S --needed base-devel cmake gcc python ``` -------------------------------- ### Install Kuzu Nightly Node.js Package Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the latest nightly build of the Kuzu Node.js package using npm. ```bash npm i kuzu@next ``` -------------------------------- ### Install Kuzu Python Client with Nix Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Python client using Nix. This command creates a shell with Python 3 and the kuzu package available. ```bash nix-shell -p "python3.withPackages (ps: [ ps.kuzu ])" ``` -------------------------------- ### Install Kuzu Python Client with pip Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the Kuzu Python client library using pip. This is a standard way to add Python packages to your environment. ```bash pip install kuzu ``` -------------------------------- ### Install Kuzu using CMake for Other Build Systems Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/c.mdx Build and install Kuzu using CMake to obtain the dynamic library and header file. These can then be used by other build systems. ```bash cmake -B build cmake --build build cmake --install build --prefix '' ``` -------------------------------- ### Install Node.js Dependencies for Kuzu Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Downloads and installs the required Node.js and npm packages for building Kuzu's Node.js bindings. ```bash make nodejs-deps ``` -------------------------------- ### Attach PostgreSQL Database with Connection String Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/postgres.mdx An example of attaching a PostgreSQL database named 'university' to Kuzu using a detailed connection string, specifying the user, host, password, and port. ```cypher ATTACH 'dbname=university user=postgres host=localhost password=testpassword port=5432' AS uw (dbtype postgres); ``` -------------------------------- ### Start In-Memory Database CLI Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/cli.mdx Opens Kuzu in-memory mode without specifying a database path. ```bash kuzu ``` ```text Opened the database under in-memory mode. Enter ":help" for usage hints. kuzu> ``` -------------------------------- ### Install and Load Kuzu Algo Extension Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/graph-algorithms.md Installs and loads the 'algo' extension for Kuzu, which provides native graph algorithm functionalities. ```python import kuzu db_path = "example.kuzu" db = kuzu.Database(db_path) conn = kuzu.Connection(db) # Install and load the Kuzu algo extension conn.execute("INSTALL algo; LOAD algo;") ``` -------------------------------- ### Install Kuzu Wasm Package Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/wasm.mdx Install the Kuzu Wasm package using npm. This is the first step to using Kuzu in a browser or Node.js environment. ```bash npm i kuzu-wasm ``` -------------------------------- ### Install Kuzu Nightly Python Package Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Install the latest nightly build of the Kuzu Python package using pip with the --pre flag. ```bash uv pip install --pre kuzu ``` -------------------------------- ### Running tests with e2e_test binary Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/testing-framework.md Examples of using the e2e_test binary to run specific test files or directories. ```bash # Run all tests inside test/test_files/copy $ ./e2e_test copy # Run all tests from test/test_files/long_string_pk.test file $ ./e2e_test long_string_pk/long_string_pk.test # Run all tests $ ./e2e_test . ``` -------------------------------- ### GTest registration example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/testing-framework.md Illustrates how a basic test case from a .test file is registered as a GTest test. ```cpp TEST_F(basic, e2e_test_BasicTest) { ... } ``` -------------------------------- ### C API Example: Database Initialization and Queries Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Demonstrates how to initialize an on-disk Kuzu database, create tables, load data from CSV, and execute queries using the C API. ```c // main.c #include #include "include/kuzu.h" int main() { // Create an empty on-disk database and connect to it kuzu_database db; kuzu_database_init("example.kuzu", kuzu_default_system_config(), &db); // Connect to the database. kuzu_connection conn; kuzu_connection_init(&db, &conn); // Create the schema. kuzu_query_result result; kuzu_connection_query(&conn, "CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE REL TABLE Follows(FROM User TO User, since INT64)", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "CREATE REL TABLE LivesIn(FROM User TO City)", &result); kuzu_query_result_destroy(&result); // Load data. kuzu_connection_query(&conn, "COPY User FROM \"user.csv\"", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "COPY City FROM \"city.csv\"", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "COPY Follows FROM \"follows.csv\"", &result); kuzu_query_result_destroy(&result); kuzu_connection_query(&conn, "COPY LivesIn FROM \"lives-in.csv\"", &result); kuzu_query_result_destroy(&result); // Execute a simple query. kuzu_connection_query(&conn, "MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;", &result); // Output query 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 = NULL; kuzu_value_get_string(&value, &name); kuzu_value_destroy(&value); kuzu_flat_tuple_get_value(&tuple, 1, &value); int64_t since = 0; kuzu_value_get_int64(&value, &since); kuzu_value_destroy(&value); kuzu_flat_tuple_get_value(&tuple, 2, &value); char *name2 = NULL; kuzu_value_get_string(&value, &name2); kuzu_value_destroy(&value); printf("%s follows %s since %lld \n", name, name2, since); free(name); free(name2); } kuzu_value_destroy(&value); kuzu_flat_tuple_destroy(&tuple); kuzu_query_result_destroy(&result); kuzu_connection_destroy(&conn); kuzu_database_destroy(&db); return 0; } ``` -------------------------------- ### User Node Data Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/example-database.md Sample data for the User node, including user ID, username, and account creation date. ```csv userID,username,account_creation_date 1,epicwolf202,2022-09-09 2,silentninja637,2023-01-27 3,stormcat597,2023-02-25 4,brightking765,2023-05-11 5,fastgirl798,2021-06-11 ``` -------------------------------- ### Load KuzuDB Query Results into Pandas DataFrame Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx This example shows how to execute a Cypher query and load the results directly into a Pandas DataFrame for further analysis. Ensure the pandas library is installed. ```python # pip install pandas response = conn.execute( """ MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, b.name, f.since; """ ) print(response.get_as_df()) ``` ```bash a.name b.name f.since 0 Adam Karissa 2020 1 Adam Zhang 2020 2 Karissa Zhang 2021 3 Zhang Noura 2022 ``` -------------------------------- ### Create Source Files Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/python/index.mdx Create the 'src' directory and the 'create_db.py' and 'main.py' files for the tutorial. ```bash mkdir src touch src/create_db.py touch src/main.py ``` -------------------------------- ### Filter Users by Age or Name Prefix Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/query-clauses/where.md Use the WHERE clause to filter nodes based on multiple conditions combined with OR. This example filters users older than 45 or whose names start with 'Kar'. ```cypher MATCH (a:User) WHERE a.age > 45 OR starts_with(a.name, "Kar") RETURN *; ``` -------------------------------- ### Go: Create Schema, Load Data, and Query Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Shows how to initialize an on-disk Kuzu database, open a connection, create tables, load data from CSV, and execute a Cypher query using the Go client. ```go // main.go package main import ( "fmt" "github.com/kuzudb/go-kuzu" ) func main() { // Create an empty on-disk database and connect to it systemConfig := kuzu.DefaultSystemConfig() systemConfig.BufferPoolSize = 1024 * 1024 * 1024 db, err := kuzu.OpenDatabase("example.kuzu", systemConfig) if err != nil { panic(err) } defer db.Close() conn, err := kuzu.OpenConnection(db) if err != nil { panic(err) } defer conn.Close() // Create schema queries := []string{ "CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", "CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", "CREATE REL TABLE Follows(FROM User TO User, since INT64)", "CREATE REL TABLE LivesIn(FROM User TO City)", "COPY User FROM \"./data/user.csv\"", "COPY City FROM \"./data/city.csv\"", "COPY Follows FROM \"./data/follows.csv\"", "COPY LivesIn FROM \"./data/lives-in.csv\"", } for _, query := range queries { queryResult, err := conn.Query(query) if err != nil { panic(err) } defer queryResult.Close() } // Execute Cypher query query := "MATCH (a:User)-[e:Follows]->(b:User) RETURN a.name, e.since, b.name" result, err := conn.Query(query) if err != nil { panic(err) } defer result.Close() for result.HasNext() { tuple, err := result.Next() if err != nil { panic(err) } defer tuple.Close() // The result is a tuple, which can be converted to a slice. slice, err := tuple.GetAsSlice() if err != nil { panic(err) } fmt.Println(slice) } } ``` -------------------------------- ### Filter Users with Non-NULL Age and Name Prefix Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/query-clauses/where.md Filter nodes ensuring a property is not NULL and meets a specific condition. This example finds users whose age is not NULL and whose names start with 'Kar'. ```cypher MATCH (a:User) WHERE a.age IS NOT NULL AND starts_with(a.name, "Kar") RETURN *; ``` -------------------------------- ### Query Vector Index with Sentence Transformers Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/vector.mdx Example of querying a vector index using embeddings generated by the Sentence Transformers library. Ensure the VECTOR extension is installed and loaded. The query vector is generated from a text string, and results are ordered by distance. ```python import kuzu # Initialize the database db = kuzu.Database("example.kuzu") conn = kuzu.Connection(db) # Install and load vector extension once again conn.execute("INSTALL VECTOR;") conn.execute("LOAD VECTOR;") from sentence_transformers import SentenceTransformer # Load a pre-trained embedding generation model # https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2 model = SentenceTransformer("all-MiniLM-L6-v2") query_vector = model.encode("quantum machine learning").tolist() result = conn.execute( """ CALL QUERY_VECTOR_INDEX( 'Book', 'book_title_index', $query_vector, $limit, efs := 500 ) RETURN node.title ORDER BY distance; """, {"query_vector": query_vector, "limit": 2}) print(result.get_as_pl()) ``` -------------------------------- ### Execute Parameterized Queries in C++ Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/prepared-statements.mdx This C++ example demonstrates how to create a database, define a schema, insert nodes with parameters, and execute a match query using prepared statements. It includes helper functions for running queries and handling results. ```cpp // main.cpp #include #include #include #include "kuzu.hpp" using namespace kuzu::main; using namespace std; unique_ptr runQuery(const string_view &query, unique_ptr &connection) { auto results = connection->query(query); if (!results->isSuccess()) { throw std::runtime_error(results->getErrorMessage()); } return results; } unique_ptr runPreparedQuery(const string_view &query, std::unordered_map> inputParams, const unique_ptr &connection) { auto prepared_stmt = connection->prepare(query); if (!prepared_stmt->isSuccess()) { throw std::runtime_error(prepared_stmt->getErrorMessage()); } auto results = connection->executeWithParams(prepared_stmt.get(), std::move(inputParams)); if (!results->isSuccess()) { throw std::runtime_error(results->getErrorMessage()); } return results; } int main() { // Remove example.kuzu remove("example.kuzu"); remove("example.kuzu.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.kuzu", systemConfig); auto connection = make_unique(database.get()); // Create the schema. runQuery("CREATE NODE TABLE N(id SERIAL PRIMARY KEY, name STRING, age INT64, embedding FLOAT[])", connection); // Create a node. runQuery("CREATE (:N {name: 'Alice', embedding: [10.0, 20.0, 30.0], age: 25});", connection); std::unordered_map> args; // `name` parameter. args.emplace("name", make_unique("Bob")); // `age` parameter. uint64_t age = 30; args.emplace("age", make_unique(age)); // `embedding` parameter. auto type = kuzu::common::LogicalType::LIST(kuzu::common::LogicalType::FLOAT()); vector> data; data.push_back(make_unique((float)40.0)); data.push_back(make_unique((float)50.1)); data.push_back(make_unique((float)60.0)); args.emplace("embedding", make_unique(std::move(type), std::move(data))); // Create a node using parameters. runPreparedQuery("CREATE (:N {name: $name, age: $age, embedding: $embedding});", std::move(args), connection); // Execute a match query. auto result = runQuery("MATCH (n) RETURN n.name, n.age, n.embedding;", connection); // Print the column names. auto columns = result->getColumnNames(); for (auto i = 0u; i < columns.size(); ++i) { if (i != 0) { cout << " | "; } cout << columns[i]; } cout << "\n"; // Print the rows. while (result->hasNext()) { auto row = result->getNext(); // Print `name`. auto value_name = row->getValue(0); KU_ASSERT_UNCONDITIONAL(value_name->getDataType().getLogicalTypeID() == kuzu::common::LogicalTypeID::STRING); cout << value_name->getValue() << " | "; // Print `age`. auto value_int64 = row->getValue(1); KU_ASSERT_UNCONDITIONAL(value_int64->getDataType().getLogicalTypeID() == kuzu::common::LogicalTypeID::INT64); cout << value_int64->getValue() << " | "; // Print `embedding`. auto value_embedding = row->getValue(2); KU_ASSERT_UNCONDITIONAL(value_embedding->getDataType().getLogicalTypeID() == kuzu::common::LogicalTypeID::LIST); auto length = value_embedding->getChildrenSize(); vector embedding; for (auto i = 0u; i < length; ++i) { auto element = kuzu::common::NestedVal::getChildVal(value_embedding, i); KU_ASSERT_UNCONDITIONAL(element->getDataType().getLogicalTypeID() == kuzu::common::LogicalTypeID::FLOAT); embedding.push_back(element->getValue()); } auto join = [](const std::vector& vec, const std::string& sep) { std::ostringstream oss; for (size_t i = 0; i < vec.size(); i++) { if (i > 0) oss << sep; oss << vec[i]; } return oss.str(); }; cout << "[" << join(embedding, ", ") << "]\n"; } return 0; } ``` ```text n.name | n.age | n.embedding Alice | 25 | [10, 20, 30] Bob | 30 | [40, 50.1, 60] ``` -------------------------------- ### Enforcing Join Order with HINT Clause Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/join-order-hint.md Example of using the HINT clause to enforce a specific join order, scanning edges using backward adjacency lists from node 'b'. This hint guides the optimizer towards a particular execution plan. ```cypher MATCH (a)-[e]->(b) WHERE b.ID = 0 HINT a JOIN (e JOIN b) RETURN *; ``` -------------------------------- ### Query Vector Index with LLM Extension Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/vector.mdx Example of querying a vector index using embeddings generated by the LLM extension, specifically with OpenAI models. Requires installing and loading both VECTOR and LLM extensions, and setting the OPENAI_API_KEY environment variable. The query vector is created directly within the query. ```python import kuzu # Initialize the database db = kuzu.Database("example.kuzu") conn = kuzu.Connection(db) # Install and load vector extension once again conn.execute("INSTALL VECTOR;") conn.execute("LOAD VECTOR;") conn.execute("INSTALL llm; LOAD llm;") os.environ["OPENAI_API_KEY"] = "sk-proj-key" # Replace with your own OpenAI API key result = conn.execute( """ CALL QUERY_VECTOR_INDEX( 'Book', 'book_title_index', create_embedding( 'quantum machine learning', 'open-ai', 'text-embedding-3-small', 384 ), $limit ) RETURN node.title ORDER BY distance; """, {"limit": 2}) print(result.get_as_pl()) ``` -------------------------------- ### Install yFiles Jupyter Graphs with pip Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/visualization/third-party-integrations/yfiles.mdx Installs the kuzu and yfiles-jupyter-graphs-for-kuzu packages using pip. Ensure kuzu is installed as a prerequisite. ```bash pip install kuzu yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### Create Node and Relationship Tables Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/import/copy-from-subquery.md Defines the necessary node and relationship tables for the examples. Ensure these tables are created before running import operations. ```cypher CREATE NODE TABLE Person(name STRING PRIMARY KEY, num_purchases INT64) CREATE NODE TABLE Product(name STRING PRIMARY KEY, price DOUBLE) CREATE REL TABLE HasReward(FROM Person TO Product); ``` -------------------------------- ### Run Java Tests Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Runs the tests for the Java bindings. Ensure JDK 11 or later is installed. ```bash make javatest NUM_THREADS=$(nproc) ``` -------------------------------- ### FOLLOWS Relationship Data Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/example-database.md Sample data for the FOLLOWS relationship, indicating which user follows another. ```csv followerID,followeeID 1,7 1,6 2,17 2,10 2,13 ``` -------------------------------- ### Compile and Run C++ Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Build your C++ project using CMake and execute the compiled binary. This demonstrates a basic workflow for running Kuzu applications. ```bash cmake -S . -B build cmake --build build ./build/kuzu-cpp ``` -------------------------------- ### SelectionState Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/database-internal/vector.md Demonstrates how SelectionState tracks valid data within a ValueVector using selectedPositions and selectedSize. ```plaintext Value vector data: [10, 11, 12, 13, 14] Selection state: selectedPositions: [0, 2] selectedSize: 2 Data being represented: [10, 12] ``` -------------------------------- ### Download Tutorial Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/example-database.md Download and unzip the tutorial dataset using curl. Ensure the files are extracted to your current working directory. ```bash curl -o tutorial_data.zip https://kuzudb.github.io/data/tutorial/tutorial_data.zip unzip tutorial_data.zip ``` -------------------------------- ### Get Current Timestamp Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/expressions/timestamp-functions.md Use `current_timestamp()` to get the current timestamp at the time of execution. ```cypher current_timestamp() ``` -------------------------------- ### Download Kuzu CLI for macOS Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/installation.mdx Download the Kuzu CLI for macOS. Extract the archive and run the executable. Alternatively, install via Homebrew. ```bash curl -L -O https://github.com/kuzudb/kuzu/releases/download/v${version}/kuzu_cli-osx-universal.tar.gz tar xzf kuzu_cli-*.tar.gz ./kuzu ``` -------------------------------- ### Kuzu Comparison Operators Examples Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/expressions/comparison-operators.md Demonstrates the usage of standard comparison operators in Kuzu. Note that if any input is NULL, the result is NULL. ```cypher 2 < 3 ``` ```cypher 1 > 5 ``` ```cypher 3 <= 3 ``` ```cypher 4 >= 2 ``` ```cypher NULL = NULL ``` ```cypher 5 <> NULL ``` -------------------------------- ### Install Python API Requirements Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs the necessary Python package dependencies for the Kuzu Python API. ```bash make -C tools/python_api requirements ``` -------------------------------- ### Display CLI Help Menu Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/cli.mdx Shows all available command-line options for the Kuzu executable. ```bash $ kuzu -h ``` ```text kuzu [databasePath] {OPTIONS} KuzuDB Shell OPTIONS: databasePath Database path. -h, --help Display this help menu -d, --default_bp_size, --defaultbpsize Size of buffer pool for default and large page sizes in megabytes --no_compression, --nocompression Disable compression -r, --read_only, --readonly Open database at read-only mode. -p, --path_history Path to directory for shell history -v, --version Display current database version -m, --mode Set the output mode of the shell -s, --no_stats, --nostats Disable query stats "--" can be used to terminate flag options and force all following arguments to be treated as positional options ``` -------------------------------- ### C++ Kuzu Database Operations Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Demonstrates creating a database, defining schemas, loading data from CSV files, and executing a query using the Kuzu C++ API. ```cpp // main.cpp #include #include "include/kuzu.hpp" using namespace kuzu::main; using namespace std; unique_ptr runQuery(const string_view &query, unique_ptr &connection) { auto results = connection->query(query); if (!results->isSuccess()) { throw std::runtime_error(results->getErrorMessage()); } return results; } int main() { // Remove example.kuzu remove("example.kuzu"); remove("example.kuzu.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.kuzu", systemConfig); auto connection = make_unique(database.get()); // Create the schema. runQuery("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", connection); runQuery("CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", connection); runQuery("CREATE REL TABLE Follows(FROM User TO User, since INT64)", connection); runQuery("CREATE REL TABLE LivesIn(FROM User TO City)", connection); // Load data. runQuery("COPY User FROM 'data/user.csv'", connection); runQuery("COPY City FROM 'data/city.csv'", connection); runQuery("COPY Follows FROM 'data/follows.csv'", connection); runQuery("COPY LivesIn FROM 'data/lives-in.csv'", connection); // Execute a simple query. auto result = runQuery("MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;", connection); // Output query result. while (result->hasNext()) { auto row = result->getNext(); std::cout << row->getValue(0)->getValue() << " | " << row->getValue(1)->getValue() << " | " << row->getValue(2)->getValue() << std::endl; } return 0; } ``` -------------------------------- ### Initialize Kuzu Database Connection Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/graph-algorithms.md Establishes a connection to an existing Kuzu database file located at 'example.kuzu'. This is the initial step required before performing any database operations. ```python import kuzu db_path = "example.kuzu" db = kuzu.Database(db_path) conn = kuzu.Connection(db) ``` -------------------------------- ### Create an On-Disk Kuzu Database (CLI) Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Initialize a new on-disk Kuzu database by specifying a database file path when running the Kuzu CLI. This database persists after the process ends. ```bash kuzu example.kuzu ``` -------------------------------- ### Initialize Kuzu Database Connection in Python Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/python/index.mdx Sets up a Kuzu database connection in Python. Replace the `conn.execute(...)` placeholder with your Cypher queries. ```python import kuzu def main() -> None: db = kuzu.Database("social_network.kuzu") conn = kuzu.Connection(db) # Query to be filled out below result = conn.execute(...) for row in result: print(row) if __name__ == "__main__": main() ``` -------------------------------- ### Install CMake and Python on macOS Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs CMake and Python using Homebrew, essential dependencies for building Kuzu on macOS. ```bash brew install cmake python ``` -------------------------------- ### Rust: Create Schema Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Example Rust code to create node tables using the Kuzu client library. This snippet focuses on schema creation. ```rust // main.rs use kuzu::{Connection, Database, Error, SystemConfig}; fn main() -> Result<(), Error> { // Create an empty on-disk database and connect to it let db = Database::new("example.kuzu", SystemConfig::default())?; let conn = Connection::new(&db)?; // Create the tables conn.query("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)")?; ``` -------------------------------- ### Python: Create Schema and Load Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Demonstrates creating node and relationship tables, then loading data from CSV files using the Python client. Assumes pyarrow is installed. ```python conn.query("CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)")?; conn.query("CREATE REL TABLE Follows(FROM User TO User, since INT64)")?; conn.query("CREATE REL TABLE LivesIn(FROM User TO City)")?; // Load the data conn.query("COPY User FROM './data/user.csv'")?; conn.query("COPY City FROM './data/city.csv'")?; conn.query("COPY Follows FROM './data/follows.csv'")?; conn.query("COPY LivesIn FROM './data/lives-in.csv'")?; let query_result = conn.query("MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;")?; // Print the rows for row in query_result { println!("{}, {}, {}", row[0], row[1], row[2]); } Ok(()) } ``` -------------------------------- ### Download and Unzip Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/tutorials/python/index.mdx Download the tutorial dataset using curl and unzip the files. The downloaded zip is then removed. ```bash curl -o tutorial_data.zip https://kuzudb.github.io/data/tutorial/tutorial_data.zip unzip tutorial_data.zip rm tutorial_data.zip ``` -------------------------------- ### JSON Data Example Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/import/copy-from-json.md This is an example of a JSON file structure used for importing data into Kuzu. It includes nested objects and arrays. ```json // people.json [ { "p_id": "p1", "name": "Gregory", "info": { "height": 1.81, "weight": 75.5, "age": 35, "insurance_provider": [ { "type": "health", "name": "Blue Cross Blue Shield", "policy_number": "1536425345" } ] } }, { "p_id": "p2", "name": "Alicia", "info": { "height": 1.65, "weight": 60.1, "age": 28, "insurance_provider": [ { "type": "health", "name": "Aetna", "policy_number": "9876543210" } ] } }, { "p_id": "p3", "name": "Rebecca" } ] ``` -------------------------------- ### Create and Populate Sample PostgreSQL Database Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/attach/postgres.mdx A Python script using asyncpg to create a 'person' table and insert sample data into a PostgreSQL database. It includes error handling for duplicate tables and fetches the inserted data. ```python import asyncio import asyncpg async def main(): conn = await asyncpg.connect('postgresql://postgres:testpassword@localhost:5432/postgres') # Create and insert data to a new table try: await conn.execute("CREATE TABLE IF NOT EXISTS person (name VARCHAR, age INTEGER);") await conn.execute("INSERT INTO person (name, age) VALUES ('Alice', 30)") await conn.execute("INSERT INTO person (name, age) VALUES ('Bob', 27)") await conn.execute("INSERT INTO person (name, age) VALUES ('Carol', 19)") await conn.execute("INSERT INTO person (name, age) VALUES ('Dan', 25)") except asyncpg.exceptions.DuplicateTableError: print(f"Table already exists, skipping creation and insertion...") # Check results print(await conn.fetch("SELECT * FROM person")) asyncio.run(main()) ``` -------------------------------- ### Basic .test file structure Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/testing-framework.md A basic example of a .test file, showing the header with dataset and buffer pool size, followed by a CASE block with a Cypher statement and expected output. ```plaintext # test/test_files/basic.test # Comments are allowed -DATASET CSV tinysnb -BUFFER_POOL_SIZE 64000000 -- -CASE BasicTest -STATEMENT MATCH (p:person) RETURN COUNT(*); ---- 1 6000 ``` -------------------------------- ### Get Path Length Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/expressions/recursive-rel-functions.md Use the `LENGTH()` function to get the number of relationships in a path. This is equivalent to `SIZE(rels(p))` for recursive relationships. ```cypher MATCH p = (a:User)-[f:Follows*1..2]->(b:User) RETURN LENGTH(p); ``` -------------------------------- ### Create Example Dataset Tables and Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/extensions/algo/index.mdx This snippet creates the necessary node and relationship tables and populates them with sample data for use with graph algorithms. ```cypher CREATE NODE TABLE Person(name STRING PRIMARY KEY); CREATE REL TABLE KNOWS(FROM Person to Person, id INT64); CREATE (u0:Person {name: 'Alice'}), (u1:Person {name: 'Bob'}), (u2:Person {name: 'Charlie'}), (u3:Person {name: 'Derek'}), (u4:Person {name: 'Eve'}), (u5:Person {name: 'Frank'}), (u6:Person {name: 'George'}), (u7:Person {name: 'Hina'}), (u8:Person {name: 'Ira'}), (u0)-[:KNOWS {id: 0}]->(u1), (u1)-[:KNOWS {id: 1}]->(u2), (u5)-[:KNOWS {id: 2}]->(u4), (u6)-[:KNOWS {id: 3}]->(u4), (u6)-[:KNOWS {id: 4}]->(u5), (u6)-[:KNOWS {id: 5}]->(u7), (u7)-[:KNOWS {id: 6}]->(u4), (u6)-[:KNOWS {id: 7}]->(u5); ``` -------------------------------- ### Build Production Site Source: https://github.com/kuzudb/docs/blob/main/README.md Builds the production-ready version of the site, outputting the static files to the ./dist/ directory. This is the final step before deployment. ```bash npm run build ``` -------------------------------- ### Get data type with typeof Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/cypher/expressions/utility-functions.md Use typeof to get the name of the data type of an argument. Useful for type checking or dynamic logic. ```cypher typeof(true) ``` -------------------------------- ### Create Kuzu Database and Load Data (Python) Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/get-started/index.mdx Initialize an on-disk Kuzu database, define the schema, and import data from CSV files using the Python client. ```python from kuzu import Connection, Database db = Database("../data/") conn = Connection(db) conn.execute( "CREATE NODE TABLE User(user_id INT64, PRIMARY KEY(user_id));\n" "CREATE NODE TABLE City(city_id INT64, name STRING, PRIMARY KEY(city_id));\n" "CREATE REL_TABLE Follows(FROM User TO User, follow_id INT64);\n" "CREATE REL_TABLE LivesIn(FROM User TO City, description STRING);" ) conn.execute( "\nCOPY User FROM './data/user.csv' (HEADER=TRUE, INFER_TYPES=TRUE);\n" "COPY City FROM './data/city.csv' (HEADER=TRUE, INFER_TYPES=TRUE);\n" "COPY Follows FROM './data/follows.csv' (HEADER=TRUE, INFER_TYPES=TRUE);\n" "COPY LivesIn FROM './data/lives-in.csv' (HEADER=TRUE, INFER_TYPES=TRUE);" ) print("Database created and data loaded successfully!") ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/developer-guide/index.md Installs the Xcode command-line developer tools, which include compilers and other essential utilities for macOS development. ```bash xcode-select --install ``` -------------------------------- ### Preview Production Build Locally Source: https://github.com/kuzudb/docs/blob/main/README.md Allows you to preview the production build locally before deploying it. This ensures the site functions as expected in a production-like environment. ```bash npm run preview ``` -------------------------------- ### Create Table and Insert Data Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/client-apis/python.mdx Sets up a table named 'Item' with integer columns and inserts sample data to be used with UDFs. ```python conn.execute("CREATE NODE TABLE IF NOT EXISTS Item (id INT64 PRIMARY KEY, a INT64, b INT64, c INT64)") conn.execute("CREATE (i:Item {id: 1}) SET i.a = 134, i.b = 123") conn.execute("CREATE (i:Item {id: 2}) SET i.a = 44, i.b = 29") conn.execute("CREATE (i:Item {id: 3}) SET i.a = 32, i.b = 68") ``` -------------------------------- ### Launch Kuzu Explorer with Custom Buffer Pool Size Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/visualization/kuzu-explorer/index.mdx Launches Kuzu Explorer with a specified buffer pool size in bytes. This allows tuning memory usage for performance. The database path must be an absolute path. ```bash docker run -p 8000:8000 \ -v /absolute/path/to/database:/database \ -e KUZU_BUFFER_POOL_SIZE=1073741824 \ --rm kuzudb/explorer:latest ``` -------------------------------- ### Launch Kuzu Explorer with an Existing Database Source: https://github.com/kuzudb/docs/blob/main/src/content/docs/visualization/kuzu-explorer/index.mdx Launches Kuzu Explorer by mounting an existing Kuzu database file. Changes made in the UI persist to the mounted file. The `--rm` flag ensures the container is removed after use. ```bash docker run -p 8000:8000 \ -v {path to the directory containing the database file}:/database \ -e KUZU_FILE={database file name} \ --rm kuzudb/explorer:latest ```