### Install asyncpg Library Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/postgres.mdx Install the asyncpg library, an asynchronous PostgreSQL client for Python, which is used in the example to create and populate a sample database. ```bash pip install asyncpg ``` -------------------------------- ### Start PostgreSQL Server with Docker Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/postgres.mdx Use this command to start a PostgreSQL server locally for development purposes. Note that this setup is not persistent and uses a plain text password, making it unsuitable for production. ```sh docker run --rm --name lbug-postgres \ -e POSTGRES_PASSWORD=testpassword \ -p 5432:5432 \ postgres:latest ``` -------------------------------- ### Initialize Database Connection (Rust) Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Initializes a new on-disk LadybugDB database and establishes a connection. This example assumes the 'lbug' crate is installed and configured. ```rust // main.rs use lbug::{Connection, Database, Error, SystemConfig}; fn main() -> Result<(), Error> { // Create an empty on-disk database and connect to it let db = Database::new("example.lbug", SystemConfig::default())?; let conn = Connection::new(&db)?; // Create the tables ``` -------------------------------- ### Start Local Server and Build Site Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Starts a local server and builds the site for production. ```bash npm start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Installs all the necessary dependencies for the project. ```bash npm install ``` -------------------------------- ### Start Ladybug CLI Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/cypher/index.mdx Opens an in-memory database using the Ladybug CLI. Ensure the CLI is installed before running. ```bash # Open an in-memory database lbug ``` -------------------------------- ### Start Unity Catalog Server Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/unity.md Clone the Unity Catalog repository and start the server. This is a prerequisite for using the Unity Catalog extension. ```bash git clone https://github.com/unitycatalog/unitycatalog.git bin/start-uc-server ``` -------------------------------- ### Start Local Development Server Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Starts the local development server, typically accessible at localhost:4321. ```bash npm run dev ``` -------------------------------- ### Install an Official Extension Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/index.mdx Install an official extension from the extension server. This only needs to be done once per extension. ```cypher INSTALL ; ``` -------------------------------- ### Full Test Example with Comments and Definitions Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/testing-framework.md This example demonstrates a comprehensive test case including header directives, buffer pool size, dataset definition, statement block definition, and multiple test cases with logging and assertions. ```text # 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 ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs the required Node.js and npm dependencies for building the Node.js bindings. ```bash make nodejs-deps ``` -------------------------------- ### Initialize Python API Submodule Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Example of initializing and checking out the Python API submodule. ```bash git submodule update --init tools/python_api ``` -------------------------------- ### Install yFiles Jupyter Graphs with uv Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/visualization/third-party-integrations/yfiles.mdx Install the ladybug and yfiles-jupyter-graphs-for-kuzu packages using uv. Ensure lbug is installed as a prerequisite. ```bash # Install lbug as a pre-requisite uv init uv add ladybug yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### User Node Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Example data for the User node, including userID, 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 ``` -------------------------------- ### C++ LadybugDB Example: Create and Query Nodes Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/prepared-statements.mdx This C++ example demonstrates how to connect to a LadybugDB database, create a node table, insert nodes using both direct queries and prepared statements with parameters, and then query the data. It includes error handling for query execution. ```cpp // main.cpp #include #include #include #include "lbug.hpp" using namespace lbug::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.lbug remove("example.lbug"); remove("example.lbug.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.lbug", 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 = lbug::common::LogicalType::LIST(lbug::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() == lbug::common::LogicalTypeID::STRING); cout << value_name->getValue() << " | "; // Print `age`. auto value_int64 = row->getValue(1); KU_ASSERT_UNCONDITIONAL(value_int64->getDataType().getLogicalTypeID() == lbug::common::LogicalTypeID::INT64); cout << value_int64->getValue() << " | "; // Print `embedding`. auto value_embedding = row->getValue(2); KU_ASSERT_UNCONDITIONAL(value_embedding->getDataType().getLogicalTypeID() == lbug::common::LogicalTypeID::LIST); auto length = value_embedding->getChildrenSize(); vector embedding; for (auto i = 0u; i < length; ++i) { auto element = lbug::common::NestedVal::getChildVal(value_embedding, i); KU_ASSERT_UNCONDITIONAL(element->getDataType().getLogicalTypeID() == lbug::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] ``` -------------------------------- ### Go Query Results Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Example output format for a Go query executing a Cypher query. ```text [Adam 2020 Karissa] [Adam 2020 Zhang] [Karissa 2021 Zhang] [Zhang 2022 Noura] ``` -------------------------------- ### Install Ladybug and Activate Virtual Environment Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/python/index.mdx Installs Ladybug within a Python virtual environment. Ensure Python is installed and a virtual environment is created before running. ```bash python -m venv .venv source .venv/bin/activate pip install ladybug ``` -------------------------------- ### Install Build Dependencies on macOS Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs CMake, Python, Ninja, and ccache on macOS using Homebrew after ensuring Xcode command-line tools are installed. ```bash xcode-select --install brew install cmake python ninja ccache ``` -------------------------------- ### Swift Query Results Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Example output format for a Swift query executing a Cypher query. ```text ["b.name": Optional("Karissa"), "e.since": Optional(2020), "a.name": Optional("Adam")] ["e.since": Optional(2020), "a.name": Optional("Adam"), "b.name": Optional("Zhang")] ["b.name": Optional("Zhang"), "e.since": Optional(2021), "a.name": Optional("Karissa")] ["e.since": Optional(2022), "a.name": Optional("Zhang"), "b.name": Optional("Noura")] ``` -------------------------------- ### Install Build Dependencies on Windows Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs Python 3, Make, and Ninja on Windows using Chocolatey. Assumes Visual Studio 2022 with C++ support is already installed. ```powershell choco install -y python3 make ninja ``` -------------------------------- ### Install and Load ADBC Extension Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/adbc.mdx Install and load the 'adbc' extension in LadybugDB. This is a prerequisite before attaching any ADBC-compatible database. ```cypher INSTALL adbc; LOAD adbc; ``` -------------------------------- ### List Available Official Extensions Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/index.mdx Run this command to see all official extensions that can be installed. ```cypher CALL SHOW_OFFICIAL_EXTENSIONS() RETURN *; ``` -------------------------------- ### Install Ladybug Node.js Client Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Installs the Ladybug Node.js client library using npm. This command is used for Node.js projects. ```bash npm install @ladybugdb/core ``` -------------------------------- ### Install Delta Lake Dependencies Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/delta.md Install the necessary Python packages for Delta Lake integration. ```shell pip install deltalake pandas ``` -------------------------------- ### Query Results Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Example output format for a Cypher query returning user relationships. ```text Adam, 2020, Karissa Adam, 2020, Zhang Karissa, 2021, Zhang Zhang, 2022, Noura ``` -------------------------------- ### Install Build Dependencies on Ubuntu Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs necessary build tools including CMake, compilers, Python, Ninja, and ccache on Ubuntu. ```bash apt update apt install -y build-essential cmake gcc g++ python3 ninja-build ccache ``` -------------------------------- ### Install Python API Requirements Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs the necessary Python dependencies for the Ladybug Python API using make. ```bash make -C tools/python_api requirements ``` -------------------------------- ### PageRank Example Usage Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/algo/pagerank.mdx Demonstrates how to set up a graph and run the PageRank algorithm, then display the results. ```APIDOC ## Example Usage ### Setup 1. Create node and relationship tables: ```cypher CREATE NODE TABLE Person(name STRING PRIMARY KEY); CREATE REL TABLE KNOWS(FROM Person to Person); ``` 2. Insert nodes and edges: ```cypher CREATE (u0:Person {name: 'Alice'}) (u1:Person {name: 'Bob'}) (u2:Person {name: 'Charlie'}) (u3:Person {name: 'Derek'}) (u4:Person {name: 'Eve'}) (u0)-[:KNOWS]->(u1) (u0)-[:KNOWS]->(u4) (u1)-[:KNOWS]->(u4) (u2)-[:KNOWS]->(u4) (u3)-[:KNOWS]->(u4); ``` 3. Create a projected graph: ```cypher CALL project_graph('Graph', ['Person'], ['KNOWS']); ``` ### Run PageRank Execute the `page_rank` procedure on the projected graph and order results by rank: ```cypher CALL page_rank('Graph') RETURN node.name, rank ORDER BY rank DESC; ``` ### Results The following table shows the nodes ranked by their PageRank score: ```table ┌───────────┬──────────┐ │ node.name │ rank │ │ STRING │ DOUBLE │ ├───────────┼──────────┤ │ Eve │ 0.130088 │ │ Bob │ 0.042750 │ │ Derek │ 0.030000 │ │ Charlie │ 0.030000 │ │ Alice │ 0.030000 │ └───────────┴──────────┘ ``` ``` -------------------------------- ### Install Ladybug Python Client with Nix Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Installs the Ladybug Python client library within a Nix shell, ensuring a reproducible Python environment. ```bash nix-shell -p "python3.withPackages (ps: [ ps.lbug ])" ``` -------------------------------- ### FOLLOWS Relationship Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Example data for the FOLLOWS relationship, indicating followerID and followeeID. ```csv followerID,followeeID 1,7 1,6 2,17 2,10 2,13 ``` -------------------------------- ### Post Node Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Example data for the Post node, including postID, creation_date, like_count, and retweet_count. ```csv postID,creation_date,like_count,retweet_count 1,2021-12-08,427,29 2,2022-06-02,9,16 3,2023-01-14,238,51 4,2023-01-06,67,147 5,2022-10-26,103,73 ``` -------------------------------- ### Launch Ladybug Explorer with an empty database Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/visualization/lbug-explorer/index.mdx Launch Ladybug Explorer with a default empty database. This command is used when you want to start with bundled datasets or create a new database. The server will start with an empty database if no path is specified. ```bash docker run -p 8000:8000 --rm ghcr.io/ladybugdb/explorer:latest ``` -------------------------------- ### Building Ladybug with CMake for Other Build Systems Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/client-apis/c.mdx Commands to build and install Ladybug using CMake, preparing it for integration with other build systems. The install prefix can be customized. ```bash cmake -B build cmake --build build cmake --install build --prefix '' ``` -------------------------------- ### Get Help with Astro CLI Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Displays help information for using the Astro CLI. ```bash npm run astro -- --help ``` -------------------------------- ### Install and Load Ladybug Algo Extension Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/graph-algorithms.md Installs and loads the 'algo' extension for running native graph algorithms within Ladybug. ```python import ladybug as lb db_path = "example.lbug" db = lb.Database(db_path) conn = lb.Connection(db) # Install and load the Ladybug algo extension conn.execute("INSTALL algo; LOAD algo;") ``` -------------------------------- ### Install Ladybug Python Client with pip Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Installs the Ladybug Python client library using pip. This command is compatible with Linux, macOS, and Windows. ```bash pip install ladybug ``` -------------------------------- ### Install Build Dependencies on AlmaLinux Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/developer-guide/index.md Installs required build tools like CMake, compilers, Python, Ninja, and ccache on AlmaLinux. ```bash dnf update dnf install -y cmake gcc gcc-c++ python3 ninja-build ccache ``` -------------------------------- ### CASE Example - General Form Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/cypher/expressions/case-expression.md This example uses the general form of CASE to return a user's name if their age is less than 50, otherwise it returns 'dummy'. ```cypher MATCH (a:User) RETURN CASE WHEN a.age < 50 THEN a.name ELSE 'dummy' END AS x; ``` -------------------------------- ### Download and Unzip Iceberg Tables Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/iceberg.md Download and extract the example Iceberg tables to the /tmp directory. ```shell cd /tmp wget https://lbugdb.github.io/data/iceberg-extension/iceberg_tables.zip unzip iceberg_tables.zip ``` -------------------------------- ### Start In-Memory Database CLI Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/client-apis/cli.mdx Call 'lbug' without arguments to start the CLI in in-memory mode. Data is not persisted after the shell closes. ```bash lbug ``` ```text Opened the database under in-memory mode. Enter ":help" for usage hints. lbug> ``` -------------------------------- ### Example: Attach University PostgreSQL Database Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/attach/postgres.mdx This example demonstrates how to attach a specific PostgreSQL database named 'university' to Ladybug using a detailed connection string and assigning it an alias 'uw'. ```cypher ATTACH 'dbname=university user=postgres host=localhost password=testpassword port=5432' AS uw (dbtype postgres); ``` -------------------------------- ### Execute Cypher Query and Get Arrow Result (Python) Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Executes a Cypher query and retrieves the result as a pyarrow Table. Ensure pyarrow is installed. ```python response = conn.execute( """ MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, b.name, f.since; """ ) print(response.get_as_arrow()) ``` ```text pyarrow.Table a.name: string b.name: string f.since: int64 ---- a.name: [["Adam","Adam","Karissa","Zhang"]] b.name: [["Karissa","Zhang","Zhang","Noura"]] f.since: [[2020,2020,2021,2022]] ``` -------------------------------- ### CASE Example - Simple Form Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/cypher/expressions/case-expression.md This example demonstrates the simple form of the CASE expression, returning a user's name when their age is exactly 50. Otherwise, it returns NULL. ```cypher MATCH (a:User) RETURN CASE a.age WHEN 50 THEN a.name END AS x; ``` -------------------------------- ### Match relationships by label and return properties Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/cypher-intro.mdx Query for relationships of a specific type (e.g., 'Follows') between nodes and return properties of both nodes and the relationship. This example shows users and when they started following each other. ```cypher MATCH (a)-[e:Follows]->(b) RETURN a.name AS user1, b.name AS user2, e.since AS follows_since; ``` -------------------------------- ### Initialize Swift Project and LadybugDB Client Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Sets up a new Swift project, configures dependencies, and initializes LadybugDB for database operations. Ensure the 'lbug-swift' client is available. ```bash mkdir lbug-swift-example cd lbug-swift-example swift package init --type=executable ``` -------------------------------- ### Start Ladybug with Icebug Schema Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/import/icebug.md Launch Ladybug using the generated schema file with the `-i` flag. ```bash lbug -i csr_graph/schema.cypher ``` -------------------------------- ### Query Vector Index with Sentence Transformers Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/vector.mdx Example of querying a vector index using Sentence Transformers for embedding generation. Requires installing and loading the vector extension and initializing the Ladybug database connection. ```python import ladybug as lb # Initialize the database db = lb.Database("example.lbug") conn = lb.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()) ``` -------------------------------- ### Initialize Database and Execute Query in Go Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Sets up a LadybugDB database, defines schema, loads data, and executes a Cypher query. Ensure data files exist. ```go // main.go package main import ( "fmt" "github.com/LadybugDB/go-ladybug" ) func main() { // Create an empty on-disk database and connect to it systemConfig := lb.DefaultSystemConfig() systemConfig.BufferPoolSize = 1024 * 1024 * 1024 db, err := lb.OpenDatabase("example.lbug", systemConfig) if err != nil { panic(err) } defer db.Close() conn, err := lb.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 by Age or Name Prefix Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/cypher/query-clauses/where.md Use the WHERE clause with boolean operators (OR) and string functions (starts_with) to filter nodes based on multiple conditions. This example finds 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 *; ``` -------------------------------- ### Initialize and Query Ladybug Database in C Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Demonstrates initializing an on-disk Ladybug database, creating node and relationship tables, loading data from CSV, and executing a Cypher query. Requires the 'lb.h' header and the Ladybug library. ```c // main.c #include #include "include/lb.h" int main() { // Create an empty on-disk database and connect to it lbug_database db; lbug_database_init("example.lbug", lbug_default_system_config(), &db); // Connect to the database. lbug_connection conn; lbug_connection_init(&db, &conn); // Create the schema. lbug_query_result result; lbug_connection_query(&conn, "CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "CREATE REL TABLE Follows(FROM User TO User, since INT64)", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "CREATE REL TABLE LivesIn(FROM User TO City)", &result); lbug_query_result_destroy(&result); // Load data. lbug_connection_query(&conn, "COPY User FROM \"user.csv\"", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "COPY City FROM \"city.csv\"", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "COPY Follows FROM \"follows.csv\"", &result); lbug_query_result_destroy(&result); lbug_connection_query(&conn, "COPY LivesIn FROM \"lives-in.csv\"", &result); lbug_query_result_destroy(&result); // Execute a simple query. lbug_connection_query(&conn, "MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;", &result); // Output query result. lbug_flat_tuple tuple; lbug_value value; while (lbug_query_result_has_next(&result)) { lbug_query_result_get_next(&result, &tuple); lbug_flat_tuple_get_value(&tuple, 0, &value); char *name = NULL; lbug_value_get_string(&value, &name); lbug_value_destroy(&value); lbug_flat_tuple_get_value(&tuple, 1, &value); int64_t since = 0; lbug_value_get_int64(&value, &since); lbug_value_destroy(&value); lbug_flat_tuple_get_value(&tuple, 2, &value); char *name2 = NULL; lbug_value_get_string(&value, &name2); lbug_value_destroy(&value); printf("%s follows %s since %lld \n", name, name2, since); free(name); free(name2); } lbug_value_destroy(&value); lbug_flat_tuple_destroy(&tuple); lbug_query_result_destroy(&result); lbug_connection_destroy(&conn); lbug_database_destroy(&db); return 0; } ``` -------------------------------- ### Query Vector Index with LLM Extension Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/vector.mdx Example of querying a vector index using the LLM extension for embedding generation. Requires installing and loading both vector and LLM extensions, setting the OpenAI API key, and initializing the Ladybug database connection. ```python import ladybug as lb # Initialize the database db = lb.Database("example.lbug") conn = lb.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()) ``` -------------------------------- ### Query Results as Dictionary Output Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Example output when query results are formatted as dictionaries. ```bash {'a.name': 'Adam', 'b.name': 'Karissa', 'f.since': 2020} {'a.name': 'Adam', 'b.name': 'Zhang', 'f.since': 2020} {'a.name': 'Karissa', 'b.name': 'Zhang', 'f.since': 2021} {'a.name': 'Zhang', 'b.name': 'Noura', 'f.since': 2022} ``` -------------------------------- ### Perform Filtered Vector Search in Cypher Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/vector.mdx This Cypher example shows how to perform a filtered vector search. It involves installing and loading the LLM extension, creating a projected graph to filter books by publication year, and then executing a vector similarity search on the filtered data. Remember to set your OpenAI API key. ```bash export OPENAI_API_KEY=sk-proj-key # Replace with your own OpenAI API key ``` ```cypher INSTALL llm; LOAD llm; // Step 1: Create a projected graph that filters books by publication year CALL PROJECT_GRAPH( 'filtered_book', // Name of the projected graph {'Book': 'n.published_year > 2010'}, // Projected node table Book with a filter on published_year. `n` is a placeholder here to reference the node table. [] // No relationship tables can be projected. ); // Step 2: Perform vector similarity search on the filtered subset // In the `QUERY_VECTOR_INDEX` function, we can pass in the name of the projected graph as `table_name` parameter. CALL QUERY_VECTOR_INDEX( 'filtered_book', // Name of the projected graph 'book_title_index', // Name of the index create_embedding('quantum world', 'open-ai', 'text-embedding-3-small', 384), 2 ) WITH node AS n, distance as dist MATCH (n)-[:PublishedBy]->(p:Publisher) RETURN n.title AS book, n.published_year AS year, p.name AS publisher ORDER BY dist; ``` -------------------------------- ### Install Ladybug Python Client with uv Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Initializes a project for uv and adds the Ladybug Python client library. This method works on Linux, macOS, and Windows. ```bash uv init uv add ladybug ``` -------------------------------- ### Install Ladybug CLI on macOS with Homebrew Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Installs the Ladybug CLI using Homebrew. After installation, you can run the 'lbug' command. ```bash brew install ladybug ``` ```bash lbug ``` -------------------------------- ### Initialize and Query Database (Java) Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Creates an on-disk database, defines node and relationship tables, loads data from CSV files, and executes a Cypher query. Prints the results to standard output. ```java // Main.java import com.ladybugdb.*; public class Main { public static void main(String[] args) throws ObjectRefDestroyedException { // Create an empty on-disk database and connect to it Database db = new Database("example.lbug"); Connection conn = new Connection(db); // Create tables. conn.query("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)"); 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 data. conn.query("COPY User FROM 'src/main/resources/user.csv'"); conn.query("COPY City FROM 'src/main/resources/city.csv'"); conn.query("COPY Follows FROM 'src/main/resources/follows.csv'"); conn.query("COPY LivesIn FROM 'src/main/resources/lives-in.csv'"); // Execute a simple query. QueryResult result = conn.query("MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;"); while (result.hasNext()) { FlatTuple row = result.getNext(); System.out.print(row); } } } ``` ```text Adam|2020|Karissa Adam|2020|Zhang Karissa|2021|Zhang Zhang|2022|Noura ``` -------------------------------- ### Install Ladybug CLI on Linux Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/installation.mdx Installs the Ladybug CLI using a curl script. After installation, you can run the 'lbug' command. ```bash curl -s https://install.ladybugdb.com | bash ``` ```bash lbug ``` -------------------------------- ### Install yFiles Jupyter Graphs with pip Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/visualization/third-party-integrations/yfiles.mdx Install the ladybug and yfiles-jupyter-graphs-for-kuzu packages using pip. Ensure lbug is installed as a prerequisite. ```bash # Install lbug as a pre-requisite pip install ladybug yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### Download Tutorial Data Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Download the tutorial data using curl and unzip the files to your current working directory. ```bash curl -o tutorial_data.zip https://huggingface.co/datasets/ladybugdb/python-tutorial/resolve/main/tutorial_data.zip unzip tutorial_data.zip ``` -------------------------------- ### Basic Ladybug C++ Client Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx This C++ code demonstrates connecting to an on-disk database, creating node and relationship tables, loading data from CSV files, and executing a simple MATCH query. Ensure the 'include/lb.hpp' header is accessible and the Ladybug library is linked. ```cpp // main.cpp #include #include "include/lb.hpp" using namespace lbug::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.lbug remove("example.lbug"); remove("example.lb.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.lbug", 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 and Query Database (Node.js) Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/get-started/index.mdx Creates an on-disk database, defines node and relationship tables, loads data from CSV, and executes a Cypher query. Prints all rows from the query result. ```javascript // main.js const lbug = require("lbug"); (async () => { // Create an empty on-disk database and connect to it const db = new lb.Database("example.lbug"); const conn = new lb.Connection(db); // Create the tables await conn.query("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)"); await conn.query("CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)"); 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 the data await conn.query('COPY User FROM "./data/user.csv"'); await conn.query('COPY City FROM "./data/city.csv"'); await conn.query('COPY Follows FROM "./data/follows.csv"'); await conn.query('COPY LivesIn FROM "./data/lives-in.csv"'); const queryResult = await conn.query("MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;"); // Get all rows from the query result const rows = await queryResult.getAll(); // Print the rows for (const row of rows) { console.log(row); } })(); ``` ```json { "a.name": "Adam", "f.since": 2020, "b.name": "Karissa" } { "a.name": "Adam", "f.since": 2020, "b.name": "Zhang" } { "a.name": "Karissa", "f.since": 2021, "b.name": "Zhang" } { "a.name": "Zhang", "f.since": 2022, "b.name": "Noura" } ``` -------------------------------- ### Start On-Disk Database CLI Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/client-apis/cli.mdx Use this command to open an on-disk database. The database directory will be created if it doesn't exist. Data is persisted after the shell closes. ```bash $ lbug example.lbug ``` ```text Opened the database example.lbug in read-write mode. Enter ":help" for usage hints. lbug> ``` -------------------------------- ### JSON Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/import/copy-from-json.md Example JSON structure for person data. ```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" } ] ``` -------------------------------- ### Insert Nodes and Edges Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/extensions/algo/louvain.mdx Populate the graph database with nodes and relationships. This example creates users and their connections. ```cypher 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'}) (u0)-[:KNOWS]->(u1), (u0)-[:KNOWS]->(u2), (u1)-[:KNOWS]->(u2), (u0)-[:KNOWS]->(u3), (u1)-[:KNOWS]->(u3), (u2)-[:KNOWS]->(u3), (u4)-[:KNOWS]->(u5), (u4)-[:KNOWS]->(u6), (u5)-[:KNOWS]->(u6), (u4)-[:KNOWS]->(u7), (u5)-[:KNOWS]->(u7), (u6)-[:KNOWS]->(u7), (u3)-[:KNOWS]->(u4); ``` -------------------------------- ### Build Production Site Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Builds the production-ready version of the site, outputting to the ./dist/ directory. ```bash npm run build ``` -------------------------------- ### JSON Data Example for Conditions Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/import/copy-from-json.md Example JSON structure for medical condition data. ```json // condition.json [ { "c_id": "c1", "name": "Diabetes" }, { "c_id": "c2", "name": "Hypertension" } ] ``` -------------------------------- ### Initialize Ladybug Database and Connection in Python Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/import/icebug.md Set up a Ladybug database and connection object in Python, assuming an existing icebug graph. ```python import ladybug as lb # get icebug graph from earlier step db = lb.Database() conn = lb.Connection(db) ``` -------------------------------- ### RECURSIVE_REL structure example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/cypher/data-types/index.mdx This is an example of the internal structure of a RECURSIVE_REL, showing nodes and relationships. ```json {_NODES: [{_ID: 0:0, _LABEL: User, name: Adam, age: 30},{_ID: 0:1, _LABEL: User, name: Karissa, age: 40}], _RELS: [(0:0)-{_LABEL: Follows, _ID: 2:0, since: 2020}->(0:1)]} ``` -------------------------------- ### Tab Synchronization Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Demonstrates how to use 'syncKey' with Tabs and TabItem components to synchronize tab selections across different tab groups. ```jsx ``` -------------------------------- ### LIKES Relationship Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Example data for the LIKES relationship, indicating userID and postID. ```csv userID,postID 16,1 2,1 4,1 13,1 11,1 ``` -------------------------------- ### Initialize Database Connection for Queries Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/python/index.mdx This script sets up a connection to a Ladybug database named 'social_network.lbug'. It includes a placeholder for executing a query, which would be filled in with specific SQL statements. ```python import ladybug as lb def main() -> None: db = lb.Database("social_network.lbug") conn = lb.Connection(db) # Query to be filled out below result = conn.execute(...) for row in result: print(row) if __name__ == "__main__": main() ``` -------------------------------- ### POSTS Relationship Data Example Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/example-database.md Example data for the POSTS relationship, indicating userID and postID. ```csv userID,postID 17,1 4,2 15,3 7,4 14,5 ``` -------------------------------- ### Create Sample Data for UDF Application Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/client-apis/python.mdx Prepare the database by creating a table and inserting sample data to be used with User-Defined Functions (UDFs). This step is necessary before applying UDFs in queries. ```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") ``` -------------------------------- ### Preview Production Build Locally Source: https://github.com/ladybugdb/ladybug-docs/blob/main/README.md Allows you to preview the production build locally before deploying. ```bash npm run preview ``` -------------------------------- ### Download and Unzip Tutorial Data Source: https://github.com/ladybugdb/ladybug-docs/blob/main/src/content/docs/tutorials/python/index.mdx Downloads the necessary tutorial data using curl and unzips it. Removes the zip file after extraction. ```bash curl -o tutorial_data.zip https://huggingface.co/datasets/ladybugdb/python-tutorial/resolve/main/tutorial_data.zip unzip tutorial_data.zip rm tutorial_data.zip ```