### Install Ladybug and Activate Virtual Environment Source: https://docs.ladybugdb.com/tutorials/python Sets up a Python virtual environment and installs the Ladybug library. Ensure Python is installed and use this for initial project setup. ```bash python -m venv .venv source .venv/bin/activate pip install ladybug ``` -------------------------------- ### Install an Extension Source: https://docs.ladybugdb.com/extensions Install an official extension from the server. This only needs to be done once per extension. ```sql INSTALL ; ``` -------------------------------- ### Run PostgreSQL Server with Docker Source: https://docs.ladybugdb.com/extensions/attach/postgres Starts a PostgreSQL server locally using Docker. Ensure you have Docker installed and running. ```bash docker run --rm --name lbug-postgres \ -e POSTGRES_PASSWORD=testpassword \ -p 5432:5432 \ postgres:latest ``` -------------------------------- ### Start On-Disk Database Source: https://docs.ladybugdb.com/client-apis/cli Starts the Ladybug CLI with an on-disk database. If the directory does not exist, it will be created. ```bash $ lbug example.lbug ``` ```text Opened the database example.lbug in read-write mode. Enter ":help" for usage hints. lbug> ``` -------------------------------- ### Install asyncpg Python Library Source: https://docs.ladybugdb.com/extensions/attach/postgres Installs the asyncpg library, an asynchronous PostgreSQL client for Python, used for interacting with the database. ```bash pip install asyncpg ``` -------------------------------- ### Configure Icebug Disk with S3 Storage Source: https://docs.ladybugdb.com/import/icebug Example of creating node and relationship tables for icebug-disk format, specifying an S3 URI for storage. Ensure the `httpfs` extension is installed and configured. ```cypher CREATE NODE TABLE city(id INT32, name STRING, population INT64, PRIMARY KEY(id)) WITH (storage = 's3://my-bucket/mygraph/', format = 'icebug-disk'); CREATE REL TABLE livesin(FROM user TO city) WITH (storage = 's3://my-bucket/mygraph/', format = 'icebug-disk'); ``` -------------------------------- ### Install and Load ADBC Extension Source: https://docs.ladybugdb.com/extensions/adbc Install and load the ADBC extension in LadybugDB before attaching databases. ```sql INSTALL adbc; LOAD adbc; ``` -------------------------------- ### Install and Load Vector Extension Source: https://docs.ladybugdb.com/extensions/vector Installs and loads the vector extension. This is a prerequisite for using vector-related functionalities. ```Python conn.execute("INSTALL VECTOR;") conn.execute("LOAD VECTOR;") ``` -------------------------------- ### Query Results from C++ Example Source: https://docs.ladybugdb.com/get-started/prepared-statements This shows the expected output after running the C++ prepared statement example. It displays the nodes created and queried from the database. ```text n.name | n.age | n.embedding Alice | 25 | [10, 20, 30] Bob | 30 | [40, 50.1, 60] ``` -------------------------------- ### C++ LadybugDB Prepared Statement Example Source: https://docs.ladybugdb.com/get-started/prepared-statements This C++ example demonstrates how to set up a LadybugDB database, create a table, insert nodes using prepared statements with parameters, and query the data. Ensure you have the LadybugDB C++ client library correctly set up. ```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; } ``` -------------------------------- ### Python Example: Query Vector Index with Sentence Transformers Source: https://docs.ladybugdb.com/extensions/vector This Python snippet demonstrates how to install and load the vector extension, initialize a Sentence Transformer model for embeddings, and query a vector index. It shows how to pass Python variables to SQL queries. ```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()) ``` -------------------------------- ### Install Nightly Build for Node.js Source: https://docs.ladybugdb.com/installation Install the next version of the Ladybug Node.js package using npm. ```bash npm i @ladybugdb/core@next ``` -------------------------------- ### Install and Load LLM Extension with API Key Source: https://docs.ladybugdb.com/extensions/vector Installs and loads the LLM extension and sets the OpenAI API key. Ensure you replace the placeholder with your actual API key. ```Python conn.execute("INSTALL llm; LOAD llm;") os.environ["OPENAI_API_KEY"] = "sk-proj-key" # Replace with your own OpenAI API key ``` -------------------------------- ### Start In-Memory Database Source: https://docs.ladybugdb.com/client-apis/cli Starts the Ladybug CLI with an in-memory database by omitting the path. ```bash lbug ``` ```text Opened the database under in-memory mode. Enter ":help" for usage hints. lbug> ``` -------------------------------- ### Download and Unzip Example Dataset Source: https://docs.ladybugdb.com/extensions/attach/iceberg This snippet shows how to download and extract an example Iceberg dataset for use with LadybugDB. ```bash cd /tmp wget https://lbugdb.github.io/data/iceberg-extension/iceberg_tables.zip unzip iceberg_tables.zip ``` -------------------------------- ### Set up Unity Catalog Server Source: https://docs.ladybugdb.com/extensions/attach/unity Clone the Unity Catalog repository and start the server. This is a prerequisite for using the extension. ```bash git clone https://github.com/unitycatalog/unitycatalog.git bin/start-uc-server ``` -------------------------------- ### Install Nightly Build for Python Source: https://docs.ladybugdb.com/installation Install the pre-release version of the Ladybug Python package using uv pip. ```bash uv pip install --pre ladybug ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.ladybugdb.com/developer-guide Installs the required Node.js dependencies for building the Node.js bindings. Ensure Node.js version 14.15.0 or later is installed. ```bash make nodejs-deps ``` -------------------------------- ### Install Ladybug Library using CMake Source: https://docs.ladybugdb.com/client-apis/c Commands to build and install the Ladybug library using CMake. The dynamic library and header can be installed to a specified prefix, making them usable with other build systems. ```bash cmake -B build cmake --build build cmake --install build --prefix '' ``` -------------------------------- ### Install Python API Requirements Source: https://docs.ladybugdb.com/developer-guide Installs the necessary dependencies for the Python API. Ensure you have Python development headers installed. ```bash make -C tools/python_api requirements ``` -------------------------------- ### Install yFiles Jupyter Graphs for Ladybug with uv Source: https://docs.ladybugdb.com/visualization/third-party-integrations/yfiles Installs the ladybug and yfiles-jupyter-graphs-for-kuzu packages using uv. Ensure lbug is installed as a pre-requisite. ```bash # Install lbug as a pre-requisite uv init uv add ladybug yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### Install Ladybug and Dependencies Source: https://docs.ladybugdb.com/get-started/graph-algorithms Installs the necessary dependencies for working with Ladybug and graph algorithms. ```bash uv init uv add lbug polars pyarrow networkx numpy scipy ``` -------------------------------- ### Link Ladybug from Source with CMake (FetchContent) Source: https://docs.ladybugdb.com/client-apis/c Example using FetchContent to download and build Ladybug as a dependency within a CMake project. It links the library statically or dynamically to an example executable, configurable via the EXAMPLE_SHARED option. ```cmake cmake_minimum_required(VERSION 3.11) project(example LANGUAGES C CXX) set(BUILD_SHELL FALSE) include(FetchContent) FetchContent_Declare(lbug URL https://github.com/LadybugDB/ladybug/archive/refs/tags/v0.5.0.zip URL_HASH SHA256=47ff308079cbbfeccc38eeb1c5f455a8c00f9294034141b9084387518f0bbed9 ) FetchContent_MakeAvailable(lbug) add_executable(example main.c) option(EXAMPLE_SHARED "Use dynamic linking" TRUE) if (EXAMPLE_SHARED) target_link_libraries(example lbug_shared) else() target_link_libraries(example lbug) endif() ``` -------------------------------- ### Attach Example PostgreSQL Database Source: https://docs.ladybugdb.com/extensions/attach/postgres Example of attaching a PostgreSQL database named 'university' to Ladybug with the alias 'uw'. ```sql ATTACH 'dbname=university user=postgres host=localhost password=testpassword port=5432' AS uw (dbtype postgres); ``` -------------------------------- ### Java: Gradle Project Structure Source: https://docs.ladybugdb.com/get-started Example Gradle project structure for a Java application using LadybugDB. ```text ├── build.gradle ├── src/main │   ├── java │   │   └── Main.java │   └── resources │   │   └── user.csv │   │   └── city.csv │   │   └── follows.csv │   │   └── lives-in.csv ``` -------------------------------- ### Install LadybugDB with pip Source: https://docs.ladybugdb.com/get-started Install the LadybugDB Python client using pip. This is the first step to using LadybugDB in your project. ```bash pip install polars ``` -------------------------------- ### Install Build Dependencies on Ubuntu Source: https://docs.ladybugdb.com/developer-guide Installs necessary build tools including CMake, GCC, Python, Ninja, and ccache on Ubuntu. ```bash apt update apt install -y build-essential cmake gcc g++ python3 ninja-build ccache ``` -------------------------------- ### Install Delta Lake and Pandas Source: https://docs.ladybugdb.com/extensions/attach/delta Install the necessary Python packages for working with Delta Lake and Pandas. ```bash pip install deltalake pandas ``` -------------------------------- ### Running a Specific Test File with e2e_test Source: https://docs.ladybugdb.com/developer-guide/testing-framework Example of running all tests from a specific .test file using the e2e_test binary. ```bash # Run all tests from test/test_files/long_string_pk.test file $ ./e2e_test long_string_pk/long_string_pk.test ``` -------------------------------- ### Install Build Dependencies on Windows Source: https://docs.ladybugdb.com/developer-guide Installs Python, Make, and Ninja using Chocolatey package manager on Windows. ```powershell choco install -y python3 make ninja ``` -------------------------------- ### Install ADBC Drivers Source: https://docs.ladybugdb.com/extensions/adbc Install common ADBC drivers using pip. Ensure the driver library is available on your system. ```bash # PostgreSQL pip install adbc-driver-postgresql # DuckDB pip install adbc-driver-duckdb # SQLite pip install adbc-driver-sqlite # Snowflake pip install adbc-driver-snowflake ``` -------------------------------- ### Install and Load HTTPFS Extension Source: https://docs.ladybugdb.com/import/icebug Install and load the `httpfs` extension in Ladybug, which is required for accessing remote storage like S3. This also includes setting up S3 credentials. ```sql INSTALL httpfs; LOAD httpfs; CALL s3_credential( key_id='YOUR_KEY_ID', secret='YOUR_SECRET', region='us-east-1' ); ``` -------------------------------- ### Less Than Operator Example Source: https://docs.ladybugdb.com/cypher/expressions/comparison-operators Demonstrates the use of the less than operator (<). ```text 2 < 3 ``` -------------------------------- ### Running All Tests in a Directory with e2e_test Source: https://docs.ladybugdb.com/developer-guide/testing-framework Example of running all tests within a specified directory using the e2e_test binary. ```bash # Run all tests inside test/test_files/copy $ ./e2e_test copy ``` -------------------------------- ### Install Build Dependencies on AlmaLinux Source: https://docs.ladybugdb.com/developer-guide Installs necessary build tools including CMake, GCC, Python, Ninja, and ccache on AlmaLinux. ```bash dnf update dnf install -y cmake gcc gcc-c++ python3 ninja-build ccache ``` -------------------------------- ### Install and Load Ladybug Algo Extension Source: https://docs.ladybugdb.com/get-started/graph-algorithms Installs and loads the 'algo' extension for running 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;") ``` -------------------------------- ### ResultSet Example Source: https://docs.ladybugdb.com/developer-guide/database-internal/vector Demonstrates a ResultSet as a Cartesian product of DataChunks, forming a comprehensive dataset. ```text Result set Data chunk Value vector: [1, 2, 3] Value vector: [a, b, c] Data Chunk Value vector: [10, 11] Data being represented: [(1,a,10), (2,b,10), (3,c,10), (1,a,11), (2,b,11), (3,c,11)] ``` -------------------------------- ### Install Ladybug Python Client with Nix Source: https://docs.ladybugdb.com/installation Installs the Ladybug Python client library using Nix. This command creates a development shell with Python and the Ladybug package available. ```shell nix-shell -p "python3.withPackages (ps: [ ps.lbug ])" ``` -------------------------------- ### Less Than or Equal To Operator Example Source: https://docs.ladybugdb.com/cypher/expressions/comparison-operators Demonstrates the use of the less than or equal to operator (<=). ```text 3 <= 3 ``` -------------------------------- ### Download Example Data Source: https://docs.ladybugdb.com/tutorials/example-database Use curl to download the zipped tutorial data. Unzip the downloaded file 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 ``` -------------------------------- ### Type Of Function Example Source: https://docs.ladybugdb.com/cypher/expressions/utility-functions Use the typeof function to get the name of the data type of an argument. ```cypher typeof(true) ``` -------------------------------- ### Install Ladybug for Windows (x86_64) Source: https://docs.ladybugdb.com/installation Download the Ladybug binary for x86_64 Windows systems. ```bash curl -L -O https://github.com/LadybugDB/ladybug/releases/download/v0.11.0/liblbug-windows-x86_64.zip ``` -------------------------------- ### C++ Example: Connect, Create Schema, Load Data, and Query Source: https://docs.ladybugdb.com/get-started This C++ code demonstrates how to connect to an on-disk Ladybug database, create node and relationship tables, load data from CSV files, and execute a sample query. Ensure the 'include' and 'lib' directories are correctly set up. ```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; } ``` -------------------------------- ### Python: Query Data and Get as PyArrow Table Source: https://docs.ladybugdb.com/get-started Execute a Cypher query and retrieve the results as a pyarrow Table. Ensure pyarrow is installed. ```python import pyarrow 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]] ``` -------------------------------- ### Install Build Dependencies on Arch Linux Source: https://docs.ladybugdb.com/developer-guide Installs necessary build tools including base-devel, CMake, GCC, Python, Ninja, and ccache on Arch Linux. ```bash pacman -Syu pacman -S --needed base-devel cmake gcc python ninja ccache ``` -------------------------------- ### Initialize Project with Swift Package Manager Source: https://docs.ladybugdb.com/get-started Sets up a new Swift project for LadybugDB interaction. This involves creating a directory, initializing a Swift package, and updating its dependencies. ```bash mkdir lbug-swift-example cd lbug-swift-example swift package init --type=executable ``` -------------------------------- ### Install Ladybug Wasm Core Source: https://docs.ladybugdb.com/client-apis/wasm Install the Ladybug Wasm core package using npm. This is the first step to using Ladybug's WebAssembly capabilities. ```bash npm i @ladybugdb/wasm-core ``` -------------------------------- ### DataChunk Example Source: https://docs.ladybugdb.com/developer-guide/database-internal/vector Illustrates a DataChunk as a collection of ValueVectors representing a structured dataset. ```text Data chunk Value vector: [1, 2, 3] Value vector: [a, b, c] Data being represented: [(1,a), (2,b), (3,c)] ``` -------------------------------- ### Install yFiles Jupyter Graphs for Ladybug with pip Source: https://docs.ladybugdb.com/visualization/third-party-integrations/yfiles Installs the ladybug and yfiles-jupyter-graphs-for-kuzu packages using pip. Ensure lbug is installed as a pre-requisite. ```bash # Install lbug as a pre-requisite pip install ladybug yfiles-jupyter-graphs-for-kuzu ``` -------------------------------- ### Open On-Disk Database with Ladybug CLI Source: https://docs.ladybugdb.com/get-started Start the Ladybug CLI and open an existing on-disk database file. ```bash lbug example.lbug ``` -------------------------------- ### Icebug Disk Output Schema Example Source: https://docs.ladybugdb.com/import/icebug Example of the Cypher schema file generated for icebug-disk format. It defines node and relationship tables with their respective columns and storage configurations. ```cypher CREATE NODE TABLE city(id INT32, name STRING, population INT64, PRIMARY KEY(id)) WITH (storage = '', format = 'icebug-disk'); CREATE NODE TABLE user(id INT32, name STRING, age INT64, PRIMARY KEY(id)) WITH (storage = '', format = 'icebug-disk'); CREATE REL TABLE follows(FROM user TO user, since INT32) WITH (storage = '', format = 'icebug-disk'); CREATE REL TABLE livesin(FROM user TO city) WITH (storage = '', format = 'icebug-disk'); ``` -------------------------------- ### Install Ladybug Node.js Client Source: https://docs.ladybugdb.com/installation Installs the Ladybug Node.js client library using npm, the Node Package Manager. This command adds the @ladybugdb/core package to your project's dependencies. ```shell npm install @ladybugdb/core ``` -------------------------------- ### Install Ladybug CLI with Homebrew Source: https://docs.ladybugdb.com/installation Installs the Ladybug CLI using the Homebrew package manager on macOS. Ensure Homebrew is installed before running this command. ```shell brew install ladybug ``` -------------------------------- ### Install Ladybug Python Client with uv Source: https://docs.ladybugdb.com/installation Initializes a project with uv and adds the Ladybug Python client library. This is a modern approach for managing Python dependencies. ```shell uv init uv add ladybug ``` -------------------------------- ### Load an Official Extension Source: https://docs.ladybugdb.com/extensions Load an installed official extension into the current session to make its functionality available. ```sql load json; ``` -------------------------------- ### Install Ladybug CLI with Shell Script Source: https://docs.ladybugdb.com/installation Installs the Ladybug CLI using a curl command to download and execute an installation script. This is a common method for Linux and macOS. ```shell curl -s https://install.ladybugdb.com | bash ``` -------------------------------- ### Building Extension Tests Source: https://docs.ladybugdb.com/developer-guide/testing-framework Command to build extension tests, which may require installing DuckDB. ```bash # Build extension tests. You would need to install DuckDB to build the extension tests. See https://duckdb.org/install/ $ make extension-test-build ``` -------------------------------- ### Automatic Test Result Rewriting (Setup) Source: https://docs.ladybugdb.com/developer-guide/testing-framework Illustrates the initial state of a test file before automatic test result rewriting is applied. ```bash $ cat test/test_files/demo.test -DATASET CSV empty -- -CASE demo -STATEMENT CREATE NODE TABLE A(ID SERIAL PRIMARY KEY, name STRING); ---- ok -STATEMENT CREATE (:A), (:A {name: 'Alice'}); ---- ok -STATEMENT CREATE (:A), (:A {name: 'Alice'}), (:A {name: 'Bob'}); ---- ok -STATEMENT MATCH (n) RETURN n.name; ---- 0 ``` -------------------------------- ### Install Ladybug Python Client with pip Source: https://docs.ladybugdb.com/installation Installs the Ladybug Python client library using pip, the standard Python package installer. This command is compatible with Linux, macOS, and Windows. ```shell pip install ladybug ``` -------------------------------- ### Install Ladybug for Linux (aarch64) Source: https://docs.ladybugdb.com/installation Download and extract the Ladybug binary for aarch64 Linux systems. ```bash curl -L -O https://github.com/LadybugDB/ladybug/releases/download/v0.11.0/liblbug-linux-aarch64.tar.gz tar xzf liblbug-*.tar.gz ``` -------------------------------- ### GTest Test Registration Example Source: https://docs.ladybugdb.com/developer-guide/testing-framework Illustrates how a basic test case from a .test file is registered as a GTest test. ```cpp TEST_F(basic, e2e_test_BasicTest) { ... } ``` -------------------------------- ### Launch Ladybug Explorer with Existing Database Source: https://docs.ladybugdb.com/visualization/lbug-explorer Use this command to launch Ladybug Explorer and connect to an existing Ladybug database file. Mount the local directory containing the database to `/database` and specify the database file name using `LBUG_FILE`. Changes in the UI will persist to this file. ```bash docker run -p 8000:8000 \ -v {path to the directory containing the database file}:/database \ -e LBUG_FILE={database file name} \ --rm ghcr.io/ladybugdb/explorer:latest ``` -------------------------------- ### Update an Installed Extension Source: https://docs.ladybugdb.com/extensions Re-download an extension if it is not working properly or if you need to ensure you have the latest version. ```sql UPDATE ; ``` -------------------------------- ### Set Default Database and Load Data Source: https://docs.ladybugdb.com/extensions/attach/postgres Attach a PostgreSQL database with an alias and set it as the default to simplify queries. This example loads all data from the 'person' table. ```sql ATTACH 'university' AS uw (dbtype postgres); USE uw; LOAD FROM person RETURN *; ``` -------------------------------- ### Load from JSON file Source: https://docs.ladybugdb.com/cypher/query-clauses/load-from Scan a JSON file directly using the LOAD FROM clause after installing the JSON extension. ```sql INSTALL json; LOAD json; // Scan the JSON file LOAD FROM "user.json" RETURN *; ``` -------------------------------- ### JSON Data Example Source: https://docs.ladybugdb.com/import/copy-from-json This is an example of a JSON file structure that can be imported into a Ladybug node table. ```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" } ] ``` -------------------------------- ### Start Ladybug with Icebug Disk Schema Source: https://docs.ladybugdb.com/import/icebug Launch Ladybug and specify the generated schema file using the `-i` flag to load the icebug-disk graph. ```bash lbug -i csr_graph/schema.cypher ``` -------------------------------- ### Async Node.js API Example Source: https://docs.ladybugdb.com/client-apis/nodejs Demonstrates creating a database, defining tables, loading data from CSV files, and executing a MATCH query using the asynchronous Node.js API. This is the default and most common approach. ```javascript const lbug = require("@ladybugdb/core"); (async () => { // Create an empty on-disk database and connect to it const db = new lbug.Database("example.lbug"); const conn = new lbug.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); } })(); ``` -------------------------------- ### Create a Sample SQLite Database Source: https://docs.ladybugdb.com/extensions/attach/sqlite This Python script creates a SQLite database named 'university.db' with a 'person' table and populates it with sample data. ```python import sqlite3 conn = sqlite3.connect('university.db') cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS person (name VARCHAR, age INTEGER);") cursor.execute("INSERT INTO person (name, age) VALUES ('Alice', 30);") cursor.execute("INSERT INTO person (name, age) VALUES ('Bob', 27);") cursor.execute("INSERT INTO person (name, age) VALUES ('Carol', 19);") cursor.execute("INSERT INTO person (name, age) VALUES ('Dan', 25);") conn.commit() conn.close() ``` -------------------------------- ### Get Month Name from Date Source: https://docs.ladybugdb.com/cypher/expressions/date-functions Use `monthname` to get the English name of the month for a given date. ```cypher monthname(DATE('2022-11-07')) ``` -------------------------------- ### Initialize Ladybug Database and Connection Source: https://docs.ladybugdb.com/tutorials/rust Create a new Ladybug database file and establish a connection to it. This snippet is part of the `create_db.rs` file for setting up the database. ```rust use lbug::{Connection, Database, Error, SystemConfig}; fn main() -> Result<(), Error> { // Rest of the code goes here. Ok(()) } ``` ```rust let db = Database::new("social_network.lbug", SystemConfig::default())?; let conn = Connection::new(&db)?; ``` -------------------------------- ### Running Specific Test File with ctest Source: https://docs.ladybugdb.com/developer-guide/testing-framework Example of running all tests from a specific .test file using ctest -R. ```bash # First cd to build/relwithdebinfo/test $ cd build/relwithdebinfo/test # Run all tests from test/test_files/common/types/interval.test $ ctest -R common~types~interval ``` -------------------------------- ### Initialize Database Connection and DataFrame Source: https://docs.ladybugdb.com/import/copy-from-subquery Sets up a Ladybug database connection and creates a Pandas DataFrame for data import. ```Python import ladybug as lb import pandas as pd db = lb.Database("example.lbug") conn = lb.Connection(db) df = pd.DataFrame({ "name": ["Adam", "Karissa", "Zhang", "Noura"], "age": [30, 40, 50, 25] }) ``` -------------------------------- ### Create Example Dataset Tables and Data Source: https://docs.ladybugdb.com/extensions/algo This snippet creates the necessary node and relationship tables ('Person', 'KNOWS') and populates them with sample data for use in graph projections and 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); ``` -------------------------------- ### Get Day Name from Date Source: https://docs.ladybugdb.com/cypher/expressions/date-functions Use `dayname` to get the English name of the day of the week for a given date. ```cypher dayname(DATE('2022-11-07')) ``` -------------------------------- ### Display CLI Help Menu Source: https://docs.ladybugdb.com/client-apis/cli Lists all available shell commands and options for the Ladybug CLI. ```bash $ lbug -h lbug [databasePath] {OPTIONS} Lbug shell OPTIONS: databasePath Path to the database. If not given or set to ":memory:", the database will be opened under in-memory mode. -h, --help Display this help menu -d, --default_bp_size, --defaultbpsize Size of buffer pool for default and large page sizes in megabytes --max_db_size=[max_db_size], --maxdbsize=[max_db_size] Maximum size of the database in bytes --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 -b, --no_progress_bar, --noprogressbar Disable query progress bar -w, --ignore_wal_replay_errors By default something goes wrong when replaying the WAL an exception will be thrown. With this flag enabled we will instead ignore these errors and stop replaying the WAL. -i, --init Path to file with script to run on startup "--" can be used to terminate flag options and force all following arguments to be treated as positional options ``` -------------------------------- ### Create Schema and Load Data in Rust Source: https://docs.ladybugdb.com/get-started Demonstrates creating node and relationship tables, and then loading data from CSV files using Rust. Ensure pyarrow is installed for CSV operations. ```rust 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'")?; ``` -------------------------------- ### Download and Unzip Tutorial Data Source: https://docs.ladybugdb.com/tutorials/python Downloads the social network dataset and extracts the CSV files. This step is necessary to obtain the data for the tutorial. ```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 ``` -------------------------------- ### Sync Node.js API Example Source: https://docs.ladybugdb.com/client-apis/nodejs Illustrates creating a database, defining tables, loading data, and executing a MATCH query using the synchronous Node.js API. This is useful in contexts where asynchronous operations are not desired. ```javascript const lbug = require("@ladybugdb/core"); // Create an empty on-disk database and connect to it const db = new lbug.Database("example.lbug"); const conn = new lbug.Connection(db); // Create the tables conn.querySync("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)"); conn.querySync("CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)"); conn.querySync("CREATE REL TABLE Follows(FROM User TO User, since INT64)"); conn.querySync("CREATE REL TABLE LivesIn(FROM User TO City)"); // Load the data conn.querySync('COPY User FROM "./data/user.csv"'); conn.querySync('COPY City FROM "./data/city.csv"'); conn.querySync('COPY Follows FROM "./data/follows.csv"'); conn.querySync('COPY LivesIn FROM "./data/lives-in.csv"'); const queryResult = conn.querySync( """ MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name; """); // Get all rows from the query result const rows = queryResult.getAllSync(); // Print the rows for (const row of rows) { console.log(row); } ``` -------------------------------- ### Launch Ladybug Explorer with Empty Database Source: https://docs.ladybugdb.com/visualization/lbug-explorer Launch Ladybug Explorer with a default empty database. This is useful for exploring bundled datasets and basic functionalities without needing a pre-existing database file. The server will start with an empty `database.kz` if no file is specified. ```bash docker run -p 8000:8000 --rm ghcr.io/ladybugdb/explorer:latest ``` -------------------------------- ### Polars DataFrame Output Example Source: https://docs.ladybugdb.com/get-started This is an example of the output format when retrieving query results as a Polars DataFrame. It shows the schema and data. ```text shape: (4, 3) ┌─────────┬─────────┬─────────┐ │ a.name ┆ b.name ┆ f.since │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞═════════╪═════════╪═════════╡ │ Adam ┆ Karissa ┆ 2020 │ │ Adam ┆ Zhang ┆ 2020 │ │ Karissa ┆ Zhang ┆ 2021 │ │ Zhang ┆ Noura ┆ 2022 │ └─────────┴─────────┴─────────┘ ``` -------------------------------- ### Create Embedding with OpenAI Source: https://docs.ladybugdb.com/extensions/llm Example of creating an embedding using OpenAI. No additional provider-specific arguments are shown as required in this basic example. ```cypher RETURN CREATE_EMBEDDING( "Hello world", "openai", "text-embedding-3-small"); ``` -------------------------------- ### Node.js: Create Schema, Load Data, and Query Source: https://docs.ladybugdb.com/get-started Demonstrates creating a graph schema, loading data from CSV files, and executing a query using the Node.js client. Ensure the 'lbug' package is installed. ```javascript 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" } ``` -------------------------------- ### Create Embedding with Ollama Source: https://docs.ladybugdb.com/extensions/llm Example of creating an embedding using Ollama. No additional provider-specific arguments are shown as required in this basic example. ```cypher RETURN CREATE_EMBEDDING("Hello world", "ollama", "nomic-embed-text"); ``` -------------------------------- ### Integrate Pre-built Library with CMake Source: https://docs.ladybugdb.com/client-apis/c Configuration example for integrating a pre-built LadybugDB C library into a CMake project. Ensure to substitute URL, URL_HASH, and library filenames for your specific platform. ```cmake cmake_minimum_required(VERSION 3.11) project(example LANGUAGES C) ExternalProject_Add(lbug-prebuilt URL https://github.com/LadybugDB/ladybug/releases/download/v0.11.0/liblbug-linux-x86_64.tar.gz ) ExternalProject_Get_Property(lbug-prebuilt SOURCE_DIR) add_library(lbug SHARED IMPORTED) add_dependencies(lbug lbug-prebuilt) set_target_properties(lbug PROPERTIES IMPORTED_LOCATION ${SOURCE_DIR}/liblbug.so) target_include_directories(lbug INTERFACE ${SOURCE_DIR}) add_executable(example main.c) target_link_libraries(example lbug) ``` -------------------------------- ### Install Build Dependencies on macOS Source: https://docs.ladybugdb.com/developer-guide Installs Xcode command-line tools and Homebrew packages including CMake, Python, Ninja, and ccache on macOS. ```bash xcode-select --install brew install cmake python ninja ccache ``` -------------------------------- ### Getting List Length in Cypher Source: https://docs.ladybugdb.com/cypher/expressions/list-functions Demonstrates using the `size()` function to get the number of elements in a list. This is useful for iteration or conditional logic. ```cypher RETURN size([1, 2, 3]) // Returns 3 ``` -------------------------------- ### Set Default Database and Load Data Source: https://docs.ladybugdb.com/extensions/attach/duckdb This example shows how to attach a DuckDB database with an alias, set it as the default database using the 'USE' statement, and then load data from a table without specifying the database prefix. ```sql ATTACH 'university.db' AS uw (dbtype duckdb); USE uw; LOAD FROM person RETURN *; ``` -------------------------------- ### Create a Sample DuckDB Database Source: https://docs.ladybugdb.com/extensions/attach/duckdb This Python code snippet demonstrates how to create a DuckDB database file named 'university.db' and populate it with a 'person' table containing names and ages. ```python import duckdb conn = duckdb.connect('university.db') conn.execute("CREATE TABLE IF NOT EXISTS person (name VARCHAR, age INTEGER);") conn.execute("INSERT INTO person VALUES ('Alice', 30);") conn.execute("INSERT INTO person VALUES ('Bob', 27);") conn.execute("INSERT INTO person VALUES ('Carol', 19);") conn.execute("INSERT INTO person VALUES ('Dan', 25);") ``` -------------------------------- ### Create Embedding with Voyage AI Source: https://docs.ladybugdb.com/extensions/llm Example of creating an embedding using Voyage AI. No additional provider-specific arguments are shown as required in this basic example. ```cypher RETURN CREATE_EMBEDDING( "Hello world", "voyageai", "voyage-3-large"); ``` -------------------------------- ### Create Embedding with Google Gemini Source: https://docs.ladybugdb.com/extensions/llm Example of creating an embedding using Google Gemini. No additional provider-specific arguments are shown as required in this basic example. ```cypher RETURN CREATE_EMBEDDING("Hello world", "google-gemini", "gemini-embedding-exp-03-07"); ``` -------------------------------- ### Rust: Install Ladybug Crate Source: https://docs.ladybugdb.com/get-started Instructions for installing the Ladybug Rust crate via Cargo. It builds Ladybug's C++ library from source by default. ```rust 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 conn.query("CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)")?; ```