### Install Ryugraph and Setup Virtual Environment Source: https://ryugraph-docs.vercel.app/tutorials/python Installs Ryugraph and activates a Python virtual environment using pip. Ensure Python is installed and this script is run within the project directory. ```bash python -m venv .venv source .venv/bin/activate pip install ryugraph ``` -------------------------------- ### Add Ryu Go Client using go get Source: https://ryugraph-docs.vercel.app/installation Add the Ryugraph Go client library as a dependency to your Go project. This command assumes you have already initialized a Go project with a `go.mod` file. ```shell go get github.com/predictable-labs/go-ryugraph@v0.11.0 ``` -------------------------------- ### Swift: Initialize Project, Add Dependency, and Query Ryugraph Source: https://ryugraph-docs.vercel.app/get-started This Swift example guides through setting up a new Swift project, adding the `ryugraph-swift` library as a dependency, and then writing code to connect to a Ryugraph database, define the schema, load data, and execute a Cypher query. It includes instructions for building the project. ```bash mkdir ryugraph-swift-example cd ryugraph-swift-example swift package init --type=executable ``` ```swift import PackageDescription let package = Package( name: "ryugraph-swift-example", platforms: [ .macOS(.v11), .iOS(.v14), ], dependencies: [ .package(url: "https://github.com/predictable-labs/ryugraph-swift/", branch: "0.11.0"), ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products from dependencies. .executableTarget( name: "ryugraph-swift-example", dependencies: [ .product(name: "Ryugraph", package: "ryugraph-swift"), ] ), ] ) ``` ```swift import Ryugraph // Create an empty on-disk database and connect to it let db = try! Database("example.ryugraph") 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/ryugraph-swift-example . ``` -------------------------------- ### Run Ryugraph Swift Example Source: https://ryugraph-docs.vercel.app/get-started Executes a pre-compiled Swift example for Ryugraph. Assumes the executable is in the current directory. The output shows example data retrieved from the database. ```bash ./ryugraph-swift-example ``` -------------------------------- ### Create Example Dataset for Ryugraph Source: https://ryugraph-docs.vercel.app/extensions/algo This Cypher code snippet creates node and relationship tables ('Person' and 'KNOWS') and populates them with sample data. This setup is used for demonstrating projected graphs and running algorithms in Ryugraph. ```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); ``` -------------------------------- ### Setup Rust Project and Add Ryugraph Dependency Source: https://ryugraph-docs.vercel.app/tutorials/rust This snippet shows how to create a new Rust Cargo project and add Ryugraph as a dependency. Ensure Rust is installed on your system. ```bash cargo new ryugraph_social_network cd ryugraph_social_network cargo add ryugraph ``` -------------------------------- ### Work with PyArrow Tables Source: https://ryugraph-docs.vercel.app/get-started This example shows how to work with PyArrow Tables in Python, assuming `pyarrow` is installed. It highlights that the `get_as_pl()` method internally uses PyArrow. This approach is beneficial for seamless interoperability with other systems that utilize Arrow as their data backend. ```python # PyArrow Table example (conceptual, as get_as_pl() materializes it) # response.get_as_arrow() ``` -------------------------------- ### Ryugraph C++ Client Setup and Usage Source: https://ryugraph-docs.vercel.app/get-started Demonstrates setting up the Ryugraph C++ client by organizing library and header files. It includes a main.cpp file that connects to a database, creates tables, loads data from CSV files, and executes a sample query. Error handling for query execution is included. The setup requires CMake for building. ```cpp #include #include "include/ryugraph.hpp" using namespace ryugraph::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.ryugraph remove("example.ryugraph"); remove("example.ryugraph.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.ryugraph", 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; } ``` -------------------------------- ### Create Example Dataset using Sentence Transformers Source: https://ryugraph-docs.vercel.app/extensions/vector This snippet demonstrates how to create an example dataset for vector search using the `sentence_transformers` library in Python. It installs and loads the vector extension, defines node and relationship tables, generates embeddings for book titles using Sentence Transformers, and inserts the data into Ryugraph. ```python # pip install sentence-transformers import ryugraph import os db = ryugraph.Database("example.ryugraph") conn = ryugraph.Connection(db) from sentence_transformers import SentenceTransformer model = SentenceTransformer("all-MiniLM-L6-v2") conn.execute("INSTALL vector; LOAD vector;") conn.execute("CREATE NODE TABLE Book(id SERIAL PRIMARY KEY, title STRING, title_embedding FLOAT[384], published_year INT64);") conn.execute("CREATE NODE TABLE Publisher(name STRING PRIMARY KEY);") conn.execute("CREATE REL TABLE PublishedBy(FROM Book TO Publisher);") titles = [ "The Quantum World", "Chronicles of the Universe", "Learning Machines", "Echoes of the Past", "The Dragon's Call" ] publishers = ["Harvard University Press", "Independent Publisher", "Pearson", "McGraw-Hill Ryerson", "O'Reilly"] published_years = [2004, 2022, 2019, 2010, 2015] for title, published_year in zip(titles, published_years): embeddings = model.encode(title).tolist() conn.execute( """ CREATE (b:Book { title: $title, title_embedding: $embeddings, published_year: $year });""", {"title": title, "year": published_year, "embeddings": embeddings} ) print(f"Inserted book: {title}") for publisher in publishers: conn.execute( """CREATE (p:Publisher {name: $publisher});""", {"publisher": publisher} ) print(f"Inserted publisher: {publisher}") for title, publisher in zip(titles, publishers): conn.execute(""" MATCH (b:Book {title: $title}) MATCH (p:Publisher {name: $publisher}) CREATE (b)-[:PublishedBy]->(p); """, {"title": title, "publisher": publisher} ) print(f"Created relationship between {title} and {publisher}") ``` -------------------------------- ### Install Ryu Python Client using uv Source: https://ryugraph-docs.vercel.app/installation Install the Ryugraph Python client library using `uv`. This command initializes `uv` if necessary and then adds the `ryugraph` package to your project. ```shell uv init uv add ryugraph ``` -------------------------------- ### Build and Link Ryugraph from Source with CMake Source: https://ryugraph-docs.vercel.app/client-apis/c This CMake example uses FetchContent to download and build Ryugraph as a dependency. It allows linking either statically or dynamically to an example executable, configurable via the `EXAMPLE_SHARED` option. Ensure `main.c` is available for the example executable. ```cmake cmake_minimum_required(VERSION 3.11) project(example LANGUAGES C CXX) set(BUILD_SHELL FALSE) include(FetchContent) FetchContent_Declare(ryugraph URL https://github.com/predictable-labs/ryugraph/archive/refs/tags/v0.5.0.zip URL_HASH SHA256=47ff308079cbbfeccc38eeb1c5f455a8c00f9294034141b9084387518f0bbed9 ) FetchContent_MakeAvailable(ryugraph) add_executable(example main.c) option(EXAMPLE_SHARED "Use dynamic linking" TRUE) if (EXAMPLE_SHARED) target_link_libraries(example ryugraph_shared) else() target_link_libraries(example ryugraph) endif() ``` -------------------------------- ### Install an Extension Source: https://ryugraph-docs.vercel.app/extensions Extensions must be installed before they can be loaded and used. Official extensions can be installed from a local extension server. ```APIDOC ## Install an Extension ### Description Installs an extension into Ryu. This operation only needs to be performed once per extension. ### Method INSTALL ### Endpoint N/A (Command) ### Parameters #### Path Parameters - **EXTENSION_NAME** (string) - Required - The name of the extension to install. - **URL** (string) - Required - The URL of the local extension server (e.g., 'http://localhost:8080/'). ### Request Example ```sql INSTALL FROM 'http://localhost:8080/'; ``` ### Response #### Success Response (200) Indicates successful installation. No specific return data is typically provided for this command. #### Response Example (No explicit response body for successful installation. Success is indicated by the absence of errors.) ``` -------------------------------- ### Install asyncpg and Create PostgreSQL Database Source: https://ryugraph-docs.vercel.app/extensions/attach/postgres Installs the asyncpg library for Python and demonstrates how to connect to a PostgreSQL database, create a table, and insert sample data. Handles potential DuplicateTableError. ```bash pip install asyncpg ``` ```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()) ``` -------------------------------- ### Declarative Ryu Installation with Nix Source: https://ryugraph-docs.vercel.app/installation Declaratively install Ryu using NixOS or Home Manager configuration. This allows for reproducible installations managed through your Nix configurations. ```nix { environment.systemPackages = [ pkgs.ryugraph ]; } // NixOS { home.packages = [ pkgs.ryugraph ]; } // Home Manager ``` -------------------------------- ### Ryugraph C++ Example: Database Operations Source: https://ryugraph-docs.vercel.app/get-started/prepared-statements A comprehensive C++ example showcasing Ryugraph database operations. This includes setting up the database, creating node tables, inserting nodes with direct values and parameters, executing queries, and printing results. It highlights functions for running queries and prepared queries. ```cpp #include #include #include #include "ryugraph.hpp" using namespace ryugraph::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.ryugraph remove("example.ryugraph"); remove("example.ryugraph.wal"); // Create an empty on-disk database and connect to it SystemConfig systemConfig; auto database = make_unique("example.ryugraph", 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 = ryugraph::common::LogicalType::LIST(ryugraph::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() == ryugraph::common::LogicalTypeID::STRING); cout << value_name->getValue() << " | "; // Print `age`. auto value_int64 = row->getValue(1); KU_ASSERT_UNCONDITIONAL(value_int64->getDataType().getLogicalTypeID() == ryugraph::common::LogicalTypeID::INT64); cout << value_int64->getValue() << " | "; // Print `embedding`. auto value_embedding = row->getValue(2); KU_ASSERT_UNCONDITIONAL(value_embedding->getDataType().getLogicalTypeID() == ryugraph::common::LogicalTypeID::LIST); auto length = value_embedding->getChildrenSize(); vector embedding; for (auto i = 0u; i < length; ++i) { auto element = ryugraph::common::NestedVal::getChildVal(value_embedding, i); KU_ASSERT_UNCONDITIONAL(element->getDataType().getLogicalTypeID() == ryugraph::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; } ``` -------------------------------- ### Install Ryugraph using CMake Source: https://ryugraph-docs.vercel.app/client-apis/c This set of commands demonstrates how to build and install the Ryugraph library using CMake. It first builds the project into a build directory and then installs it to a specified prefix. This is useful for integrating Ryugraph into other build systems. ```shell cmake -B build cmake --build build cmake --install build --prefix '' ``` -------------------------------- ### Install Ryu CLI on Windows Source: https://ryugraph-docs.vercel.app/installation Download the Ryu Command Line Interface (CLI) for Windows x86-64 architecture using curl. After downloading, extract the zip file and run the `ryugraph.exe` from the terminal. ```shell curl -L -O https://github.com/predictable-labs/ryugraph/releases/download/v0.11.0/ryugraph_cli-windows-x86_64.zip ``` -------------------------------- ### Project Graph: Simple Projection Example in Ryugraph Source: https://ryugraph-docs.vercel.app/extensions/algo An example of the `PROJECT_GRAPH` procedure in Ryugraph, demonstrating how to create a projected graph named 'Graph' using the 'Person' node table and 'KNOWS' relationship table. ```cypher CALL PROJECT_GRAPH('Graph', ['Person'], ['KNOWS']); ``` -------------------------------- ### Install Ryu Python Client with Nix Source: https://ryugraph-docs.vercel.app/installation Install the Ryugraph Python client library using Nix. This command creates a Nix shell environment with Python and the specified Ryugraph package. ```shell nix-shell -p "python3.withPackages (ps: [ ps.ryugraph ])" ``` -------------------------------- ### Install an Extension Source: https://ryugraph-docs.vercel.app/extensions Installs an official extension from a local extension server. Extensions only need to be installed once. Note that newer Ryu versions (v0.11.3+) pre-install common extensions. ```ryugraph INSTALL FROM 'http://localhost:8080/'; ``` -------------------------------- ### Install and load Ryugraph algo extension Source: https://ryugraph-docs.vercel.app/get-started/graph-algorithms Installs the 'algo' extension into the Ryugraph database and then loads it, making its graph algorithm functions available for use within the current connection. ```python import ryugraph db_path = "example.ryugraph" db = ryugraph.Database(db_path) conn = ryugraph.Connection(db) # Install and load the Ryugraph algo extension conn.execute("INSTALL algo; LOAD algo;") ``` -------------------------------- ### Install Polars and Execute Cypher Query Source: https://ryugraph-docs.vercel.app/get-started This snippet demonstrates how to install the Polars library and execute a Cypher query using a connection object. The results are then fetched as a Polars DataFrame using `get_as_pl()`. This is useful for integrating graph database query results directly into data analysis workflows. ```python # pip install polars response = conn.execute( """ MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, b.name, f.since; """ ) print(response.get_as_pl()) ``` -------------------------------- ### Ryugraph Explorer Development Build Error Example Source: https://ryugraph-docs.vercel.app/visualization/ryugraph-explorer This is an example error message that may occur if the development build of Ryugraph Explorer is used with a stable or outdated release of Ryugraph, due to incompatible storage formats. ```text ERROR (1): Error getting version of Ryugraph: Error: std::bad_alloc ``` -------------------------------- ### Install and Use Ryugraph Crate (Rust) Source: https://ryugraph-docs.vercel.app/get-started This snippet shows how to add the 'ryugraph' crate to your Rust project's Cargo.toml for installation. By default, it builds the C++ library from source, but dynamic linking is also an option. ```rust use ryugraph::{Connection, Database, Error, SystemConfig}; fn main() -> Result<(), Error> { // Create an empty on-disk database and connect to it let db = Database::new("example.ryugraph", SystemConfig::default())?; let conn = Connection::new(&db)?; // Create the tables ``` -------------------------------- ### Install ryugraph-wasm Package Source: https://ryugraph-docs.vercel.app/client-apis/wasm This snippet shows how to install the ryugraph-wasm package using npm. This is the initial step required to use Ryugraph's WebAssembly capabilities in your project. ```bash npm i ryugraph-wasm ``` -------------------------------- ### Execute CURRENT_SETTING function to get database configuration Source: https://ryugraph-docs.vercel.app/cypher/query-clauses/call The `CURRENT_SETTING` function returns the value of a specified database configuration parameter. It takes the setting name as a parameter, for example, 'threads'. ```cypher CALL current_setting('threads') RETURN *; ``` -------------------------------- ### Set up Unity Catalog Server (Shell) Source: https://ryugraph-docs.vercel.app/extensions/attach/unity This code snippet demonstrates how to clone the Unity Catalog repository and start its server. It's a prerequisite for using the Unity Catalog extension. ```shell git clone https://github.com/unitycatalog/unitycatalog.git bin/start-uc-server ``` -------------------------------- ### Get Union Tag Source: https://ryugraph-docs.vercel.app/cypher/expressions/union-functions The `union_tag` function retrieves the tag associated with a given union value. This is useful for determining which variant of the union is currently active. It takes a union as input and returns its tag. ```pseudocode union_tag(union_value(a := 1)) ``` -------------------------------- ### Go: Create Schema, Load Data, and Query Ryugraph Source: https://ryugraph-docs.vercel.app/get-started This Go program illustrates how to initialize a Ryugraph database, define a schema with node and relationship tables, load data from CSV files, and execute a Cypher query to retrieve user connections. It utilizes the `go-ryugraph` library. ```go package main import ( "fmt" "github.com/predictable-labs/go-ryugraph" ) func main() { // Create an empty on-disk database and connect to it systemConfig := ryugraph.DefaultSystemConfig() systemConfig.BufferPoolSize = 1024 * 1024 * 1024 db, err := ryugraph.OpenDatabase("example.ryugraph", systemConfig) if err != nil { panic(err) } defer db.Close() conn, err := ryugraph.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) } } ``` -------------------------------- ### Create Ryugraph Database Initialization Script Source: https://ryugraph-docs.vercel.app/tutorials/rust This snippet creates a new Rust binary target for database creation and copies the main file to it. This is used for one-time database setup. ```bash mkdir src/bin cp src/main.rs src/bin/create_db.rs ``` -------------------------------- ### Enforcing Join Order with HINT Clause Source: https://ryugraph-docs.vercel.app/developer-guide/join-order-hint An example demonstrating how to use the HINT clause with a specific join order to guide the Ryugraph optimizer. This enforces scanning backward adjacency lists from node 'b'. ```cypher MATCH (a)-[e]->(b) WHERE b.ID = 0 HINT a JOIN (e JOIN b) RETURN *; ``` -------------------------------- ### Create On-Disk Ryugraph Database using CLI Source: https://ryugraph-docs.vercel.app/get-started Demonstrates how to create and open an on-disk Ryugraph database using the command-line interface. This command initializes a persistent database file that can be accessed and modified. ```bash ryugraph example.ryugraph ``` -------------------------------- ### Create Project Structure Source: https://ryugraph-docs.vercel.app/tutorials/python Creates a 'src' directory and two Python files, 'create_db.py' and 'main.py', within it. This organizes the project for database creation and querying. ```bash mkdir src touch src/create_db.py touch src/main.py ``` -------------------------------- ### Create Example Dataset using Ryugraph LLM Extension Source: https://ryugraph-docs.vercel.app/extensions/vector This snippet demonstrates creating an example dataset for vector search using Ryugraph's `llm` extension to generate embeddings directly via Cypher. It installs and loads both `llm` and `vector` extensions, sets the OpenAI API key, defines schema, and then creates book and publisher nodes with embeddings generated by the `create_embedding` function. ```python import ryugraph import os db = ryugraph.Database("example.ryugraph") conn = ryugraph.Connection(db) conn.execute("INSTALL llm; LOAD llm;") os.environ["OPENAI_API_KEY"] = "sk-proj-key" # Replace with your own OpenAI API key conn.execute("INSTALL vector; LOAD vector;") conn.execute("CREATE NODE TABLE Book(id SERIAL PRIMARY KEY, title STRING, title_embedding FLOAT[384], published_year INT64);") conn.execute("CREATE NODE TABLE Publisher(name STRING PRIMARY KEY);") conn.execute("CREATE REL TABLE PublishedBy(FROM Book TO Publisher);") titles = [ "The Quantum World", "Chronicles of the Universe", "Learning Machines", "Echoes of the Past", "The Dragon's Call" ] publishers = ["Harvard University Press", "Independent Publisher", "Pearson", "McGraw-Hill Ryerson", "O'Reilly"] published_years = [2004, 2022, 2019, 2010, 2015] for title, published_year in zip(titles, published_years): conn.execute( """ CREATE (b:Book { title: $title, title_embedding: create_embedding( $title, 'open-ai', 'text-embedding-3-small', 384 ), published_year: $year }); """, {"title": title, "year": published_year} ) print(f"Inserted book: {title}") for publisher in publishers: conn.execute( """CREATE (p:Publisher {name: $publisher});""", {"publisher": publisher} ) print(f"Inserted publisher: {publisher}") for title, publisher in zip(titles, publishers): conn.execute(""" MATCH (b:Book {title: $title}) MATCH (p:Publisher {name: $publisher}) CREATE (b)-[:PublishedBy]->(p); """, {"title": title, "publisher": publisher} ) print(f"Created relationship between {title} and {publisher}") ``` -------------------------------- ### Start Ryugraph CLI Source: https://ryugraph-docs.vercel.app/tutorials/cypher Initiates the Ryugraph Command Line Interface (CLI) shell. This command allows direct interaction with a Ryugraph database in a terminal environment for testing Cypher queries. ```bash # Open an in-memory database ryugraph ``` -------------------------------- ### Create Ryugraph Database and Connection (Python) Source: https://ryugraph-docs.vercel.app/concurrency Demonstrates how to create a READ_WRITE Ryugraph database instance and establish a connection for executing queries. This example uses the `ryugraph` library in Python. Ensure the `ryugraph` library is installed before running this code. ```python import ryugraph # Open the database in `READ_WRITE` mode. The below code is equivalent to: # db = ryugraph.Database("example.ryugraph", read_only=False) db = ryugraph.Database("example.ryugraph") conn = ryugraph.Connection(db) conn.execute("CREATE (a:Person {name: 'Alice'});") ``` -------------------------------- ### Rust: Create Schema, Load Data, and Query Ryugraph Source: https://ryugraph-docs.vercel.app/get-started Demonstrates creating node and relationship tables, loading data from CSV files, and executing a Cypher query to find user relationships. This example uses the Ryugraph Rust client. ```rust fn main() -> Result<(), Box> { // Create an empty on-disk database and connect to it let mut conn = ryugraph::Connection::open_database("example.ryugraph")?; // Create schema 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 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(()) } ``` -------------------------------- ### Get Internal ID Offset - Cypher Source: https://ryugraph-docs.vercel.app/cypher/expressions/node-rel-functions The OFFSET function calculates the offset of an internal ID. It takes an ID as input and returns an INT64. The example demonstrates calculating the offset of the internal ID of a User node. ```cypher MATCH (a) RETURN OFFSET(ID(a)) AS OFFSET LIMIT 1; ``` -------------------------------- ### Create Node Table Schema Source: https://ryugraph-docs.vercel.app/import This example defines the schema for a 'Person' node table in Ryugraph. It includes columns for 'id', 'name', 'age', and 'address', specifying their data types. This DDL statement is a prerequisite for importing data into the Person nodes. ```cypher CREATE NODE TABLE Person(id INT64 PRIMARY KEY, name STRING, age INT64, address STRING); ``` -------------------------------- ### Initialize Ryugraph environment and add dependencies Source: https://ryugraph-docs.vercel.app/get-started/graph-algorithms Initializes the project environment using 'uv' and adds necessary Python libraries for Ryugraph, data handling (Polars, PyArrow), and graph algorithms (NetworkX, NumPy, SciPy). This sets up the project with the required dependencies. ```bash uv init uv add ryugraph polars pyarrow networkx numpy scipy ``` -------------------------------- ### Explicitly Specify CSV File Format with COPY FROM Source: https://ryugraph-docs.vercel.app/import This example demonstrates how to use the COPY FROM clause to import data from a file, explicitly specifying the file format as 'csv' even if the file has a different extension. This ensures correct data parsing. ```cypher COPY person FROM 'person.dsv' (file_format = 'csv') ``` -------------------------------- ### Query Recursive Paths with Named Path Source: https://ryugraph-docs.vercel.app/cypher/query-clauses/match This example shows how to assign a named path 'p' to a recursive graph pattern. It finds paths where a user follows one or two other users, and then lives in a city, filtering by the starting user's name. ```cypher MATCH p = (a:User)-[:Follows*1..2]->(:User)-[:LivesIn]->(:City) WHERE a.name = 'Adam' RETURN p; ``` -------------------------------- ### Unity Catalog Extension - Setup and Usage Source: https://ryugraph-docs.vercel.app/extensions/attach/unity Instructions on setting up a Unity Catalog server and attaching it to Ryugraph, including parameter details and type mappings. ```APIDOC ## Setting up a Unity Catalog server First, set up the open-source version of Unity Catalog: ```console git clone https://github.com/unitycatalog/unitycatalog.git bin/start-uc-server ``` ### Attach to a Unity Catalog Use the `ATTACH` statement to connect Ryugraph to a Unity Catalog. ``` ATTACH [CATALOG_NAME] AS [alias] (dbtype UC_CATALOG) ``` #### Parameters - **CATALOG_NAME** (string) - Required - The catalog name to attach to in the Unity Catalog. - **alias** (string) - Optional - Database alias to use in Ryugraph. If not provided, the catalog name will be used. Recommended when attaching multiple databases. **Note:** Ryugraph attaches to the `default` schema under the given catalog name. Specifying the schema to attach is not currently supported. ### Unity Catalog to Ryugraph Type Mapping | Data type in Unity Catalog | Corresponding data type in Ryugraph | |---|---| | `BOOLEAN` | `BOOLEAN` | | `BYTE` | Unsupported | | `SHORT` | `INT16` | | `INT` | `INT32` | | `LONG` | `INT64` | | `DOUBLE` | `DOUBLE` | | `FLOAT` | `FLOAT` | | `DATE` | `DATE` | | `TIMESTAMP` | `TIMESTAMP` | | `TIMESTAMP_NTZ` | Unsupported | | `STRING` | `STRING` | | `BINARY` | Unsupported | | `DECIMAL` | `DECIMAL` | ``` -------------------------------- ### Glob Data from Google Cloud Storage Source: https://ryugraph-docs.vercel.app/extensions/gcs Access and copy data from multiple files in Google Cloud Storage that match a specified pattern. This example copies CSV files starting with 'vPerson' into the 'person' table, including a header row. ```sql COPY person FROM "gs://tinysnb/vPerson*.csv"(header=true); ``` -------------------------------- ### Get Node/Relationship Label Name - Cypher Source: https://ryugraph-docs.vercel.app/cypher/expressions/node-rel-functions The LABEL function retrieves the label name of a node or relationship. It accepts NODE or REL as input and returns a STRING. The alias LABELS can also be used. The example shows returning the label of any node. ```cypher MATCH (a) RETURN LABEL(a) AS LABEL LIMIT 1; ``` -------------------------------- ### Query Ryugraph Database and Get Results as PyArrow Table (Python) Source: https://ryugraph-docs.vercel.app/get-started This snippet demonstrates how to execute a Cypher query against a Ryugraph database using a Python connection and retrieve the results formatted as a PyArrow Table. It requires the 'ryugraph' and 'pyarrow' libraries to be installed. ```python # pip install pyarrow response = conn.execute( """ MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, b.name, f.since; """ ) print(response.get_as_arrow()) ``` -------------------------------- ### Get Node/Relationship Internal ID - Cypher Source: https://ryugraph-docs.vercel.app/cypher/expressions/node-rel-functions The ID function returns the internal database ID for a given node or relationship. This function takes either a NODE or REL as input and outputs an internal database ID. Example demonstrates returning the ID of a User node. ```cypher MATCH (a:User) RETURN ID(a) AS ID LIMIT 1; ``` -------------------------------- ### Initialize and Query Ryugraph Database in C Source: https://ryugraph-docs.vercel.app/get-started This C code snippet demonstrates how to initialize an on-disk Ryugraph database, create node and relation tables, load data from CSV files, and execute a graph query. It includes necessary cleanup for database connections and query results. Ensure ryugraph.h is accessible. ```c #include #include "include/ryugraph.h" int main() { // Create an empty on-disk database and connect to it ryugraph_database db; ryugraph_database_init("example.ryugraph", ryugraph_default_system_config(), &db); // Connect to the database. ryugraph_connection conn; ryugraph_connection_init(&db, &conn); // Create the schema. ryugraph_query_result result; ryugraph_connection_query(&conn, "CREATE NODE TABLE User(name STRING PRIMARY KEY, age INT64)", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "CREATE NODE TABLE City(name STRING PRIMARY KEY, population INT64)", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "CREATE REL TABLE Follows(FROM User TO User, since INT64)", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "CREATE REL TABLE LivesIn(FROM User TO City)", &result); ryugraph_query_result_destroy(&result); // Load data. ryugraph_connection_query(&conn, "COPY User FROM \"user.csv\"", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "COPY City FROM \"city.csv\"", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "COPY Follows FROM \"follows.csv\"", &result); ryugraph_query_result_destroy(&result); ryugraph_connection_query(&conn, "COPY LivesIn FROM \"lives-in.csv\"", &result); ryugraph_query_result_destroy(&result); // Execute a simple query. ryugraph_connection_query(&conn, "MATCH (a:User)-[f:Follows]->(b:User) RETURN a.name, f.since, b.name;", &result); // Output query result. ryugraph_flat_tuple tuple; ryugraph_value value; while (ryugraph_query_result_has_next(&result)) { ryugraph_query_result_get_next(&result, &tuple); ryugraph_flat_tuple_get_value(&tuple, 0, &value); char *name = NULL; ryugraph_value_get_string(&value, &name); ryugraph_value_destroy(&value); ryugraph_flat_tuple_get_value(&tuple, 1, &value); int64_t since = 0; ryugraph_value_get_int64(&value, &since); ryugraph_value_destroy(&value); ryugraph_flat_tuple_get_value(&tuple, 2, &value); char *name2 = NULL; ryugraph_value_get_string(&value, &name2); ryugraph_value_destroy(&value); printf("%s follows %s since %lld \n", name, name2, since); free(name); free(name2); } ryugraph_value_destroy(&value); ryugraph_flat_tuple_destroy(&tuple); ryugraph_query_result_destroy(&result); ryugraph_connection_destroy(&conn); ryugraph_database_destroy(&db); return 0; } ``` -------------------------------- ### Create Schema, Load Data, and Query Ryugraph Database (Java) Source: https://ryugraph-docs.vercel.app/get-started This Java example demonstrates initializing a Ryugraph database, creating node and relationship tables, loading data from CSV files, and executing a query to retrieve user relationships. It uses the Ryugraph Java client library. ```java import com.ryugraphdb.*; 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.ryugraph"); 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); } } } ``` -------------------------------- ### Disable Spilling to Disk for Large Imports Source: https://ryugraph-docs.vercel.app/import This example shows how to disable the feature that spills imported relationship table data to disk when memory usage approaches the buffer pool size. This is controlled by the 'spill_to_disk' parameter within a CALL statement. This feature is not available for in-memory or read-only databases. ```cypher CALL spill_to_disk=false ``` -------------------------------- ### Host Your Own Extension Server Source: https://ryugraph-docs.vercel.app/extensions Instructions on how to set up and run a local extension server using Docker for hosting your own Ryu extensions. ```APIDOC ## Host Your Own Extension Server ### Description Provides instructions to host a Ryu extension server using Docker, allowing you to serve custom or private extensions. ### Method Docker Commands ### Endpoint N/A (Docker commands) ### Parameters None ### Request Example ```bash # Pull the latest extension repository image docker pull ghcr.io/ryugraphdb/extension-repo:latest # Run the extension server in detached mode, exposing port 8080 docker run -d -p 8080:80 ghcr.io/ryugraphdb/extension-repo:latest ``` ### Response #### Success Response (200) Indicates the Docker container is running successfully. The extension server will be accessible at `http://localhost:8080`. #### Response Example (Docker run command output indicating container ID and successful start.) ``` -------------------------------- ### Launch Ryugraph Explorer with Empty Database (Docker) Source: https://ryugraph-docs.vercel.app/visualization/ryugraph-explorer This command launches Ryugraph Explorer with an empty, in-memory database, omitting the volume mount (`-v`). It's suitable for exploring bundled datasets or starting fresh. Ryugraph Explorer will look for `database.kz` or create it if the directory is mounted but `RYUGRAPH_FILE` is not specified. ```bash docker run -p 8000:8000 --rm ryugraphdb/explorer:latest ``` -------------------------------- ### Initialize Ryugraph Database Connection Source: https://ryugraph-docs.vercel.app/tutorials/rust This snippet demonstrates how to establish a connection to a Ryugraph database file named 'social_network.ryugraph' and sets up the necessary system configuration. It's the foundational step for all subsequent graph queries. ```rust use ryugraph::{Connection, Database, Error, SystemConfig, Value}; fn main() -> Result<(), Error> { let db = Database::new("social_network.ryugraph", SystemConfig::default())?; let conn = Connection::new(&db)?; // Rest of the code goes here. Ok(()) } ``` -------------------------------- ### Install Ryu CLI using Homebrew on macOS Source: https://ryugraph-docs.vercel.app/installation Install the Ryu Command Line Interface (CLI) on macOS using the Homebrew package manager. This command installs the CLI, allowing you to run Ryu directly from your terminal. ```shell brew install ryugraph ryugraph ```