### Schema Setup for Examples Source: https://typedb.com/docs/typeql-reference/schema/undefine The initial schema state used for the following undefine examples. ```typeql define entity content owns id; entity page sub content, owns page-id, owns name; entity profile sub page, owns username; entity user sub profile, owns phone, owns karma; attribute id value string; attribute page-id sub id; attribute username sub page-id; attribute name value string; attribute phone value string; attribute karma value double; attribute bio value string; attribute profile-picture value string; attribute email @independent, value string @regex("^.*@.*\.com"); user owns bio, owns profile-picture, owns email; attribute tag value string; entity post owns tag @card(0..); relation parentship @abstract, relates parent, relates child; relation fathership sub parentship, relates father as parent; user plays parentship:parent; user owns email @card(0..1); ``` -------------------------------- ### Start TypeDB Enterprise Cluster Servers Source: https://typedb.com/docs/home/install/enterprise Examples for starting three separate TypeDB Enterprise servers in a cluster on a private network. ```bash ./typedb server \ --server.address=10.0.0.1:1729 \ --server.internal-address.zeromq=10.0.0.1:1730 \ --server.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-1.address=10.0.0.1:1729 \ --server.peers.peer-1.internal-address.zeromq=10.0.0.1:1730 \ --server.peers.peer-1.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-2.address=10.0.0.2:1729 \ --server.peers.peer-2.internal-address.zeromq=10.0.0.2:1730 \ --server.peers.peer-2.internal-address.grpc=10.0.0.2:1731 \ --server.peers.peer-3.address=10.0.0.3:1729 \ --server.peers.peer-3.internal-address.zeromq=10.0.0.3:1730 \ --server.peers.peer-3.internal-address.grpc=10.0.0.3:1731 ``` ```bash ./typedb server \ --server.address=10.0.0.2:1729 \ --server.internal-address.zeromq=10.0.0.2:1730 \ --server.internal-address.grpc=10.0.0.2:1731 \ --server.peers.peer-1.address=10.0.0.1:1729 \ --server.peers.peer-1.internal-address.zeromq=10.0.0.1:1730 \ --server.peers.peer-1.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-2.address=10.0.0.2:1729 \ --server.peers.peer-2.internal-address.zeromq=10.0.0.2:1730 \ --server.peers.peer-2.internal-address.grpc=10.0.0.2:1731 \ --server.peers.peer-3.address=10.0.0.3:1729 \ --server.peers.peer-3.internal-address.zeromq=10.0.0.3:1730 \ --server.peers.peer-3.internal-address.grpc=10.0.0.3:1731 ``` ```bash ./typedb server \ --server.address=10.0.0.3:1729 \ --server.internal-address.zeromq=10.0.0.3:1730 \ --server.internal-address.grpc=10.0.0.3:1731 \ --server.peers.peer-1.address=10.0.0.1:1729 \ --server.peers.peer-1.internal-address.zeromq=10.0.0.1:1730 \ --server.peers.peer-1.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-2.address=10.0.0.2:1729 \ --server.peers.peer-2.internal-address.zeromq=10.0.0.2:1730 \ --server.peers.peer-2.internal-address.grpc=10.0.0.2:1731 \ --server.peers.peer-3.address=10.0.0.3:1729 \ --server.peers.peer-3.internal-address.zeromq=10.0.0.3:1730 \ --server.peers.peer-3.internal-address.grpc=10.0.0.3:1731 ``` -------------------------------- ### Start TypeDB Enterprise Manually Source: https://typedb.com/docs/home/install/enterprise Execute the server binary from the installation directory to launch the TypeDB Enterprise instance. ```bash ./typedb server ``` -------------------------------- ### Get Cluster Request Examples Source: https://typedb.com/docs/reference/cloud-http-api Examples of how to perform the GET request using curl, Python, and Rust. ```curl curl --request GET \ --url https://cloud.typedb.com/api/v1/team/TEAM_ID/spaces/SPACE_ID/clusters/CLUSTER_ID \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` ```python import requests url = "https://cloud.typedb.com/api/v1/team/TEAM_ID/spaces/SPACE_ID/clusters/CLUSTER_ID" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` ```rust #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("https://cloud.typedb.com/api/v1/team/TEAM_ID/spaces/SPACE_ID/clusters/CLUSTER_ID") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Get User Request Example (cURL) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to fetch a user using cURL. Replace USERNAME and {ACCESS-TOKEN} with actual values. ```shell curl --request GET \ --url http://localhost:8000/v1/users/USERNAME \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` -------------------------------- ### Get Database Request Example (Rust) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to retrieve a database using Rust's reqwest library. Asynchronous execution is handled with tokio. ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/databases/DATABASE_NAME") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Get User Request Example (Python) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to fetch a user using Python's requests library. Ensure the Authorization header is correctly formatted. ```python import requests url = "http://localhost:8000/v1/users/USERNAME" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` -------------------------------- ### Setup TypeDB in GitHub Actions Source: https://typedb.com/docs/guides/integrations/use-github-actions Installs and runs a specified version of TypeDB using the `typedb/setup-typedb` action. Ensure `typedb_version` is set to your desired TypeDB version. ```yaml name: TypeDB on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup TypeDB uses: typedb/setup-typedb@1.0.0 with: typedb_version: 3.5.1 ``` -------------------------------- ### Start TypeDB server Source: https://typedb.com/docs/home/install/ce Starts a local TypeDB server instance. ```bash typedb server ``` -------------------------------- ### Get Databases using Rust Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get all databases using Rust's reqwest library, including the Authorization header. ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/databases") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Install TypeDB using apt (Debian/Ubuntu) Source: https://typedb.com/docs/home/install/ce Installs TypeDB using the apt package manager. Requires GPG key setup and repository configuration. ```shell sudo apt install software-properties-common apt-transport-https gpg gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-key 17507562824cfdcc gpg --export 17507562824cfdcc | sudo tee /etc/apt/trusted.gpg.d/typedb.gpg > /dev/null echo "deb https://repo.typedb.com/public/public-release/deb/ubuntu trusty main" | sudo tee /etc/apt/sources.list.d/typedb.list > /dev/null sudo apt update sudo apt install typedb ``` -------------------------------- ### Get Database Request Example (cURL) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to retrieve a database using cURL. Ensure the Authorization header contains a valid access token. ```bash curl --request GET \ --url http://localhost:8000/v1/databases/DATABASE_NAME \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` -------------------------------- ### Get Database Request Example (Python) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to retrieve a database using Python's requests library. The Authorization header must be correctly formatted. ```python import requests url = "http://localhost:8000/v1/databases/DATABASE_NAME" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` -------------------------------- ### Configure Cluster for External Client Access Source: https://typedb.com/docs/home/install/enterprise Example of starting a server using separate hostnames for external client communication and private network inter-server communication. ```bash ./typedb server \ --server.address=external-host-1:1729 \ --server.internal-address.zeromq=10.0.0.1:1730 \ --server.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-1.address=external-host-1:1729 \ --server.peers.peer-1.internal-address.zeromq=10.0.0.1:1730 \ --server.peers.peer-1.internal-address.grpc=10.0.0.1:1731 \ --server.peers.peer-2.address=external-host-2:1729 \ --server.peers.peer-2.internal-address.zeromq=10.0.0.2:1730 \ --server.peers.peer-2.internal-address.grpc=10.0.0.2:1731 \ --server.peers.peer-3.address=external-host-3:1729 \ --server.peers.peer-3.internal-address.zeromq=10.0.0.3:1730 \ --server.peers.peer-3.internal-address.grpc=10.0.0.3:1731 ``` -------------------------------- ### SQL Table Creation for Employment Source: https://typedb.com/docs/guides/typeql/sql-vs-typeql An SQL example demonstrating how to create an 'employment' table using foreign keys to link employees and companies, including a start date. ```sql CREATE TABLE employment ( id INT PRIMARY KEY, employee_id INT REFERENCES person(id), employer_id INT REFERENCES company(id), start_date DATE ); ``` -------------------------------- ### Get Databases using cURL Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get all databases using cURL, including the Authorization header. ```shell curl --request GET \ --url http://localhost:8000/v1/databases \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` -------------------------------- ### Get Databases using Python Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get all databases using Python's requests library, including the Authorization header. ```python import requests url = "http://localhost:8000/v1/databases" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` -------------------------------- ### Get User Request Example (Rust) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to fetch a user using Rust's reqwest library. The Authorization header is set using reqwest::header::AUTHORIZATION. ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/users/USERNAME") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Install TypeDB using install script (Linux/macOS) Source: https://typedb.com/docs/home/install/ce Installs the latest TypeDB version to $HOME/.typedb. Ensure the PATH is updated. ```shell curl -sSL https://typedb.com/install.sh | sh && export PATH="$HOME/.typedb:$PATH" ``` -------------------------------- ### Create Courier and Order with Delivery (UPS Returned) Source: https://typedb.com/docs/guides/typeql/read-data This example creates a UPS courier and an order with a 'returned' status. It includes address and location setup. Use this to record orders that have been returned. ```typeql put $courier isa courier, has name "UPS"; end; ``` ```typeql match $city isa city, has name "Montreal"; put $address isa address, has street "86 East Drive"; (location: $city, located: $address) isa locating; ``` ```typeql match $user isa user, has id "u0009"; $courier isa courier, has name "UPS"; $city isa city, has name "Montreal"; insert $order isa order, has id "o0020", has status "returned"; $execution isa action-execution, links (action: $order, executor: $user), has timestamp 2023-12-19T13:49:42.726; (delivered: $order, deliverer: $courier, destination: $address) isa delivery;end; ``` -------------------------------- ### Create Database Request Example (Rust) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a database using Rust's reqwest library. The POST request includes the necessary Authorization header. ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .post("http://localhost:8000/v1/databases/DATABASE_NAME") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Install and Initialize Python Driver Source: https://typedb.com/docs/home/install/drivers Install the driver via pip and initialize the connection using the default address. ```bash pip install typedb-driver ``` ```python from typedb.driver import * driver = TypeDB.driver(address=TypeDB.DEFAULT_ADDRESS, ...) ``` -------------------------------- ### Install and Initialize TypeScript HTTP Driver Source: https://typedb.com/docs/home/install/drivers Install the driver via npm and initialize the connection with credentials and server addresses. ```bash npm install typedb-driver-http ``` ```typescript import { TypeDBHttpDriver, isApiErrorResponse } from "typedb-driver-http"; const driver = new TypeDBHttpDriver({ username: "...", password: "...", addresses: [ "..." ], }); ``` -------------------------------- ### Install Frontend Dependencies Source: https://typedb.com/docs/guides/integrations/social-network Install project dependencies for the frontend using npm or pnpm. ```bash npm install # or pnpm install ``` -------------------------------- ### Create Database Request Example (cURL) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a database using cURL. Ensure the Authorization header is present and valid. ```bash curl --request POST \ --url http://localhost:8000/v1/databases/DATABASE_NAME \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` -------------------------------- ### Install TypeDB using install script (Windows) Source: https://typedb.com/docs/home/install/ce Installs TypeDB to %LOCALAPPDATA%\TypeDB using PowerShell. ```powershell iwr https://typedb.com/install.ps1 -useb | iex ``` -------------------------------- ### Example JSON Response Body for Deployment Source: https://typedb.com/docs/reference/cloud-http-api A sample JSON response received after a successful cluster deployment request. Note the 'status' field indicating the deployment is 'starting'. ```json { "id":"api-cluster", "serverCount":1, "storageSizeGB":10, "isFree":true, "status":"starting", "createdAt":1738256490070, "teamID":"new-team", "spaceID":"default", "version":"3.1.0" } ``` -------------------------------- ### Create Database Request Example (Python) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a database using Python's requests library. Authentication is handled via the Authorization header. ```python import requests url = "http://localhost:8000/v1/databases/DATABASE_NAME" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.post(url, headers=headers) ``` -------------------------------- ### Install Cybersecurity Schema and Data Source: https://typedb.com/docs/use-cases/cybersecurity Use this command to load the STIX 2.1 schema and a sample dataset into TypeDB Console. This is suitable for small to medium-sized examples. ```bash typdb console --username= --address=
--command="database create-init cti http://github.com/typedb/typedb-examples/releases/latest/download/cti-schema.tql http://github.com/typedb/typedb-examples/releases/latest/download/cti-data.tql" ``` -------------------------------- ### Create User Request Example (Rust) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a user using Rust's reqwest library. User credentials are serialized to JSON. ```rust use reqwest; use serde::Serialize; #[derive(Serialize)] struct UserCredentials { password: String, } #[tokio::main] async fn main() -> Result<(), Box> { let user_credentials = UserCredentials { password: "password".to_string(), }; let client = reqwest::Client::new(); let resp = client .post("http://localhost:8000/v1/users/USERNAME") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .json(&user_credentials) .send().await; Ok(()) } ``` -------------------------------- ### Date literal examples Source: https://typedb.com/docs/typeql-reference/values/date Standard ISO 8601 date format examples. ```typeql 2024-03-30 1920-09-21 ``` -------------------------------- ### Create User Request Example (cURL) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a user using cURL. Replace USERNAME, {ACCESS-TOKEN}, and PASSWORD with actual values. ```shell curl --request POST \ --url http://localhost:8000/v1/users/USERNAME \ --header 'Authorization: Bearer {ACCESS-TOKEN}' \ --json '{"password": "PASSWORD"}' ``` -------------------------------- ### Execute one-shot query examples Source: https://typedb.com/docs/reference/typedb-http-api Example implementations for executing a one-shot query using curl, Python, and Rust. ```bash curl --request POST \ --url http://localhost:8000/v1/query \ --header 'Authorization: Bearer {ACCESS-TOKEN}' \ --json '{"databaseName": "DATABASE_NAME", "transactionType": "schema", "query": "define entity person;"}' ``` ```python import requests url = "http://localhost:8000/v1/query" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } body = { "databaseName": "DATABASE_NAME", "transactionType": "schema", "query": "define entity person;" } response = requests.post(url, headers=headers, json=body) ``` ```rust use reqwest; use serde::Serialize; #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub enum TransactionType { Read, Write, Schema, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct OneshotQuery { database_name: String, transaction_type: TransactionType, query: String, } #[tokio::main] async fn main() -> Result<(), Box> { let query = OneshotQuery { database_name: DATABASE_NAME, transaction_type: TransactionType::Schema, query: "define entity person;".to_string(), }; let client = reqwest::Client::new(); let resp = client .post("http://localhost:8000/v1/query") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .json(&query) .send().await; Ok(()) } ``` -------------------------------- ### Define Schema for Examples Source: https://typedb.com/docs/typeql-reference/functions/scalar Schema definition used for the subsequent function examples. ```typeql define entity content owns id; entity page sub content, owns page-id, owns name; entity profile sub page, owns username; entity user sub profile, owns phone, owns karma; attribute id value string; attribute page-id sub id; attribute username sub page-id; attribute name value string; attribute phone value string; attribute karma value double; ``` -------------------------------- ### Define Schema for Examples Source: https://typedb.com/docs/typeql-reference/pipelines/insert Schema definition used for the subsequent insert examples. ```typeql define entity content owns id; entity page sub content, owns page-id, owns name; entity profile sub page, owns username; entity user sub profile, owns phone, owns karma; attribute id value string; attribute page-id sub id; attribute username sub page-id; attribute name value string; attribute phone value string; attribute karma value double; attribute bio value string; attribute profile-picture value string; attribute email @independent, value string @regex("^.*@.*\.com"); user owns bio, owns profile-picture, owns email; attribute group-id sub id; attribute rank, value string @values("admin", "member"); attribute tag value string; relation group-membership, relates group, relates member, owns rank; entity group, owns name, owns group-id, owns tag, plays group-membership:group; user, plays group-membership:member; ``` -------------------------------- ### Create User Request Example (Python) Source: https://typedb.com/docs/reference/typedb-http-api Example of how to create a user using Python's requests library. The password is sent in the JSON body. ```python import requests url = "http://localhost:8000/v1/users/USERNAME" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } body = { "password": "PASSWORD" } response = requests.post(url, headers=headers, json=body) ``` -------------------------------- ### Run Frontend Development Server Source: https://typedb.com/docs/guides/integrations/social-network Start the frontend development server using npm or pnpm. ```bash npm run dev # or pnpm dev ``` -------------------------------- ### Get Server Version using cURL Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get the TypeDB server version using cURL. ```shell curl --request GET \ --url http://localhost:8000/v1/version ``` -------------------------------- ### Basic TypeDB Driver Workflow in Python Source: https://typedb.com/docs/core-concepts/drivers/overview Demonstrates the fundamental steps for connecting to TypeDB, initializing a database with a schema, opening a transaction, executing a query, and processing results. Ensure TypeDB server is running and accessible at the specified address. ```python from typedb.driver import * DB_NAME = "my_database" address = "localhost:1729" credentials = Credentials("admin", "password") options = DriverOptions(is_tls_enabled=False, tls_root_ca_path=None) # 1. Connect to TypeDB with TypeDB.driver(address, credentials, options) as driver: # 2. Initialize database with a schema during application startup try: driver.databases.create(DB_NAME) # raises already exists exception finally: with driver.transaction(DB_NAME, TransactionType.SCHEMA) as tx: tx.query("define entity person;").resolve() tx.commit() # 3. Open a transaction with driver.transaction(DB_NAME, TransactionType.READ) as tx: # 4. Execute queries result = tx.query("match $x label person; fetch { 'entity': $x };").resolve() # 5. Process results for answer in result.as_concept_documents(): print(answer) # 6. Transaction automatically closed, call .commit() to commit and close, or .close() explicitly if not using 'with' # 7. Driver connection automatically closed, or call .close() explicitly if not using 'with' ``` -------------------------------- ### Example JSON Request Body for Deployment Source: https://typedb.com/docs/reference/cloud-http-api A concrete example of the JSON request body used for deploying a cluster. This can be used as a template. ```json { "id":"api-cluster", "serverCount":1, "storageSizeGB":10, "provider":"gcp", "region":"europe-west2", "isFree":true, "machineType":"c2d-highcpu-2", "storageType":"standard-rwo", "version":"latest" } ``` -------------------------------- ### Load Schema and Data into TypeDB Source: https://typedb.com/docs/guides/typeql/insert-update-data Use this Console command to initialize your TypeDB instance with the bookstore example schema and data. Ensure you have a running TypeDB instance and Console. ```bash database create-init bookstore https://github.com/typedb/typedb-examples/releases/download/3.7.0/bookstore-schema.tql https://github.com/typedb/typedb-examples/releases/download/3.7.0/bookstore-data.tql ``` -------------------------------- ### Install and Initialize C# Driver Source: https://typedb.com/docs/home/install/drivers Add NuGet packages for the driver and platform-specific runtimes, then initialize the driver. ```xml ``` ```xml ``` ```csharp using TypeDB.Driver; using TypeDB.Driver.Api; using var driver = TypeDB.Driver(TypeDB.DefaultAddress, new Credentials("admin", "password"), new DriverOptions(false, null)); ``` -------------------------------- ### Insert Data for TypeQL Examples Source: https://typedb.com/docs/core-concepts/typeql/query-variables-patterns This snippet demonstrates how to insert various entities and relationships into TypeDB, serving as foundational data for subsequent query examples. ```typeql insert $james isa person, has name "James", has username "@james"; $typedb isa company, has name "TypeDB", has username "@typedb"; $emp isa employment, links (employer: $typedb, employee: $james); $john isa person, has name "John", has username "@john"; $sky-high isa school, has name "Sky High School", has username "@sky-high"; $edu isa education, links (institute: $sky-high, attendee: $john); $jeff isa person, has name "Jeff", has username "@jeff"; $shut-shop isa company, has name "Shut Shop", has username "@shut-shop"; ``` -------------------------------- ### Get Server Version using Rust Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get the TypeDB server version using Rust's reqwest library. ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/version") .send().await; Ok(()) } ``` -------------------------------- ### Get Server Version using Python Source: https://typedb.com/docs/reference/typedb-http-api Example of how to get the TypeDB server version using Python's requests library. ```python import requests url = "http://localhost:8000/v1/version" response = requests.get(url) ``` -------------------------------- ### Show TypeDB Server Help Source: https://typedb.com/docs/maintenance-operation/typedb-configuration Run this command to see all available command-line options for the TypeDB server. ```bash typedb server --help ``` -------------------------------- ### Create Promotion and Add Items Source: https://typedb.com/docs/guides/typeql/insert-update-data Creates a new promotion with a code, name, and validity period, then links books to it with a specified discount. Use this to manage sales and discounts. ```TypeQL insert $promotion isa promotion, has code "HOL23", has name "Holiday Sale 2023", has start-timestamp 2023-12-01T00:00:00, has end-timestamp 2023-12-31T23:59:59;end; ``` ```TypeQL match $book isa book, has isbn-13 "9780575104419"; $promotion isa promotion, has name "Holiday Sale 2023"; insert $inclusion isa promotion-inclusion, links (promotion: $promotion, item: $book), has discount 0.25;end; ``` ```TypeQL match $book isa book, has isbn-13 "9780060929794"; $promotion isa promotion, has name "Holiday Sale 2023"; insert $inclusion isa promotion-inclusion, links (promotion: $promotion, item: $book), has discount 0.25;end; ``` ```TypeQL match $book isa book, has isbn-13 "9780375801679"; $promotion isa promotion, has name "Holiday Sale 2023"; insert $inclusion isa promotion-inclusion, links (promotion: $promotion, item: $book), has discount 0.25;end; ``` ```TypeQL match $book isa book, has isbn-13 "9780008627843"; $promotion isa promotion, has name "Holiday Sale 2023"; insert $inclusion isa promotion-inclusion, links (promotion: $promotion, item: $book), has discount 0.25;end; ``` ```TypeQL match $book isa book, has isbn-13 "9780500026557"; $promotion isa promotion, has name "Holiday Sale 2023"; insert $inclusion isa promotion-inclusion, links (promotion: $promotion, item: $book), has discount 0.25;end; ``` -------------------------------- ### Example: Retrieve and Sort Posts Source: https://typedb.com/docs/typeql-reference/pipelines/sort This example demonstrates how to retrieve all posts on a given page and sort them from newest to oldest using the sort operator. ```APIDOC ## Example: Retrieve and Sort Posts ### Description Retrieve all posts on a given page, sorted from newest to oldest. ### Query ```typeql match $page isa page, has id ""; $post isa post, has creation-timestamp $created; posting (page: $page, post: $post); sort $created desc; ``` ``` -------------------------------- ### Define Schema for Examples Source: https://typedb.com/docs/core-concepts/typeql/query-clauses Schema definition establishing entities, attributes, and relations used in the subsequent query examples. ```typeql define attribute name, value string; attribute email, value string; relation friendship, relates friend @card(0..2); relation viewing relates viewer, relates viewed; relation posting, relates page, relates post; entity person, owns name, owns email, plays friendship:friend, plays viewing:viewer; entity post, plays posting:post, plays viewing:viewed; entity page plays posting:page; insert $james isa person, has name "James"; $john isa person, has name "John"; $jane isa person, has name "Jane"; ``` -------------------------------- ### Schema Definition Source: https://typedb.com/docs/typeql-reference/patterns/disjunctions Schema setup for the provided disjunction examples. ```typeql define attribute email, value string; attribute phone, value string; attribute username, value string; relation friendship, relates friend @card(0..2); relation marriage, relates spouse @card(0..2); relation policy, relates covered @card(0..); entity user, owns username, owns email, owns phone, plays friendship:friend; entity person, plays marriage:spouse, plays policy:covered; ``` -------------------------------- ### Setup TypeDB Connection and Database Source: https://typedb.com/docs/guides/integrations/graph-viz Sets up the TypeDB driver, connects to the database, and initializes the schema and data. Requires TypeDB version >= 3.7.0. ```python SCHEMA = "" define attribute name, value string; attribute age, value integer; entity person, owns name, owns age; " DATA = "" insert $john isa person, has name "John", has age 20; $jane isa person, has name "Jane", has age 30; " SIMPLE_QUERY = "" match $x isa person, has name $n; " from typedb.driver import TypeDB, Credentials, DriverOptions, TypeDB, QueryOptions, TransactionType DB_ADDRESS = "127.0.0.1:1729" DB_CREDENTIALS = Credentials("admin", "password") DRIVER_OPTIONS = DriverOptions(is_tls_enabled=False) QUERY_OPTIONS = QueryOptions() QUERY_OPTIONS.include_query_structure = True DB_NAME = "typedb-graph-tutorial-py" def setup(driver, schema, data): if DB_NAME in [db.name for db in driver.databases.all()]: driver.databases.get(DB_NAME).delete() driver.databases.create(DB_NAME) with driver.transaction(DB_NAME, TransactionType.SCHEMA) as tx: tx.query(schema).resolve() tx.commit() with driver.transaction(DB_NAME, TransactionType.WRITE) as tx: rows = list(tx.query(data).resolve()) assert 1 == len(rows) tx.commit() driver = TypeDB.driver(DB_ADDRESS, DB_CREDENTIALS, DRIVER_OPTIONS) setup(driver, SCHEMA, DATA) ``` -------------------------------- ### Load Bookstore Schema and Data Source: https://typedb.com/docs/guides/typeql/read-data Use this command in TypeDB Console to initialize the bookstore example with its schema and data. ```bash database create-init bookstore https://github.com/typedb/typedb-examples/releases/download/3.7.0/bookstore-schema.tql https://github.com/typedb/typedb-examples/releases/download/3.7.0/bookstore-data.tql ``` -------------------------------- ### Get Users Requests Source: https://typedb.com/docs/reference/typedb-http-api Example requests to retrieve all users on the server. ```bash curl --request GET \ --url http://localhost:8000/v1/users \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` ```python import requests url = "http://localhost:8000/v1/users" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/users") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Initialize database from remote files Source: https://typedb.com/docs/tools/console Create and initialize a database using remote schema and data files. ```bash database create-init bookstore http://github.com/typedb/typedb-examples/releases/latest/download/bookstore-schema.tql http://github.com/typedb/typedb-examples/releases/latest/download/bookstore-data.tql ``` ```bash typedb console --address=
--username= --command="database create-init bookstore http://github.com/typedb/typedb-examples/releases/latest/download/bookstore-schema.tql http://github.com/typedb/typedb-examples/releases/latest/download/bookstore-data.tql" ``` -------------------------------- ### Initialize C Driver Source: https://typedb.com/docs/home/install/drivers Include the header and initialize the driver with credentials and options. ```c #include "typedb_driver.h" Credentials* credentials = credentials_new("admin", "password"); DriverOptions* options = driver_options_new(false, NULL); TypeDBDriver* driver = driver_open("127.0.0.1:1729", credentials, options); ``` -------------------------------- ### Install and Initialize Java Driver Source: https://typedb.com/docs/home/install/drivers Configure Maven dependencies and initialize the driver using credentials and options. ```xml repo.typedb.com https://repo.typedb.com/public/public-release/maven/ com.typedb typedb-driver {version} ``` ```java import com.typedb.driver.TypeDB; import com.typedb.driver.api.Driver; import com.typedb.driver.api.Credentials; import com.typedb.driver.api.DriverOptions; try (Driver driver = TypeDB.driver(TypeDB.DEFAULT_ADDRESS, new Credentials("admin", "password"), new DriverOptions(false, null))) { ... } ``` -------------------------------- ### Get Database Schema Requests Source: https://typedb.com/docs/reference/typedb-http-api Example requests to retrieve the full database schema. ```bash curl --request GET \ --url http://localhost:8000/v1/databases/DATABASE_NAME/schema \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` ```python import requests url = "http://localhost:8000/v1/databases/DATABASE_NAME/schema" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/databases/DATABASE_NAME/schema") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Get Reducer Arguments (C) Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Retrieves the arguments for a Reducer. For example, `$x` in `sum($x)`. ```c struct VariableIterator* reducer_get_arguments(const struct Reducer* reducer) ``` -------------------------------- ### Get Database Type Schema Requests Source: https://typedb.com/docs/reference/typedb-http-api Example requests to retrieve the database type schema. ```bash curl --request GET \ --url http://localhost:8000/v1/databases/DATABASE_NAME/type-schema \ --header 'Authorization: Bearer {ACCESS-TOKEN}' ``` ```python import requests url = "http://localhost:8000/v1/databases/DATABASE_NAME/type-schema" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } response = requests.get(url, headers=headers) ``` ```rust use reqwest; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::new(); let resp = client .get("http://localhost:8000/v1/databases/DATABASE_NAME/type-schema") .header(reqwest::header::AUTHORIZATION, "Bearer {ACCESS-TOKEN}") .send().await; Ok(()) } ``` -------------------------------- ### Get Reducer Name (C) Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Retrieves the name of the operation applied by this Reducer. For example, `sum` in `sum($x)`. ```c char* reducer_get_name(const struct Reducer* reducer) ``` -------------------------------- ### Get Reducer in ReduceAssignment (C) Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Retrieves the reducer applied in this ReduceAssignment. For example, `sum($x)` in `$c = sum($x)`. ```c struct Reducer* reduce_assignment_get_reducer(const struct ReduceAssignment* reduce_assignment) ``` -------------------------------- ### Get Assigned Variable in ReduceAssignment (C) Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Retrieves the variable being assigned to in this ReduceAssignment. For example, `$c` in `$c = sum($x)`. ```c struct Variable* reduce_assignment_get_assigned(const struct ReduceAssignment* reduce_assignment) ``` -------------------------------- ### Constraining Ownership with @range Source: https://typedb.com/docs/typeql-reference/annotations/range Example of constraining the 'creation-timestamp' attribute owned by a 'post' entity to values starting from January 1, 1970, using the @range annotation. ```typeql define entity post owns creation-timestamp @range(1970-01-01T00:00:00..); attribute creation-timestamp, value datetime; ``` -------------------------------- ### Input Variable Example in TypeQL Source: https://typedb.com/docs/typeql-reference/data-model Demonstrates an input variable '$x' bound in a preceding stage, used in a subsequent 'match' clause. ```typeql match $x isa user, has age 33; limit 1; match friendship ($y, $x); # $x is an input for this stage ``` -------------------------------- ### Example Python Request to Query in Transaction Source: https://typedb.com/docs/reference/typedb-http-api Shows how to execute a query within a transaction using Python's requests library. Ensure the 'requests' library is installed. ```python import requests url = "http://localhost:8000/v1/transactions/TRANSACTION_ID/query" headers = { "Authorization": "Bearer {ACCESS-TOKEN}" } body = { "query": "define entity person;" } response = requests.post(url, headers=headers, json=body) ``` -------------------------------- ### Configure Driver Options Source: https://typedb.com/docs/reference/typedb-grpc-drivers/csharp Sets up connection options, including TLS configuration. ```csharp // No TLS DriverOptions options = new DriverOptions(false, null); ``` ```csharp // TLS with custom CA certificate DriverOptions options = new DriverOptions(true, "/path/to/ca-certificate.pem"); ``` -------------------------------- ### Get Date Value in Seconds from Concept Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Returns the value of this date concept as seconds since the start of the UNIX epoch. If the concept holds a different type, the error flag will be set. ```c int64_t concept_get_date_as_seconds(const struct Concept* concept) ``` -------------------------------- ### Create Courier and Order with Delivery (FedEx Dispatched) Source: https://typedb.com/docs/guides/typeql/read-data This example creates a FedEx courier and an order with a 'dispatched' status. It includes address and location setup. Use this for orders dispatched by FedEx. ```typeql put $courier isa courier, has name "FedEx"; end; ``` ```typeql match $city isa city, has name "Montreal"; put $address isa address, has street "86 East Drive"; (location: $city, located: $address) isa locating; ``` ```typeql match $user isa user, has id "u0009"; $courier isa courier, has name "FedEx"; $city isa city, has name "Montreal"; insert $order isa order, has id "o0021", has status "dispatched"; $execution isa action-execution, links (action: $order, executor: $user), has timestamp 2020-05-23T05:28:33.906; (delivered: $order, deliverer: $courier, destination: $address) isa delivery;end; ``` -------------------------------- ### Compare Queries With and Without Functions Source: https://typedb.com/docs/academy/10-using-functions/10.1-functions-as-views These examples show how to perform a user review verification query using standard match syntax versus using a defined function. ```TypeDB match $user isa user, has id $id; fetch { "user-id": $id, "verified-reviews": ( match rating ($review, $book); order-line ($order, $book); $_ isa action-execution ($user, $review), has timestamp $review-time; $_ isa action-execution ($user, $order), has timestamp $order-time; $review-time > $order-time; return count; ) }; ``` ```TypeDB with fun verified-user-reviews($user: user) -> { review }: match $review isa review; rating ($review, $book); order-line ($order, $book); $_ isa action-execution ($user, $review), has timestamp $review-time; $_ isa action-execution ($user, $order), has timestamp $order-time; $review-time > $order-time; return { $review }; match $user isa user, has id $id; fetch { "user-id": $id, "verified-reviews": ( match let $review in verified-user-reviews($user); return count; ) }; ``` -------------------------------- ### Create New Query Options Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Use this function to initialize a new QueryOptions object. No setup or imports are required. ```c struct QueryOptions* query_options_new(void) ``` -------------------------------- ### Create Courier and Order with Delivery (UPS Canceled) Source: https://typedb.com/docs/guides/typeql/read-data This example creates a UPS courier and an order with a 'canceled' status. It includes address and location setup. Use this to record orders that have been canceled. ```typeql put $courier isa courier, has name "UPS"; end; ``` ```typeql match $city isa city, has name "Montreal"; put $address isa address, has street "86 East Drive"; (location: $city, located: $address) isa locating; ``` ```typeql match $user isa user, has id "u0009"; $courier isa courier, has name "UPS"; $city isa city, has name "Montreal"; insert $order isa order, has id "o0019", has status "canceled"; $execution isa action-execution, links (action: $order, executor: $user), has timestamp 2022-03-08T07:40:28.387; (delivered: $order, deliverer: $courier, destination: $address) isa delivery;end; ``` -------------------------------- ### Get Datetime Value from Concept Source: https://typedb.com/docs/reference/typedb-grpc-drivers/c Returns the value of this datetime concept as seconds and nanoseconds parts since the start of the UNIX epoch. If the concept holds a different type, the error flag will be set. ```c struct DatetimeInNanos concept_get_datetime(const struct Concept* concept) ``` -------------------------------- ### Pipeline and Conjunction Retrieval Source: https://typedb.com/docs/core-concepts/drivers/analyze A TypeQL pipeline consists of stages. Stages can contain conjunctions, which are retrieved using their `ConjunctionID` from the `Pipeline` object. This example shows how to get the root conjunction from the first stage. ```python pipeline = analyzed.pipeline() stages = list(pipeline.stages()) block_id = stages[0].as_match().block() root_conjunction = pipeline.conjunction(block_id) ```