# LLM Access Source: https://docs-relytone.data.cloud/ai-tools/llm RelytONE provides seamless access to OpenAI's latest language models including GPT-4o-mini and GPT-5-mini through a simple, OpenAI-compatible API proxy. Use your existing OpenAI integrations by simply pointing to RelytONE's base URL and authenticating with your Personal API Key. ## Quick Example ```bash curl theme={null} curl -X POST https://relyt.one/api/v1/llm-proxy/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Introduce yourself." } ] }' ``` ```python Python theme={null} from openai import OpenAI client = OpenAI( api_key="", base_url="https://relyt.one/api/v1/llm-proxy/v1/" ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Introduce yourself." } ] ) print(response.choices[0].message.content) ``` ## Base URL ``` https://relyt.one/api/v1/llm-proxy/v1/ ``` ## Authentication Use your Personal API Key as the bearer token. See [Manage API Key](/api/api-key) for details. ## Available Models * `gpt-4o-mini` - GPT-4 Optimized Mini * `gpt-5-mini` - GPT-5 Mini More models will be released progressively to expand your options. ## Pricing & Usage Limits The LLM API is **free for all users** with daily usage limits. We're committed to enhancing your experience by gradually increasing usage limits over time. # Relyt MCP Source: https://docs-relytone.data.cloud/ai-tools/mcp Connect AI assistants to RelytONE using the Model Context Protocol ## Overview The [Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open standard that enables Large Language Models (LLMs) to interact with external systems. RelytONE provides a **local MCP server** that runs on your machine, allowing AI assistants like Cursor and Claude to manage your RelytONE resources through natural language. > [!WARNING] > > **Use with Caution**: This MCP server grants LLMs direct access to manipulate your RelytONE resources, including creating, modifying, and deleting projects and databases. **We strongly recommend NOT using it in production environments.** Only use it in development or testing scenarios where accidental changes won't impact critical systems. ## Prerequisites Before setting up the MCP server, ensure you have: 1. **Node.js** version 18.0.0 or higher installed. Check your version with: ```bash theme={null} node --version ``` 2. **RelytONE API Token**: Generate an API key from the [RelytONE console](https://console.relyt.one) under **Settings → API Keys**. You'll need this token for authentication. ## Setup The MCP server runs locally on your machine using npx. > [tab] Cursor > > > [card] Installation Options > > > > **Option 1: One-Click Install** > > > > [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/zh-Hant/install-mcp?name=relytone\&config=eyJlbnYiOnsiUkVMWVRPTkVfQkVBUkVSX1RPS0VOIjoieW91ci1hcGktdG9rZW4taGVyZSJ9LCJjb21tYW5kIjoibnB4IC0teWVzIEByZWx5dC9tY3Atc2VydmVyLXJlbHl0b25lIn0%3D) > > > > **Option 2: Manual Configuration** > > > > Navigate to **Preferences → Cursor Settings → MCP → New MCP Server** and add: > > > > ```json theme={null} > > { > > "mcpServers": { > > "relytone": { > > "command": "npx", > > "args": ["--yes", "@relyt/mcp-server-relytone"], > > "env": { > > "RELYTONE_BEARER_TOKEN": "your-api-token-here" > > } > > } > > } > > } > > ``` > > > [card] Verify Connection > > > > Once configured successfully, you should see the RelytONE MCP server listed as connected: > > > > ![RelytONE MCP Server Connection Status in Cursor](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/cursor-mcp-connection.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=23d388614dcf14c1d8016e8f06185b84) > [tab] Claude Code > > > [card] Installation > > > > Run the following command in your terminal: > > > > ```bash theme={null} > > claude mcp add npx @relyt/mcp-server-relytone \ > > --env RELYTONE_BEARER_TOKEN=your-api-token-here > > ``` > > > > > [!NOTE] > > > > > > Replace `your-api-token-here` with your actual API token from the [RelytONE console](https://console.relyt.one). > > > [card] Start Using > > > > Start a new Claude Code session and begin using RelytONE MCP with natural language commands! ## Available Tools All [RelytONE APIs](/api/api-introduction) are exposed as MCP tools. The tool names follow the format `-`, such as: * `get-organizations` - List organizations * `get-projects` - List projects * `post-projects` - Create a project * `get-projects-slug-databases` - List databases in a project * `post-projects-slug-databases` - Create a database You don't need to know the exact tool names—simply describe what you want in natural language, and the AI will use the appropriate tools. ## Usage Examples Simply describe what you want in natural language. Here are some examples: **List projects in an organization:** ``` Please list all projects in the "my-org" organization ``` **Create a new project:** ``` Create a project under "my-org" with name "analytics-dev" and description "Development environment for analytics" ``` **Create a database:** ``` Create a database named "customers" in the "analytics-dev" project ``` **Get project details:** ``` Show me the details and compute resources for project "analytics-dev" ``` # Get Organization Details Source: https://docs-relytone.data.cloud/api-reference/organizations/get-organization-details /api/openapi.yaml get /organizations/{id} Get detailed information of an organization by id # Get Organizations List Source: https://docs-relytone.data.cloud/api-reference/organizations/get-organizations-list /api/openapi.yaml get /organizations Get list of organizations that the user has access to # Update Organization Information Source: https://docs-relytone.data.cloud/api-reference/organizations/update-organization-information /api/openapi.yaml patch /organizations/{id} Update basic information of an organization # Create Database Source: https://docs-relytone.data.cloud/api-reference/project-resources/create-database /api/openapi.yaml post /projects/{id}/databases Create a new database under the specified project # Get Compute Resource Details Source: https://docs-relytone.data.cloud/api-reference/project-resources/get-compute-resource-details /api/openapi.yaml get /projects/{id}/computes/{computeId} Get detailed information of a specific compute resource # Get Compute Resource Metrics Source: https://docs-relytone.data.cloud/api-reference/project-resources/get-compute-resource-metrics /api/openapi.yaml post /projects/{id}/computes/{computeId}/metrics Get performance metrics data for compute resources # Get Project Compute Resources List Source: https://docs-relytone.data.cloud/api-reference/project-resources/get-project-compute-resources-list /api/openapi.yaml get /projects/{id}/computes Get all compute resources for a project # Get Project Databases List Source: https://docs-relytone.data.cloud/api-reference/project-resources/get-project-databases-list /api/openapi.yaml get /projects/{id}/databases Get all databases for a project # Create New Project Source: https://docs-relytone.data.cloud/api-reference/projects/create-new-project /api/openapi.yaml post /projects Create a new project under the specified organization # Delete Project Source: https://docs-relytone.data.cloud/api-reference/projects/delete-project /api/openapi.yaml delete /projects/{id} Soft delete project (mark as deleted) # Get Project Details Source: https://docs-relytone.data.cloud/api-reference/projects/get-project-details /api/openapi.yaml get /projects/{id} Get detailed information of a project by id # Get Projects List Source: https://docs-relytone.data.cloud/api-reference/projects/get-projects-list /api/openapi.yaml get /projects Get list of projects for the specified organization # Update Project Information Source: https://docs-relytone.data.cloud/api-reference/projects/update-project-information /api/openapi.yaml patch /projects/{id} Update basic information of a project # Create API Key Source: https://docs-relytone.data.cloud/api-reference/user/create-api-key /api/openapi.yaml post /user/api-keys Create a new API key for the current user # Delete API Key Source: https://docs-relytone.data.cloud/api-reference/user/delete-api-key /api/openapi.yaml delete /user/api-keys Delete the specified API key # Get User API Keys List Source: https://docs-relytone.data.cloud/api-reference/user/get-user-api-keys-list /api/openapi.yaml get /user/api-keys Get all API keys for the current user # RelytONE API Source: https://docs-relytone.data.cloud/api/api-introduction The RelytONE API enables you to manage your Relyt projects programmatically. View all available methods in the [API reference](/api-reference/). This is a REST API that provides: * Resource-oriented URLs * JSON-encoded request and response bodies * Standard HTTP response codes and verbs ## Authentication Authenticate requests using API keys with bearer token authentication. Learn how to [manage API keys](/api/api-key). Include your API key in the `Authorization` header: ```bash theme={null} curl --request POST \ --url https://relyt.one/api/v1/user/api-keys \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "name": "", "description": "" }' ``` ## Base URL All API requests use this base URL: ```bash theme={null} https://relyt.one/api/v1 ``` **Common Endpoints:** * List all organizations: `https://relyt.one/api/v1/organizations` * List all projects: `https://relyt.one/api/v1/projects` ## Next Steps Explore the [API reference](/api-reference) to test and execute API requests directly. # Manage API Keys Source: https://docs-relytone.data.cloud/api/api-key API keys authenticate your requests to the [RelytONE API](/api-reference). Each key is a randomly-generated token that remains valid until revoked. ## API Key Types RelytONE currently supports **Personal API Keys**: | **Key Type** | **Scope** | **Validity** | | - | - | - | | Personal Key | All organization projects where the user is a member | Valid until revoked; access ends if user leaves organization | ## Create an API Key ### Via Console Navigate to **Organization Settings** > **API Keys** in the RelytONE Console. > [!NOTE] > > Create your first API key from the Console, then use it to manage additional keys via API. ![Frame21 Jp](https://mintcdn.com/relytone/WPpCTTEQCQzF-r65/images/Frame21.jpg?fit=max\&auto=format\&n=WPpCTTEQCQzF-r65\&q=85\&s=367a993466197a6cbbb574e43543da56) ### Via API Use an existing API key to create new keys programmatically: ```bash theme={null} curl --request POST \ --url https://relyt.one/api/v1/user/api-keys \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "name": "", "description": "" }' ``` **Response:** ```json theme={null} { "id": "", "key": "", "fullKey": "", "name": "", "description": "", "createdAt": "2023-11-07T05:31:56Z", "consumerId": "", "consumerUsername": "" } ``` ## Additional Operations For more API key management operations, see: * [List API Keys](/api-reference/user/get-user-api-keys-list) * [Create API Key](/api-reference/user/create-api-key) * [Delete API Key](/api-reference/user/delete-api-key) # Own Your AI Coding Assistant: A Self-Hosted, Open-Source Code Agent Source: https://docs-relytone.data.cloud/blog/code-agent # What’s Missing in Today’s AI Coding Tools? Over the past two years, we’ve seen a surge of "AI + coding" products. A representative example is Claude Code, which stands out for its clean interaction design and its ability to quickly generate code through conversational prompts. However, it comes with three well-known drawbacks that many developers have likely encountered: ### **Context Is Often Missing** In the traditional Claude Code / CodeX CLI workflow: * **Input →** A pile of code snippets you manually copy and paste. * **Model →** Forced to *guess* the context based only on natural language and raw strings. This leads to two critical issues: * **Lost cross-file references:** The LLM has no way to access complete project context. * **Blurry semantic boundaries:** The model only sees "a few isolated lines of code", not the full business logic. As a result, the lack of truly relevant context directly impacts the quality of code generation. The workaround is to feed in *more and more* context to patch the missing semantics and information — but that quickly drives up the cost, which we’ll discuss next. ### High Usage Costs Claude is undeniably powerful, but the price can be a *deal-breaking barrier* for both enterprises and individual developers in everyday use. For example, with **Claude Opus 4.1**, Base Input Tokens are priced at **\$15 / MTok** and Output Tokens at **\$75 / MTok(**[Reference](https://www.anthropic.com/pricing#api)**)**—just a few back-and-forth interactions can easily rack up tens of dollars. Cursor has become popular among developers and effectively addresses the context problem. However, since **September 15**, Cursor no longer allows subscribers to use Auto Mode without limits. Auto requests now count against the included usage quota of your plan. ([Reference](https://cursor.com/blog/aug-2025-pricing))  ### Privacy and Restriction Concerns Cursor not only faces high usage costs, but its privacy and closed-source limitations are equally concerning. * **Security risks:** During the *codebase indexing* stage, the official documentation states that *"embeddings and metadata are stored in the cloud."* While source code itself may not be stored, transmitting it over the network is unavoidable. ([Reference](https://docs.cursor.com/en/context/codebase-indexing)) * **Closed-source limitations:** Cursor operates as a closed-source black box, leaving no way to audit how it actually works. Persistent telemetry runs in the background, continuously sending analytics calls. Even when the app is idle, unexplained data streams maintain live connections to their servers. More concerning, the platform repeatedly re-ingests your entire codebase without explicit consent—sometimes even a brief pause can trigger a full reprocessing. # Claude Context: Zilliz’s Open-Source Solution for Code Context **Claude Context** is an open-source, MCP-compatible semantic code search engine. Whether you’re building a custom AI coding assistant from scratch or adding semantic awareness to existing agents like Claude Code or Gemini CLI, Claude Context provides the engine to make it possible. It runs locally, integrates seamlessly with your favorite tools and environments (such as **VS Code** and **Chrome**), and delivers powerful code-understanding capabilities—without depending on closed-source, cloud-only platforms. ([Reference](https://milvus.io/zh/blog/build-open-source-alternative-to-cursor-with-code-context.md)) At its core, **Claude Code** functions as a **RAG (Retrieval-Augmented Generation) engine**, composed of three main modules: * **Text Processing:** Syntax-based logic for segmenting code into meaningful chunks. * **Embedding Service:** Integrates with popular cloud-hosted embedding providers. * **Vector Database:** Connects to either local or cloud-hosted **Milvus** vector engines. ![Zilliz Pn](https://mintcdn.com/relytone/t2rr1M4X9EzYwT0a/images/zilliz.png?fit=max\&auto=format\&n=t2rr1M4X9EzYwT0a\&q=85\&s=b00d5897c0e51ac653badd022c8a249a) # Enhancements For **Fully-local**, **Self-hosted** Code Context To enable a fully local deployment of the coding agent, we enhanced Claude Code with the following two features: * **Vector Search with Postgres:** No longer limited to a single vector database—you can run directly on Postgres, either locally, cloud, or your existing PG infra. For example, spin up a Dockerized Postgres instance on your laptop, or use lightweight Postgres services like [****Relyt ONE(https://relyt.one)****](https://relyt.one) or [****Neon(https://neon.com/)****](https://neon.com/). * **Encryption:** Many companies worry about whether AI might "leak" source code. To address this, indexing can store data in encrypted form, with decryption happening only in local memory at runtime. This ensures your entire development workflow continues to operate strictly within a **private boundary**. ![Enhanced Pn](https://mintcdn.com/relytone/t2rr1M4X9EzYwT0a/images/enhanced.png?fit=max\&auto=format\&n=t2rr1M4X9EzYwT0a\&q=85\&s=737b35ed13dea499c090d5ca6056f845) # **Hands On** To achieve a fully localized deployment of **Claude Context** and enhance **CodeX CLI** with stronger contextual capabilities, we use a local **Ollama Embedding Model** together with a Dockerized **Postgres** setup. With the following script, you can perform **one-click installation and configuration**: ``` curl -fsSL https://raw.githubusercontent.com/YuweiXiao/code-context/refs/heads/main/install-mcp-setup.sh | bash ``` The script will automatically install and configure all required components for running Claude Context locally: * **Ollama installation and embedding model download** * **Postgres download and setup** * **CodeX configuration rendering: Claude Context MCP** ### Common Issues * **Ollama is not installed on macOS** * On macOS, Ollama must be installed manually via the `.dmg` package: [Ollama Download](https://ollama.com/download/mac) * After installation, re-run the script (note: you must manually run `ollama` once after the dmg installation). * **Docker is not installed. Please install Docker first.** * If you run the configuration script *without* providing a `postgres-url` parameter, the script will automatically spin up a local Postgres instance as the vector engine. This requires a Docker environment, so you’ll need to install Docker first. * If you prefer not to install Docker, you can create a Postgres database using a managed service such as **Relyt ONE**, and then provide the connection string when running the script. Once configuration is complete, simply restart **CodeX** to start using it. ``` cd # start codex > codex # Check MCP Installation. If everything is working properly, you should be able to see "claude-context mcp". > /mcp # Ask codex to index the codebase > index this codebase # The indexing is async, check indexing status > Check the indexing status # Start search > Find functions related to XXX ``` **1. New Step** # How to configure Relyt ONE in Dify? Source: https://docs-relytone.data.cloud/blog/dify-work-flow # Dify self-hosting Dify is an open-source platform for developing LLM applications. Its intuitive interface combines agentic AI workflows, RAG pipelines, agent capabilities, model management, observability features, and more—allowing you to quickly move from prototype to production. ([Reference](https://github.com/langgenius/dify)) In this guide, we'll walk you through setting up Dify with Relyt ONE (All In One Serverless PostgreSQL) to build a knowledge base Q\&A workflow. # Quick start The easiest way to get Dify up and running is through [Docker Compose](https://github.com/langgenius/dify/blob/main/docker/docker-compose.yaml). Before we dive in, make sure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your machine. ### Clone Dify You can visit the GitHub repository ([https://github.com/langgenius/dify](https://github.com/langgenius/dify)) to clone it manually, or simply run the following command: ``` git clone https://github.com/langgenius/dify.git ``` ### Prepare Docker Compose Head to [https://www.docker.com/](https://www.docker.com/) to download Docker Desktop. Make sure to select the correct version for your system. Run this command to verify Docker is properly installed: ``` docker --version ``` # Get a Relyt ONE Serverless PostgreSQL Relyt ONE provides free PostgreSQL service. Visit our website ([https://relyt.one](https://relyt.one)) to get started for free. ### Create a Project Once you're logged in, create a new project on the Projects page. ([Reference](/docs/create-project)) ![Frame17 Pn](https://mintcdn.com/relytone/pi8VPkBOtJGoqO9S/images/Frame17.png?fit=max\&auto=format\&n=pi8VPkBOtJGoqO9S\&q=85\&s=03d02aa4c160632a3eb9c59ba7232d79) ### Check Project Connect Info Once you're in the project, click the '**Connect**' button to open the Connect dialog, then switch to the '**GUI Client Application Tab**' to view your connection details. You'll see information like host, port, database, and user. ([Reference](/docs/connect)) ![Project connect dialog GUI tab](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/project-connect-gui-tab.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=4d30ef6e5436898e87eb38bb7f7ebced) ### Configure DB connect parameters in Dify Head to your Dify project's root directory and find the '**docker**' folder. Inside, rename '**.env.example**' to '**.env**' and open it. Jump to the '**Vector Database Configuration**' section, then select '**pgvecto-rs configurations**' to set up your parameters. ``` VECTOR_STORE=pgvecto-rs ... # pgvecto-rs configurations, only available when VECTOR_STORE is `pgvecto-rs` PGVECTO_RS_HOST=[your database host] PGVECTO_RS_PORT=[your database port] PGVECTO_RS_USER=[your database role name] PGVECTO_RS_PASSWORD=[your database password] PGVECTO_RS_DATABASE=[your database name] ``` Then you can initialize Dify with docker compose. ``` docker compose up -d ``` Now, you can access the Dify dashboard in your browser at [http://localhost/install](http://localhost/install) and start the initialization process. ### Create Knowledge on Dify Visit Dify at [http://localhost/install](http://localhost/install), navigate to the Knowledge Tab in the header, and click the 'Create Knowledge' button. ![Dify create knowledge modal](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-create-knowledge.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=c5872d620714ebf1ea2d5ec15c3cbe33) Select your source—for this demo, I'll upload content from a local Markdown document. Next, configure the chunk settings. Pay special attention to the '**maximum chunk length**' setting, as different lengths can produce varying results. You'll want to adjust this based on your specific use case. ![Dify knowledge chunk settings](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-knowledge-chunk-settings.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=afead451bdfd223e3b6870d9dbcf79c7) ### Verify DB connection Follow the guided steps to create your knowledge base. Once it's created, you can verify everything worked by checking your database schema—you should see the knowledge records appear in the table. ![Knowledge records stored in database table](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/database-knowledge-records.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=1f423ec998beaac19d25b7f48be7dc74) # Create Knowledge Base Workflow ### Create workflow Head back to Dify's Studio Tab and click 'Create App' to start building your workflow: * Create App * Select ‘Create from Blank’ * Choose an App Type * Select ‘Chatflow’ type ![Dify create app screen](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-create-app.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=cad70d9e39b2c45e3e059f1dfcbfaae6) After following the guide to create your workflow, you'll enter the workflow builder interface. Now, click the add button between the '**Start**' node and the '**LLM**' node to add a new '**Knowledge Retrieval**' node. ![Adding a knowledge retrieval node in Dify workflow](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-add-knowledge-node.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=429f40a7c7a8649a1f31c09bd97ab882) ![Knowledge retrieval node added to Dify workflow](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-knowledge-node-layout.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=9801abebbc274d61fbf58cbb51d55443) In the Knowledge Retrieval node's settings panel, click the '**Add**' button and select the knowledge base you created earlier. ![Selecting a knowledge base for the retrieval node](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-select-knowledge-base.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=c3bd8cf9e1f60706b1e1672db60a2013) ### LLM Provider API Key Configuration Next up is the LLM node. First, you need to configure the LLM provider API key. Follow this path: ``` LLM Node Panel > Settings > Model > Model selection popup menu > Model Provider Settings ``` ![LLM node settings panel in Dify](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-llm-node-settings.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=d3a525b3d8823796c878a6525556dafd) ![Model provider settings dialog in Dify](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/dify-provider-settings.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=f2e8f260cff1eac783c4cc25ecf1e38d) Then navigate to the configuration page and set up your API key. You can refer to Dify's documentation ([https://platform.openai.com/api-keys](https://platform.openai.com/api-keys)) for detailed instructions. ![Frame19 Jp](https://mintcdn.com/relytone/T399sYdcbjeBb_lX/images/Frame19.jpg?fit=max\&auto=format\&n=T399sYdcbjeBb_lX\&q=85\&s=5f58e83648c95a170cf9ea444cdb1bb6) ### Finish and Run Once you complete all the setup steps above, you can test your workflow. Congratulations—your knowledge base Q\&A system is now ready to go! # About Relyt ONE Relyt ONE is a Serverless PostgreSQL database, providing built-in high performance extensions for vectors, full-text search and analytics (pg\_duckdb). We believe in technological equality and inclusive support for all developers. All features and services are included in the free plan. We welcome you to give it a thorough try! ![Relyt ONE console overview](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/relyt-one-console-overview.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=bc32e0e5d572c586823fe2d4b3424eca) # Use n8n to Chat with Your RelytONE Database Source: https://docs-relytone.data.cloud/blog/n8n-chat-database # Why n8n + RelytONE? [n8n](https://n8n.io/) is a low-code automation platform that chains triggers, APIs, and AI nodes into reusable workflows. In this guide we’ll connect n8n’s “Chat with a database using AI” template to RelytONE—routing prompts through our LLM proxy and running SQL on our PostgreSQL compute—so you can talk to your database through natural language. # Prerequisites * A RelytONE project with at least one compute running (get one for free at [https://relyt.one](https://relyt.one)). * A RelytONE LLM proxy token. Create and manage tokens in the console via `AI Tools > LLM Access`. [See docs](../ai-tools/llm). * Access to n8n Cloud or a self-hosted n8n instance. # 1. Start from n8n’s AI + Database Template Import the [Chat with a Database using AI](https://n8n.io/workflows/2090-chat-with-a-database-using-ai/) template. n8n will open the template setup page with two options: * **OpenAI Chat Model** – LLM credential. * **Postgres Tool** – database credential. # 2. Configure the LLM Node with RelytONE In **OpenAI Chat Model**, click the pencil icon: * **Base URL / Endpoint**: `https://relyt.one/api/v1/llm-proxy/v1/` * **Access Token**: paste your RelytONE token n8n handles the rest—no custom headers needed. ![Configure LLM node with RelytONE](https://mintcdn.com/relytone/WTaY6JGoeJCOrZEe/images/n8n-configure-llm.jpg?fit=max\&auto=format\&n=WTaY6JGoeJCOrZEe\&q=85\&s=dbe946d0bbbd9d1e4e5a1b0d7d5b0f50) # 3. Connect the Postgres Node to RelytONE Compute In **Postgres Tool**, edit the credential and copy everything from `Project > Connect`: * **Host / Port / Database / User**: as shown in the dialog * **Password**: input manually (RelytONE does not retain it) * **SSL Mode**: `require` Save to bind the Postgres node to your compute. ![Configure Postgres node with RelytONE compute](https://mintcdn.com/relytone/WTaY6JGoeJCOrZEe/images/n8n-configure-pg.jpg?fit=max\&auto=format\&n=WTaY6JGoeJCOrZEe\&q=85\&s=c062b032cc308ddaf5f810beae84cd46) # 4. Chat with Your Data Once both options are green, click `Continue` to open the workflow. Use the lower-left chat panel to ask questions; the LLM turns prompts into SQL, runs them on RelytONE over SSL, and replies in the same pane. ![Chatting with database through n8n](https://mintcdn.com/relytone/WTaY6JGoeJCOrZEe/images/n8n-chat-database.jpg?fit=max\&auto=format\&n=WTaY6JGoeJCOrZEe\&q=85\&s=a8a266c8d34dedcac121ce281be8672a) # About RelytONE RelytONE is an all-in-one serverless PostgreSQL with built-in vector search, full-text indexing, and pg\_duckdb analytics. It also delivers LLM access, observability, so you can launch AI-native workflows without reaching for extra tooling. # TPC-H Benchmark: One-Click Verification of Relyt ONE Analytics Performance Source: https://docs-relytone.data.cloud/blog/tpch-benchmark-en Quickly evaluate Relyt ONE OLAP capabilities using the pre-configured TPC-H 1GB dataset ## Overview Relyt ONE delivers exceptional analytical performance powered by our caching service and the DuckDB execution engine. To enable users to quickly evaluate the system's OLAP capabilities, we provide a pre-configured TPC-H standard benchmark dataset that supports out-of-the-box, one-click performance testing. ### What is TPC-H? TPC-H is a decision support benchmark standard established by the Transaction Processing Performance Council (TPC). It simulates a real-world data warehouse environment with 8 business tables and 22 complex analytical queries, covering common OLAP scenarios including aggregations, joins, and subqueries. TPC-H is widely used to evaluate and compare the analytical performance of database systems. ### Why Use a Pre-configured Dataset? * **Quick start**: Ready immediately after project creation * **Standardized testing**: Industry-recognized benchmark with meaningful, comparable metrics * **Repeatability**: Unified data layout and configuration across environments ### Dataset Architecture The pre-configured TPC-H 1GB dataset is created as external tables, with actual data stored on S3 object storage. Through Relyt ONE's auto caching service, the system automatically caches hot data, delivering high-throughput, low-latency data access. ## Usage Guide ### 1. Connect to Database The pre-configured dataset lives in the `tpch` schema of the `postgres` database. **1. Connect via psql** ```bash theme={null} PGSSLMODE=require psql -h relyt-g94eh8mxxxxx.us-ca.relyt.one -U relytdb_owner -d postgres ``` > [!NOTE] > > Replace the host address in the connection string with your actual project address. You can obtain the complete connection information from the console. ### 2. Explore the Dataset **1. List schema objects** ```sql theme={null} -- Tables \dt tpch.* -- Views (pre-defined 22 queries) \dv tpch.* ``` **2. Preview sample rows** ```sql theme={null} SELECT * FROM tpch.nation; SELECT * FROM tpch.lineitem LIMIT 10; ``` **3. Check table sizes** ```sql theme={null} SELECT 'customer' AS table_name, count(*) FROM tpch.customer UNION ALL SELECT 'orders', count(*) FROM tpch.orders UNION ALL SELECT 'lineitem', count(*) FROM tpch.lineitem; ``` ### 3. Execute Individual Queries All 22 standard TPC-H queries ship as views (`q01` through `q22`). **1. Run a specific query** ```sql theme={null} SELECT * FROM tpch.q03; SELECT * FROM tpch.q06; ``` **2. Inspect execution plans** Use `EXPLAIN ANALYZE` to view execution plans and timing: ```sql theme={null} EXPLAIN ANALYZE SELECT * FROM tpch.q01; ``` > [!NOTE] > > Views encapsulate the official TPC-H SQL so you can focus on performance validation rather than query maintenance. ### 4. One-Click Performance Testing **1. Run the full suite** ```sql theme={null} SELECT * FROM tpch.run_benchmark(); ``` The function executes each query twice: * **Cold run** loads data from S3 into cache. * **Hot run** reuses cached data to demonstrate steady-state performance. **2. Interpret the output** Hot-run metrics provide the most representative view of production behavior: | Query # | Execution Time (ms) | Row Count | Status | | :-: | -: | -: | :-: | | 1 | 173.45 | 4 | SUCCESS | | 2 | 39.07 | 100 | SUCCESS | | 3 | 87.42 | 10 | SUCCESS | | 4 | 77.47 | 5 | SUCCESS | | 5 | 91.02 | 5 | SUCCESS | | 6 | 43.94 | 1 | SUCCESS | | 7 | 94.25 | 4 | SUCCESS | | 8 | 108.99 | 2 | SUCCESS | | 9 | 203.4 | 175 | SUCCESS | | 10 | 153.52 | 20 | SUCCESS | | 11 | 27.23 | 1048 | SUCCESS | | 12 | 68.5 | 2 | SUCCESS | | 13 | 222.47 | 42 | SUCCESS | | 14 | 61.18 | 1 | SUCCESS | | 15 | 87.09 | 1 | SUCCESS | | 16 | 64.68 | 18314 | SUCCESS | | 17 | 67.44 | 1 | SUCCESS | | 18 | 179.22 | 57 | SUCCESS | | 19 | 185.97 | 1 | SUCCESS | | 20 | 64.35 | 186 | SUCCESS | | 21 | 255.63 | 100 | SUCCESS | | 22 | 53.99 | 7 | SUCCESS | Result columns explained: * `query_num`: Query number (1-22) * `execution_time_ms`: Hot Run execution time in milliseconds * `row_count`: Number of rows returned * `status`: Execution status ## Performance Reference Below are TPC-H 1GB Hot Run results for Relyt ONE under different configurations. Each value represents the per-query execution time in milliseconds: | query\_num | 1 vCPU (ms) | 2 vCPU (ms) | 4 vCPU (ms) | | :-: | -: | -: | -: | | 1 | 570.57 | 323.57 | 182.67 | | 2 | 82.79 | 59.52 | 50.25 | | 3 | 350.26 | 171.21 | 108.80 | | 4 | 260.28 | 174.01 | 93.80 | | 5 | 309.06 | 176.48 | 107.33 | | 6 | 148.61 | 86.23 | 50.42 | | 7 | 280.33 | 202.57 | 117.94 | | 8 | 334.19 | 233.00 | 127.51 | | 9 | 596.58 | 379.15 | 234.15 | | 10 | 322.58 | 235.33 | 175.58 | | 11 | 60.28 | 48.04 | 35.27 | | 12 | 216.86 | 124.52 | 80.13 | | 13 | 761.56 | 450.64 | 229.10 | | 14 | 173.94 | 119.24 | 77.98 | | 15 | 273.00 | 167.99 | 99.32 | | 16 | 115.87 | 90.06 | 75.97 | | 17 | 211.57 | 120.52 | 79.28 | | 18 | 527.96 | 345.42 | 195.62 | | 19 | 581.96 | 360.51 | 216.49 | | 20 | 173.12 | 107.07 | 80.55 | | 21 | 853.32 | 511.36 | 327.68 | | 22 | 65.70 | 60.71 | 62.79 | > [!NOTE] > > The `run_benchmark()` function automatically performs Cold/Hot dual testing. The reference data in the table above are all Hot Run results. Actual performance may vary due to network conditions, concurrent load, and other factors. ## Custom Testing If you need to test larger datasets (e.g., 10GB, 100GB, 1TB), follow this process: 1. **Generate Data**: Use the official TPC-H `dbgen` tool to generate datasets at the desired scale 2. **Upload to S3**: Upload the generated data files to your object storage 3. **Create External Tables**: Map S3 data files through [external tables](/features/external_table) in Relyt ONE. 4. **Execute Queries**: Reference query views in the pre-configured `tpch` schema or test with custom queries ## FAQ **Q: Why execute Cold Run and Hot Run?**\ A: Cold Run reflects performance when querying data loaded from S3 for the first time, while Hot Run reflects performance when data is already cached. Hot Run is closer to actual production performance as hot data is automatically cached. **Q: Can TPC-H testing represent my actual business performance?**\ A: TPC-H provides standardized performance reference, but actual business performance also depends on data models, query patterns, indexing strategies, and other factors. It's recommended to conduct additional testing with real business data. # Branching Source: https://docs-relytone.data.cloud/docs/branch Instantly create isolated environments for development, testing, and recovery. RelytONE branching lets you instantly create a full copy of your database. Use branches to safely test changes, debug issues, or run analytics without affecting your live production data. ![Database Branching Diagram](https://mintcdn.com/relytone/dSnkOFzsx2vBECyE/images/branch.png?fit=max\&auto=format\&n=dSnkOFzsx2vBECyE\&q=85\&s=ef7f290949448d24c2e5fb5b18f9666d) ## Why use branches? * **Isolated:** Changes in a branch stay in that branch. Your production data is never touched. * **Fast & Efficient:** Creating a branch takes seconds and costs nothing in storage until you make changes. * **Zero Overhead:** Branching happens without slowing down your main database. ## Common Use Cases ### Safe Development & Testing * **Preview Environments:** Give every pull request its own dedicated database. * **Real Data Testing:** Test new features against a copy of production data to catch bugs early. * **Schema Validation:** Try out risky schema changes on a disposable branch before applying them to `main`. ### Instant Recovery & Debugging * **Forensics:** Create a branch from a past timestamp to investigate exactly what the database looked like when an error occurred. * **Data Recovery:** If data is accidentally deleted, spin up a branch from the moment before the deletion to recover it. ### Analytics Isolation * **Heavy Queries:** Run complex analytical queries on a separate branch so you don't slow down your transactional application. ## Branching vs. Read Replicas While both branches and read replicas provide copies of your data, they serve different purposes: | Feature | Branch | Read Replica | | :- | :- | :- | | **Data State** | Static snapshot at creation time (diverges as you write) | Continuously synchronized with the primary | | **Writes** | **Read-Write** (Independent) | **Read-Only** | | **Best For** | Development, Testing, Recovery, Experiments | Scaling read traffic, High Availability | | **Impact** | Isolated from primary | Linked to primary (replication lag) | ## How it Works Every RelytONE project starts with a primary `main` branch. You can create new branches from `main` or any other existing branch. Each branch functions as an independent database with its own connection string. You can connect to it using standard PostgreSQL tools. When you are finished with a task, simply delete the branch to keep your environment clean. # Connect Database Source: https://docs-relytone.data.cloud/docs/connect This guide explains how to connect to Relyt (PostgreSQL‑compatible) using psql, popular drivers, and GUI tools. It covers general connection settings and security, where to find your connection parameters, and concise examples plus troubleshooting for common clients. ## 1. General Connection Settings ### Connection Parameters The connection details for your database are available in the Connect panel of the Relyt console. You can copy a ready-to-use connection string for common clients or copy individual parameters. ```text theme={null} postgresql://relytdb_owner:[your_password_here]@relyt-t8e2q4l3we7w-pooler.us-ca.relyt.one/relytdb?sslmode=require | | | | | | | | | +--> database name | +-----> password +------> hostname | | | +-----> username +--> "-pooler" suffix indicates server-side pooling ``` ![Gui Console Pn](https://mintcdn.com/relytone/t2rr1M4X9EzYwT0a/images/gui_console.png?fit=max\&auto=format\&n=t2rr1M4X9EzYwT0a\&q=85\&s=5e7d5d3f992e1fbc738c0a0e9a02a217) ### Connection Pooling Every Relyt compute has server-side connection pooling enabled. To use it, connect to the hostname with the `-pooler` suffix. * Powered by [PgBouncer](https://www.pgbouncer.org/) * Supports up to 10,000 concurrent client connections * Configured with `pool_mode=transaction` (see [feature details](https://www.pgbouncer.org/features.html)) You can also keep client-side connection pools in your application; they complement the server-side pool to smooth spikes and reduce latency. ### TLS/SSL Security Relyt requires TLS for all connections. Connections that do not use SSL/TLS are rejected. The minimum acceptable setting is `sslmode=require`. For stronger protection against man-in-the-middle attacks, prefer `sslmode=verify-ca` or `sslmode=verify-full`. When using `verify-ca` or `verify-full`, ensure the appropriate CA root is available on the host or provide `sslrootcert` explicitly. | sslmode | | Verification and Behavior | | - | - | - | | require | Minimum required | TLS required; no CA/hostname verification | | verify-ca | Recommended | TLS required; verifies CA; provide `sslrootcert` if needed | | verify-full | Recommended | TLS required; verifies CA and hostname; provide `sslrootcert` if needed | ## 2. PSQL Connection psql is the official command-line client tool provided by PostgreSQL and is the most direct way to connect to Relyt. ```powershell theme={null} psql 'postgres://[user]:[password]@[hostname]/[database]?sslmode=require' ``` ## 3. Python Connection Python is one of the most commonly used languages in data analysis and backend development. Through the psycopg2 driver, you can easily connect to and operate Relyt databases in Python applications. The following introduces two common connection methods: connection pooling and direct connection. ### Install Dependencies Before getting started, you need to install the PostgreSQL Python driver. `psycopg2-binary` is a pre-compiled binary version that is more convenient to install and suitable for most use cases. ```powershell theme={null} pip install psycopg2-binary ``` ### Connection Pool Method Connection pooling is the recommended connection method for production environments, especially suitable for high-concurrency web applications. Connection pooling can reuse database connections, avoiding performance overhead from frequently establishing and disconnecting connections, while also controlling the maximum number of connections to prevent too many database connections. ```python theme={null} from psycopg2 import pool connection_url = f"postgresql://[username]:[password]@[hostname]/[database]?sslmode=require" connection_pool = pool.SimpleConnectionPool(1, 5, connection_url) conn = connection_pool.getconn() cur = conn.cursor() cur.execute("SELECT version();") result = cur.fetchone() print("PostgreSQL version:", result[0]) cur.close() connection_pool.putconn(conn) connection_pool.closeall() ``` ### Direct Connection Method The direct connection method is suitable for simple scripts and one-time operations. This approach has more intuitive code and is suitable for learning and debugging. ```python theme={null} import psycopg2 conn = psycopg2.connect( host="[hostname]", port=5432, user="[user]", password="[password]", dbname="[database]", sslmode="require" ) cur = conn.cursor() cur.execute("SELECT version();") result = cur.fetchone() print("PostgreSQL version:", result[0]) cur.close() conn.close() ``` ## 4. Java Connection Java is the mainstream language for enterprise application development. You can easily connect to Relyt databases through the PostgreSQL JDBC driver. JDBC (Java Database Connectivity) is Java's standard database connection API, providing a unified database access interface. > [!NOTE] > > **Requirement**: PostgreSQL jar package version must be at least 42.2.6 ### URL Parameter Method This is the most common JDBC connection method, where all connection parameters are included in the connection URL. This method is suitable for applications with relatively fixed configurations. ```java theme={null} import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; String url = "jdbc:postgresql://[host]:[port]/[database]?user=[username]&password=[password]&sslmode=require"; Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT version();"); if (rs.next()) { System.out.println("PostgreSQL version: " + rs.getString(1)); } rs.close(); stmt.close(); conn.close(); ``` ### Properties Method Using a Properties object to configure connection parameters provides greater flexibility, especially suitable for scenarios that require dynamic configuration of connection parameters, such as reading connection information from configuration files. ```java theme={null} import java.util.Properties; String url = "jdbc:postgresql://[host]:[port]/[database]"; Properties props = new Properties(); props.setProperty("user", "[username]"); props.setProperty("password", "[password]"); props.setProperty("sslmode", "require"); Connection conn = DriverManager.getConnection(url, props); ``` ### Configure Application Name Setting a meaningful name for your application is a good practice that helps database administrators identify and monitor different client connections. Add the ApplicationName parameter to the connection string: ``` jdbc:postgresql://localhost:5435/MyDB?ApplicationName=MyApp ``` > [!NOTE] > > **Note**: After configuration, administrators can view which client a session belongs to through `pg_stat_activity`. This is very useful for troubleshooting and performance monitoring. **Reference Documentation**: [https://jdbc.postgresql.org/documentation/use/](https://jdbc.postgresql.org/documentation/use/) ## 5. GUI Client Applications For users who are not familiar with command-line operations, or for scenarios that require complex data browsing and management, graphical database management tools provide a more intuitive operating interface. These tools typically provide data table browsing, SQL query editors, data import/export, database structure management, and other functions. To connect to Relyt through GUI applications, you generally need to provide the following information: * hostname * port * username * password * database Except for the password, all this information can be obtained from the Connect interface in the console. ### pgAdmin4 pgAdmin is the officially recommended web interface management tool for PostgreSQL, which is powerful and completely free. It provides complete database management functions, including database object management, SQL query execution, performance monitoring, backup and recovery, etc. > [!NOTE] > > [https://www.pgadmin.org/](https://www.pgadmin.org/) ![Pgadmin Gui Pn](https://mintcdn.com/relytone/t2rr1M4X9EzYwT0a/images/pgadmin_gui.png?fit=max\&auto=format\&n=t2rr1M4X9EzYwT0a\&q=85\&s=f1ca24803d298c137de1c9cbdd61c779) ### DBeaver DBeaver is a universal database management tool that supports multiple database types. It has a modern user interface and provides powerful SQL editors, data visualization tools, and a rich plugin ecosystem. For users who need to manage multiple types of databases, DBeaver is a great choice. > [!NOTE] > > [https://dbeaver.io/download/](https://dbeaver.io/download/) ![Dbeaver Gui Pn](https://mintcdn.com/relytone/t2rr1M4X9EzYwT0a/images/dbeaver_gui.png?fit=max\&auto=format\&n=t2rr1M4X9EzYwT0a\&q=85\&s=09a398dbd73aaa55028dfcc17389ae91) ## 6. Common Issues During usage, you may encounter some connection issues. The following are the most common problems and their solutions: ### Endpoint ID is not specified This error typically occurs when using older versions of PostgreSQL client libraries. The root cause of the problem is that the client's TLS implementation does not support Server Name Indication (SNI) technology, while Relyt's cloud service relies on SNI to correctly route connections to the corresponding database instances. When the client TLS does not support Server Name Indication (SNI), the connection may show the following error: > ERROR: Endpoint ID is not specified. Either please upgrade the postgres client library (libpq) for SNI support or pass the endpoint ID (first part of the domain name) as a parameter: '?options=project%3D'. **Solutions**: **Upgrade your PostgreSQL client**: Install psql (libpq) >= 14 for full SNI support # Create a Project Source: https://docs-relytone.data.cloud/docs/create-project # Start to create a project First, after you log in to your account, you will land on the console page, positioned in the *Projects* section. In the top right corner, there is a '**+ New project**' button. Click it to start creating a new project. ![Frame17 Pn](https://mintcdn.com/relytone/pi8VPkBOtJGoqO9S/images/Frame17.png?fit=max\&auto=format\&n=pi8VPkBOtJGoqO9S\&q=85\&s=03d02aa4c160632a3eb9c59ba7232d79) # Configuration of project * **Project Name** * Set up your project name, 60 characters limited. * **Region** * Currently, only the Los Angeles region is available. Additional regions will be added soon. * **Project password** * Set up your project password, Please keep your password secure, as the platform does not store it. This password will be required for the subsequent connection process. ![Project creation settings form](https://mintcdn.com/relytone/L6U1cJH72uSbRY3N/images/project-creation-settings.png?fit=max\&auto=format\&n=L6U1cJH72uSbRY3N\&q=85\&s=f0e52bbf2dcd4f9c06ddcd727ad41a62) Once everything is configured, click the '**Create**' button to complete the project creation. Projects typically spin up within seconds. You can refresh the project status by clicking the refresh button. # Extensions Source: https://docs-relytone.data.cloud/docs/extensions/index Seamlessly access popular PostgreSQL ecosystem tools within RelytONE. Relyt ONE comes pre-configured with a selection of widely-adopted PostgreSQL extensions, enabling you to leverage the broader ecosystem's capabilities with minimal setup. Below is a collection of the extensions currently available. ## Supported Extensions > [card] [PostGIS](/docs/extensions/postgis) > > Spatial database extender for PostgreSQL. > [card] [TimescaleDB](/docs/extensions/timescaledb) > > Time-series database optimized for fast ingest and complex queries. > [card] [PGMQ](/docs/extensions/pgmq) > > A lightweight message queue for PostgreSQL. > [card] [uuid-ossp](/docs/extensions/uuid-ossp) > > Generate and manage Universally Unique Identifiers (UUIDs). # PGMQ Source: https://docs-relytone.data.cloud/docs/extensions/pgmq Build reliable message queues directly inside Postgres using the Postgres Message Queue extension, fully managed on Relyt ONE. Relyt ONE ships with **PGMQ v1.7** enabled for every Postgres cluster, so you can run durable message queues directly in Postgres. Use simple SQL to send, receive, delete, and archive jobs without leaving the database. ## Key Capabilities * **Visibility timeouts** keep a message locked to one consumer before it reappears * **SQL-first workflow**—no background workers or extra services to manage * **Archive or delete** messages to match compliance or replay needs * **Pure Postgres deployment** with the extension already managed by Relyt ONE ## Quick Start ### Step 1: Enable the extension ```sql theme={null} CREATE EXTENSION IF NOT EXISTS pgmq; ``` ### Step 2: Create a queue ```sql theme={null} SELECT pgmq.create('my_queue'); ``` Each queue is a table under the `pgmq` schema (`q_`). Archives live under `a_`. ### Step 3: Publish messages ```sql theme={null} SELECT pgmq.send( queue_name => 'my_queue', msg => '{"task": "resize", "asset_id": 42}', delay => 5 -- optional seconds to defer visibility ); ``` Use `pgmq.send_batch` with a JSONB array to enqueue many messages atomically. ### Step 4: Consume messages ```sql theme={null} SELECT * FROM pgmq.read( queue_name => 'my_queue', vt => 30, -- seconds to keep the message invisible to others qty => 10 ); ``` `pgmq.pop('my_queue')` is a shortcut that reads **and** deletes a single message immediately. ### Step 5: Complete work * **Delete forever:** `SELECT pgmq.delete('my_queue', msg_id);` * **Archive for replay:** `SELECT pgmq.archive(queue_name => 'my_queue', msg_id => 7);` * Inspect archives via `SELECT * FROM pgmq.a_my_queue;` ### Step 6: Clean up ```sql theme={null} SELECT pgmq.drop_queue('my_queue'); ``` ## Visibility Timeout Tips * Set `vt` longer than the expected processing time; unfinished work reappears when the timeout expires. * Use shorter `vt` for idempotent consumers needing faster retries. * Always delete or archive after successful processing to avoid duplicates. ## Best Practices 1. **Keep messages small**—store big payloads in tables and enqueue references. 2. **Monitor lag** by counting rows in `pgmq.q_*` tables or using `read_ct`. 3. **Standardize headers** for trace IDs or tenant metadata via the optional `headers` parameter. 4. **Back up archive tables** if you rely on replay semantics. ## Next Steps * Browse the full SQL surface area and release notes on the [official PGMQ docs](https://pgmq.github.io/pgmq/). * Explore the [pgmq GitHub repo](https://github.com/pgmq/pgmq) for issues, changelog, and community examples. # PostGIS Source: https://docs-relytone.data.cloud/docs/extensions/postgis Get started with PostGIS in Relyt ONE for powerful geospatial data analysis and operations. Relyt ONE integrates **PostGIS 3.5.4** with **GDAL 3.11**, providing industry-leading spatial database capabilities for storing, querying, and analyzing geographic data directly in PostgreSQL. PostGIS extends PostgreSQL with support for geographic objects, spatial indexes, and hundreds of spatial functions for processing and analyzing vector and raster data. ## Key Features * **Spatial Data Types**: Support for points, lines, polygons, and complex geometries * **Coordinate Systems**: Full projection support with thousands of spatial reference systems * **Spatial Indexing**: High-performance GiST and BRIN indexes for spatial queries * **Geometry Operations**: Distance calculations, intersections, unions, buffers, and more * **Standards Compliant**: OGC-compliant implementation of SQL/MM specifications * **Raster Support**: Store and analyze raster data with GDAL 3.11 integration ## Quick Start ### Step 1: Enable PostGIS Extension First, enable the PostGIS extension in your database: ```sql theme={null} CREATE EXTENSION IF NOT EXISTS postgis; ``` Verify the installation and check the version: ```sql theme={null} SELECT PostGIS_Version(); ``` **Expected Output:** ``` 3.5 USE_GEOS=1 USE_PROJ=1 USE_STATS=1 ``` ### Step 2: Create a Spatial Table Create a table with geometry columns to store spatial data: ```sql theme={null} CREATE TABLE cities ( id SERIAL PRIMARY KEY, name VARCHAR(100), population INTEGER, geom GEOMETRY(Point, 4326) ); COMMENT ON COLUMN cities.id IS 'Primary key, auto-increment'; COMMENT ON COLUMN cities.name IS 'City name'; COMMENT ON COLUMN cities.population IS 'Population count'; COMMENT ON COLUMN cities.geom IS 'Geographic point (longitude, latitude) in WGS84'; ``` The `GEOMETRY(Point, 4326)` type specifies: * `Point`: The geometry type (point, linestring, polygon, etc.) * `4326`: The SRID (Spatial Reference System Identifier) for WGS84 coordinates ### Step 3: Insert Spatial Data Insert cities with their geographic coordinates: ```sql theme={null} INSERT INTO cities (name, population, geom) VALUES ('San Francisco', 873965, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)), ('New York', 8336817, ST_SetSRID(ST_MakePoint(-74.0060, 40.7128), 4326)), ('Los Angeles', 3979576, ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326)), ('Chicago', 2693976, ST_SetSRID(ST_MakePoint(-87.6298, 41.8781), 4326)), ('Seattle', 753675, ST_SetSRID(ST_MakePoint(-122.3321, 47.6062), 4326)); ``` You can also use the simpler `ST_Point` function: ```sql theme={null} INSERT INTO cities (name, population, geom) VALUES ('Boston', 692600, ST_GeomFromText('POINT(-71.0589 42.3601)', 4326)); ``` ### Step 4: Create Spatial Index Create a spatial index to accelerate spatial queries: ```sql theme={null} CREATE INDEX cities_geom_idx ON cities USING GIST (geom); ``` **Benefits:** * Dramatically improves performance for spatial queries * Essential for large datasets with millions of geometries * Uses R-tree-like indexing structure ### Step 5: Basic Spatial Queries #### Distance Calculations Find cities within 500 km of San Francisco: ```sql theme={null} SELECT name, population, ST_Distance( geom::geography, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography ) / 1000 AS distance_km FROM cities WHERE ST_DWithin( geom::geography, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography, 500000 -- 500 km in meters ) ORDER BY distance_km; ``` #### Nearest Neighbor Search Find the 3 closest cities to a given point: ```sql theme={null} SELECT name, ST_Distance( geom::geography, ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326)::geography ) / 1000 AS distance_km FROM cities ORDER BY geom <-> ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326) LIMIT 3; ``` The `<->` operator uses the spatial index for efficient nearest neighbor queries. ### Step 6: Working with Polygons Create a table for geographic regions: ```sql theme={null} CREATE TABLE regions ( id SERIAL PRIMARY KEY, name VARCHAR(100), geom GEOMETRY(Polygon, 4326) ); ``` Insert a polygon representing a geographic area: ```sql theme={null} INSERT INTO regions (name, geom) VALUES ('Bay Area', ST_GeomFromText( 'POLYGON(( -123.0 38.0, -122.0 38.0, -122.0 37.0, -123.0 37.0, -123.0 38.0 ))', 4326 )); ``` Find cities within a region: ```sql theme={null} SELECT c.name, c.population FROM cities c JOIN regions r ON ST_Contains(r.geom, c.geom) WHERE r.name = 'Bay Area'; ``` ### Step 7: Advanced Spatial Operations #### Buffer Operations Create a 100 km buffer around a city: ```sql theme={null} SELECT name, ST_Buffer(geom::geography, 100000)::geometry AS buffer_geom FROM cities WHERE name = 'San Francisco'; ``` #### Area and Distance Calculations Calculate the area of a polygon in square kilometers: ```sql theme={null} SELECT name, ST_Area(geom::geography) / 1000000 AS area_sq_km FROM regions; ``` #### Intersection Detection Check if two geometries intersect: ```sql theme={null} SELECT c.name AS city, r.name AS region FROM cities c CROSS JOIN regions r WHERE ST_Intersects(c.geom, r.geom); ``` #### Centroid Calculation Find the geometric center of a polygon: ```sql theme={null} SELECT name, ST_AsText(ST_Centroid(geom)) AS centroid FROM regions; ``` ### Step 8: Converting Coordinate Systems Transform coordinates between different spatial reference systems: ```sql theme={null} -- Convert from WGS84 (4326) to Web Mercator (3857) SELECT name, ST_AsText(ST_Transform(geom, 3857)) AS mercator_coords FROM cities LIMIT 3; ``` ### Step 9: Export Spatial Data Export geometries in various formats: ```sql theme={null} -- GeoJSON format SELECT name, ST_AsGeoJSON(geom) AS geojson FROM cities LIMIT 1; -- Well-Known Text (WKT) SELECT name, ST_AsText(geom) AS wkt FROM cities LIMIT 1; -- KML format SELECT name, ST_AsKML(geom) AS kml FROM cities LIMIT 1; ``` ## Common Spatial Functions | Function | Description | Example | | - | - | - | | `ST_Distance` | Calculate distance between geometries | `ST_Distance(geom1, geom2)` | | `ST_DWithin` | Check if geometries are within distance | `ST_DWithin(geom1, geom2, 1000)` | | `ST_Contains` | Check if geometry contains another | `ST_Contains(polygon, point)` | | `ST_Intersects` | Check if geometries intersect | `ST_Intersects(geom1, geom2)` | | `ST_Buffer` | Create buffer around geometry | `ST_Buffer(geom, 1000)` | | `ST_Area` | Calculate area of polygon | `ST_Area(geom::geography)` | | `ST_Length` | Calculate length of linestring | `ST_Length(geom::geography)` | | `ST_Union` | Combine multiple geometries | `ST_Union(geom1, geom2)` | | `ST_Centroid` | Find center point | `ST_Centroid(geom)` | | `ST_Transform` | Transform between coordinate systems | `ST_Transform(geom, 3857)` | ## Best Practices 1. **Use Geography vs Geometry**: Cast to `geography` type for accurate distance calculations on Earth's surface 2. **Always Create Spatial Indexes**: Essential for performance on large datasets 3. **Specify SRID**: Always specify the spatial reference system (e.g., 4326 for WGS84) 4. **Use Appropriate Functions**: Use `ST_DWithin` instead of `ST_Distance < x` for better performance 5. **Validate Geometries**: Use `ST_IsValid()` to check geometry validity before operations ## Next Steps * Explore [PostGIS documentation](https://postgis.net/documentation/) for comprehensive function reference * Learn about [raster data support](https://postgis.net/docs/RT_reference.html) with GDAL * Check out [topology](https://postgis.net/docs/Topology.html) features for advanced spatial relationships * Integrate with QGIS, ArcGIS, or other GIS tools using standard PostgreSQL connections *** For advanced features including 3D geometries, routing, geocoding, and raster analysis, refer to the official [PostGIS documentation](https://postgis.net/docs/). # TimescaleDB Source: https://docs-relytone.data.cloud/docs/extensions/timescaledb Get started with TimescaleDB time-series database functionality in Relyt ONE. Learn how to create hypertables, insert time-series data, and run efficient queries. > [!NOTE] > > Relyt ONE integrates [TimescaleDB](https://github.com/timescale/timescaledb), an open-source time-series database extension for PostgreSQL. We use TimescaleDB Apache 2 Edition v2.21.3 to provide powerful time-series capabilities. For a detailed comparison of features between Apache 2 Edition and Community Edition, see the [TimescaleDB editions feature comparison](https://docs.tigerdata.com/about/latest/timescaledb-editions/#feature-comparison). ## What is TimescaleDB? TimescaleDB is a powerful PostgreSQL extension that transforms your database into a high-performance time-series database. It's designed for handling large volumes of time-stamped data while maintaining full SQL compatibility and leveraging PostgreSQL's reliability. Key benefits: * **Automatic partitioning** via hypertables for efficient time-series data storage * **Fast queries** with optimized indexing and query planning * **Full SQL support** - no need to learn new query languages * **Horizontal scaling** capabilities for massive datasets * **Built-in functions** for time-series analysis ## Prerequisites Before getting started, ensure you have: * An active Relyt database connection * TimescaleDB extension enabled on your database * Basic familiarity with SQL and PostgreSQL ## Quick Start ### Step 1: Enable TimescaleDB Extension First, connect to your Relyt database and enable the TimescaleDB extension: ```sql theme={null} -- Connect to your database and enable TimescaleDB CREATE EXTENSION IF NOT EXISTS timescaledb; -- Verify the extension is installed \dx ``` You should see `timescaledb` listed among your installed extensions. ### Step 2: Create Your First Hypertable A hypertable is TimescaleDB's core abstraction - it looks like a regular PostgreSQL table but is automatically partitioned by time. ```sql theme={null} -- Create a regular table first CREATE TABLE sensor_data ( time TIMESTAMPTZ NOT NULL, sensor_id INTEGER NOT NULL, temperature DOUBLE PRECISION, humidity DOUBLE PRECISION, location TEXT ); -- Convert it to a hypertable SELECT create_hypertable('sensor_data', by_range('time')); ``` > [!NOTE] > > The `time` column must be the first argument to `create_hypertable()` and should be of type `TIMESTAMPTZ`, `TIMESTAMP`, or `DATE`. > [!WARNING] > > Always include a `time` column in your hypertables and ensure it's properly indexed for optimal performance. ### Step 3: Insert Time-Series Data Insert data just like you would with any PostgreSQL table: ```sql theme={null} -- Insert sample sensor readings INSERT INTO sensor_data (time, sensor_id, temperature, humidity, location) VALUES (NOW() - INTERVAL '1 hour', 1, 22.5, 45.0, 'living_room'), (NOW() - INTERVAL '45 minutes', 1, 22.8, 44.5, 'living_room'), (NOW() - INTERVAL '30 minutes', 2, 19.2, 52.0, 'bedroom'), (NOW() - INTERVAL '15 minutes', 2, 19.5, 51.5, 'bedroom'), (NOW(), 3, 15.8, 68.0, 'outside'); -- Insert bulk data efficiently INSERT INTO sensor_data (time, sensor_id, temperature, humidity, location) SELECT generate_series(NOW() - INTERVAL '7 days', NOW(), INTERVAL '5 minutes') AS time, (random() * 3 + 1)::INTEGER AS sensor_id, (random() * 10 + 15)::DOUBLE PRECISION AS temperature, (random() * 30 + 40)::DOUBLE PRECISION AS humidity, CASE (random() * 2)::INTEGER WHEN 0 THEN 'indoor' ELSE 'outdoor' END AS location; ``` ### Step 4: Query Time-Series Data TimescaleDB provides powerful functions for time-series analysis: ```sql theme={null} -- Get latest readings per sensor SELECT DISTINCT ON (sensor_id) sensor_id, time, temperature, humidity, location FROM sensor_data ORDER BY sensor_id, time DESC; -- Calculate hourly averages using time_bucket SELECT time_bucket('1 hour', time) AS hour, sensor_id, AVG(temperature) AS avg_temp, AVG(humidity) AS avg_humidity FROM sensor_data WHERE time > NOW() - INTERVAL '24 hours' GROUP BY hour, sensor_id ORDER BY hour DESC, sensor_id; -- Find temperature trends over the last week SELECT time_bucket('1 day', time) AS day, location, MIN(temperature) AS min_temp, MAX(temperature) AS max_temp, AVG(temperature) AS avg_temp FROM sensor_data WHERE time > NOW() - INTERVAL '7 days' GROUP BY day, location ORDER BY day DESC; ``` ## Essential TimescaleDB Functions ### time\_bucket() The most important function for time-series analysis - groups data into time intervals: ```sql theme={null} -- 15-minute intervals SELECT time_bucket('15 minutes', time) AS bucket, AVG(temperature) FROM sensor_data GROUP BY bucket ORDER BY bucket; -- Daily intervals with offset SELECT time_bucket('1 day', time, '6 hours'::INTERVAL) AS bucket, COUNT(*) FROM sensor_data GROUP BY bucket; ``` ### first() and last() Get the first or last value in a time range: ```sql theme={null} -- Get first and last temperature reading per day SELECT time_bucket('1 day', time) AS day, first(temperature, time) AS first_temp, last(temperature, time) AS last_temp FROM sensor_data GROUP BY day ORDER BY day; ``` ### Continuous Aggregates Pre-compute common queries for faster performance: ```sql theme={null} -- Create a continuous aggregate for hourly averages CREATE MATERIALIZED VIEW hourly_sensor_avg AS SELECT time_bucket('1 hour', time) AS hour, sensor_id, AVG(temperature) AS avg_temp, AVG(humidity) AS avg_humidity FROM sensor_data GROUP BY hour, sensor_id; -- Query the pre-computed view SELECT * FROM hourly_sensor_avg WHERE hour > NOW() - INTERVAL '24 hours' ORDER BY hour DESC; ``` ## Common Use Cases > [card] IoT Sensor Data > > Store and analyze readings from temperature, humidity, and other sensors with automatic time-based partitioning. > [card] Application Metrics > > Monitor application performance, response times, and system metrics with efficient time-series queries. > [card] Financial Data > > Track stock prices, trading volumes, and market data with millisecond precision. > [card] Log Analytics > > Store and analyze application logs, system events, and audit trails over time. ## Learn More This guide covers the basics of using TimescaleDB in Relyt ONE. For comprehensive documentation on advanced features, best practices, and detailed API references, visit the official TimescaleDB documentation: > [card] [TimescaleDB Official Documentation](https://docs.timescale.com/) > > Explore advanced features like data retention, compression, continuous aggregates, and performance optimization. > [!TIP] > > **Getting Started**: Begin with simple hypertables and basic queries. As your data grows, explore advanced features like continuous aggregates and compression in the [official TimescaleDB docs](https://docs.timescale.com/). # uuid-ossp Source: https://docs-relytone.data.cloud/docs/extensions/uuid-ossp Generate and manage Universally Unique Identifiers (UUIDs) in Relyt ONE. The **uuid-ossp** extension provides functions to generate universally unique identifiers (UUIDs) using one of several standard algorithms. It is useful for creating unique primary keys that are unique across distributed systems. For more information, see the official [PostgreSQL uuid-ossp Documentation](https://www.postgresql.org/docs/current/uuid-ossp.html). ## Quick Start ### Step 1: Enable Extension Enable the extension in your database: ```sql theme={null} CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; ``` ### Step 2: Generate UUIDs Generate a random Version 4 UUID (most common): ```sql theme={null} SELECT uuid_generate_v4(); ``` **Expected Output:** ``` uuid_generate_v4 -------------------------------------- a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 ``` Generate a Version 1 UUID (timestamp & MAC address): ```sql theme={null} SELECT uuid_generate_v1(); ``` ### Step 3: Use as Primary Key Create a table using UUID as the primary key with a default value: ```sql theme={null} CREATE TABLE users ( user_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), username VARCHAR(50), email VARCHAR(100) ); INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com'), ('jane_smith', 'jane@example.com'); SELECT * FROM users; ``` ## Functions | Function | Return Type | Description | | :- | :- | :- | | `uuid_generate_v1()` | `uuid` | Generates a version 1 UUID using MAC address and timestamp. | | `uuid_generate_v1mc()` | `uuid` | Generates a version 1 UUID using a random multicast MAC address. | | `uuid_generate_v3(namespace, name)` | `uuid` | Generates a deterministic version 3 UUID (MD5) from namespace and name. | | `uuid_generate_v4()` | `uuid` | Generates a random version 4 UUID. | | `uuid_generate_v5(namespace, name)` | `uuid` | Generates a deterministic version 5 UUID (SHA-1) from namespace and name. Preferred over v3. | # External Tables Source: https://docs-relytone.data.cloud/docs/external_table Query data on S3 object storage through external tables with automatic schema inference. Support for Parquet, JSON, and CSV formats powered by DuckDB for high-performance data access. Relyt ONE enables querying data stored on S3 object storage through external tables. The schema is automatically inferred from the data, simplifying table creation and greatly improving usability. External tables support **Parquet**, **JSON**, and **CSV** formats. Powered by DuckDB's `read_parquet`, `read_json`, and `read_csv` functions, they deliver efficient data access. Built-in local and remote caching reduces latency and improves throughput for optimal query performance. ## Syntax ```sql theme={null} CREATE TABLE () USING duckdb WITH ( duckdb_external_location = 's3://xxxxxx', duckdb_external_format = 'parquet', -- csv, json duckdb_external_options = '' -- optional ); ``` ## Parameters * **`duckdb_external_location`**: S3 path to your data. See [Load Data](/features/load-data) for format details. * Example: `s3://s3.us-west-1.amazonaws.com/bucket/path/dat.parquet accessid=xxxx secret=yyyy` * **`duckdb_external_format`**: Data format. Options: `parquet`, `csv`, `json` * **`duckdb_external_options`** *(optional)*: Additional parameters passed to DuckDB. * Example: Include filename in results with `{"filename": true}` > [!NOTE] > > No need to define columns explicitly—Relyt ONE automatically samples the data to infer column names and types. After creation, use `\d+ ` or `SELECT * FROM LIMIT 1` to inspect the schema. External tables work like regular PostgreSQL tables. Queries involving external tables automatically leverage the DuckDB engine, with caching ensuring high performance regardless of S3 latency or bandwidth constraints. ## Examples ### Create a Parquet External Table ```sql theme={null} CREATE TABLE lineitem () USING duckdb WITH ( duckdb_external_location = 's3://s3.us-west-1.amazonaws.com/my_bucket/lineitem/*.parquet accessid=xxxx secret=yyyy', duckdb_external_format = 'parquet' ); SELECT * FROM lineitem LIMIT 1; ``` ### Create a CSV External Table with Custom Column Names ```sql theme={null} CREATE TABLE nation () USING duckdb WITH ( duckdb_external_location = 's3://s3.us-west-1.amazonaws.com/my_bucket/csv/nation.tbl accessid=xxxx secret=yyyy', duckdb_external_format = 'csv', duckdb_external_options = '{"column_names": ["n_nationkey","n_name","n_regionkey","n_comment"]}' ); ``` ### Create a JSON External Table ```sql theme={null} CREATE TABLE external_json () USING duckdb WITH ( duckdb_external_location = 's3://s3.us-west-1.amazonaws.com/my_bucket/json/a.tbl accessid=xxxx secret=yyyy', duckdb_external_format = 'json' ); ``` **Verify the schema:** ``` \d+ external_json Table "public.external_json" Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target --------+------------------+-----------+----------+---------+----------+-------------+-------------- a | bigint | | | | plain | | b | text | | | | extended | | c | double precision | | | | plain | | Access method: duckdb ``` # Full-Text Search Source: https://docs-relytone.data.cloud/docs/fulltext/quick-start Get started with pg_search, Relyt ONE's built-in BM25 full-text search extension based on the open-source ParadeDB project with enhanced crash recovery. Relyt ONE comes with the built-in `pg_search` extension, providing powerful full-text search capabilities based on BM25 ranking. The extension is built on the open-source [ParadeDB project](https://github.com/paradedb/paradedb), a modern Elasticsearch alternative for Postgres. Relyt has enhanced ParadeDB with **Write-Ahead Logging (WAL) support for crash recovery**, ensuring production-grade reliability and full recoverability of search indexes. Our enhancements are also open-sourced at [github](https://github.com/relytcloud/paradedb). ## Key Features * **Real-time Search**: Immediate visibility with zero indexing delay * **High Performance**: Parallel BM25 index creation and query execution * **ACID Compliance**: Full transactional guarantees * **Crash Recovery**: WAL-based backup and recovery support * **Custom Tokenization**: User-defined tokenizers for different languages and use cases ## Quick Start ### Step 1: Create a Table and Insert Sample Data Use the helper function to create a test table with sample data: ```sql theme={null} CALL pgsearch.create_bm25_test_table( schema_name => 'public', table_name => 'mock_items' ); ``` This creates a `mock_items` table and populates it with sample product data for testing. ### Step 2: Create a BM25 Index Create a full-text search index on the desired columns: ```sql theme={null} CREATE INDEX search_idx ON mock_items USING bm25 (id, description, category, rating, in_stock, created_at, metadata) WITH (key_field='id'); ``` The `key_field` parameter specifies the primary key column used for document identification. ### Step 3: Query Using the BM25 Index The `@@@` operator is used for full-text search queries. #### Basic Search - Single Term ```sql theme={null} SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes'; ``` #### Multiple Terms ```sql theme={null} SELECT description, rating, category FROM mock_items WHERE description @@@ 'keyboard' OR category @@@ 'toy'; ``` #### Search with Filters Combine full-text search with structured filters: ```sql theme={null} -- Using @@@ operator for numeric comparison SELECT id, description, rating FROM mock_items WHERE description @@@ 'shoes' AND rating @@@ '>3' ORDER BY id; -- Using standard SQL operators SELECT id, description, rating FROM mock_items WHERE description @@@ 'shoes' AND rating > 3; -- Exact match SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes' AND rating @@@ '4'; -- Date filtering SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes' AND created_at @@@ '"2023-04-20T16:38:02Z"'; -- Boolean filtering SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes' AND in_stock @@@ 'true'; -- Range queries SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes' AND rating @@@ '[1 TO 4]'; -- Term range SELECT description, rating, category FROM mock_items WHERE description @@@ '[book TO camera]'; -- Set filtering SELECT description, rating, category FROM mock_items WHERE description @@@ 'shoes' AND rating @@@ 'IN [2 3 4]'; ``` ### Step 4: Advanced Search Features #### Proximity Search Use the tilde (`~`) operator for phrase proximity matching: ```sql theme={null} SELECT description, rating, category FROM mock_items WHERE description @@@ '"ergonomic keyboard"~1'; ``` **Output:** ``` description | rating | category --------------------------+--------+------------- Ergonomic metal keyboard | 4 | Electronics (1 row) ``` The `~1` allows one word between the search terms. #### Highlighting Highlight matching terms in search results: ```sql theme={null} SELECT id, pgsearch.snippet(description) FROM mock_items WHERE description @@@ 'shoes' LIMIT 5; ``` #### Relevance Scoring Retrieve relevance scores for search results: ```sql theme={null} SELECT description, rating, category, pgsearch.score(id) AS score FROM mock_items WHERE description @@@ 'shoes' ORDER BY score DESC LIMIT 5; ``` #### Field Boosting Apply different weights to search terms using the caret (`^`) operator: ```sql theme={null} SELECT id, pgsearch.score(id) AS score FROM mock_items WHERE description @@@ 'shoes^2' OR category @@@ 'footwear' ORDER BY score DESC LIMIT 5; ``` The `^2` boosts the importance of matches in the description field by a factor of 2. #### Match Function Use the `pgsearch.match()` function for more control over search behavior: ```sql theme={null} -- Simple match SELECT description, rating, category FROM mock_items WHERE id @@@ pgsearch.match('description', 'running shoes'); -- JSON-based query SELECT description, rating, category FROM mock_items WHERE id @@@ '{ "match": { "field": "description", "value": "running shoes" } }'::jsonb; -- Custom tokenizer SELECT description, rating, category FROM mock_items WHERE id @@@ pgsearch.match( 'description', 'running shoes', tokenizer => pgsearch.tokenizer('whitespace') ); ``` *** For more advanced features including custom tokenizers, aggregations, fuzzy search, hybrid search, and query optimization techniques, please refer to the [ParadeDB documentation](https://docs.paradedb.com/documentation/overview). Since Relyt ONE's `pg_search` is based on ParadeDB, most features and syntax are fully compatible. # Graph Analytics (AGE) Source: https://docs-relytone.data.cloud/docs/graph/quick-start Relyt ONE integrates Apache AGE as a built-in extension, supporting efficient graph data queries and operations using the [Cypher](https://neo4j.com/docs/cypher-manual/current/) query language. ## Prerequisites Before you begin, ensure you have: * Created a Relyt ONE instance * Connected to the database > [!TIP] > > For details on instance creation, user management, and connection methods, refer to the relevant documentation. ## Overview This guide covers: 1. **Creating and Using Graphs** - Basic AGE usage 2. **Bulk Data Import** - Importing existing table data into graphs ## Example: Product Catalog Graph Let's model a basic product catalog using AGE. We'll create a catalog containing collections (e.g., Spring/Summer and Fall/Winter), with each collection containing items. Items can have sub-items, and each item has its own properties, images, and attachments. ![Product Catalog Graph Model](https://mintcdn.com/relytone/KjADbefTKFLEE1ih/images/graph-rel.png?fit=max\&auto=format\&n=KjADbefTKFLEE1ih\&q=85\&s=67d1fe32daa20163625d6bfed8021487) In this model: * Each entity (blue rectangle) converts to a **Vertex** (node) * Each relationship converts to an **Edge** **Naming Conventions:** * Node labels: PascalCase (e.g., `Catalog`) * Relationships: UPPER\_SNAKE\_CASE (e.g., `HAS_ATTRIBUTE`) ## Setup ### Set Search Path Add `ag_catalog` to your search path to simplify queries: ```sql theme={null} SET search_path TO public, ag_catalog; ``` ### Create a Graph ```sql theme={null} SELECT create_graph('playground'); ``` ## Creating Graph Structure You have two approaches: 1. **Dynamic Creation**: Insert vertices and edges directly; the engine auto-creates definitions 2. **Pre-defined Structure**: Create all vertex and edge definitions before inserting data > [!WARNING] > > The first approach is faster but requires caution: you cannot query entities that don't exist yet. The graph engine converts each vertex and edge to database tables. Querying a non-existent label will return an error. > [!TIP] > > For production use with a known structure, pre-define all vertices and edges before inserting data. ### Create Vertex and Edge Labels ```sql theme={null} -- Create vertex labels select create_vlabel(GRAPH_NAME, LABEL); -- Create edge labels select create_elabel(GRAPH_NAME, LABEL); ``` For our example graph: ```sql theme={null} -- Vertices select create_vlabel('playground', 'Catalog'); select create_vlabel('playground', 'Collection'); select create_vlabel('playground', 'Item'); select create_vlabel('playground', 'Attribute'); select create_vlabel('playground', 'Image'); select create_vlabel('playground', 'Attachment'); -- Edges select create_elabel('playground', 'BELONGS_TO'); select create_elabel('playground', 'PART_OF'); select create_elabel('playground', 'CHILD_OF'); select create_elabel('playground', 'HAS_ATTRIBUTE'); select create_elabel('playground', 'HAS_IMAGE'); select create_elabel('playground', 'HAS_ATTACHMENT'); ``` > [!NOTE] > > Edge labels don't specify which vertices they connect. Actual connections are determined by the data. ## Writing Data ### Create a Catalog Node ```sql theme={null} select * from cypher('playground', $$ CREATE (c:Catalog { code: "C001" }) SET c.name = "Apparel Catalog" RETURN c $$) as (catalog agtype); ``` This creates a node with: * Label: `Catalog` * Property: `code = "C001"` * Additional property: `name = "Apparel Catalog"` ### Using MERGE (UPSERT) AGE doesn't support custom indexes. Running the same `CREATE` query twice creates duplicate nodes. Use `MERGE` for upsert behavior: ```sql theme={null} select * from cypher('playground', $$ MERGE (c:Catalog { code: "C001" }) RETURN c $$) as (catalog agtype); ``` This finds or creates a Catalog with `code = "C001"`. > [!WARNING] > > With MERGE, you cannot use SET in the same statement. Split into two commands: ```sql theme={null} -- 1. Create/find node with key property select * from cypher('playground', $$ MERGE (c:Catalog { code: "C001" }) RETURN c $$) as (catalog agtype); -- 2. Set additional properties select * from cypher('playground', $$ MATCH (c:Catalog { code: "C001" }) SET c.name = "Apparel Catalog" RETURN c $$) as (catalog agtype); ``` > [!TIP] > > Only include key properties in MERGE to avoid duplicates. Use MATCH + SET for additional properties. ### Add a Collection Create a Collection and connect it to the Catalog: ```sql theme={null} select * from cypher('playground', $$ MATCH (c:Catalog { code: "C001"} ) MERGE (co:Collection { code: "SS22" }) MERGE (co)-[:BELONGS_TO]->(c) RETURN co $$) as (collection agtype); ``` Notice the visual representation: `(co)-[:BELONGS_TO]->(c)` clearly shows a directed relationship. ### Add Items Add multiple items to the SS22 collection: ```sql theme={null} select * from cypher('playground', $$ MATCH (co:Collection { code: "SS22" }) MERGE (i1:Item { code: 'ISS001'}) MERGE (i1)-[:PART_OF]->(co) MERGE (i2:Item { code: 'ISS002'}) MERGE (i2)-[:PART_OF]->(co) MERGE (i3:Item { code: 'ISS003'}) MERGE (i3)-[:PART_OF]->(co) RETURN [i1, i2, i3] $$) as (items agtype); ``` ### Update Items with Attributes Add attributes as connected nodes: ```sql theme={null} select * from cypher('playground', $$ MATCH (i:Item) WHERE i.code = "ISS001" SET i.name = "T-Shirt" MERGE (i)-[:HAS_ATTRIBUTE { value: "S"}]->(:Attribute { name: "size" }) RETURN i $$) as (item agtype); ``` Add another attribute: ```sql theme={null} select * from cypher('playground', $$ MERGE (i:Item { code: "ISS001"})-[:HAS_ATTRIBUTE { value: "Blue"}]->(:Attribute { name: "color" }) RETURN i $$) as (item agtype); ``` > [!NOTE] > > Edges can have properties, making them first-class citizens in the graph. ## Querying Graphs ### Pattern Matching Retrieve all items in catalog C001: ```sql theme={null} select * from cypher('playground', $$ MATCH (c:Catalog { code: "C001" })<-[:BELONGS_TO]-(co:Collection)<-[:PART_OF]-(i:Item) RETURN i $$) as (item agtype); ``` ### Variable-Length Paths A more compact and powerful representation: ```sql theme={null} select * from cypher('playground', $$ MATCH (c:Catalog { code: "C001" })-[*]-(i:Item) RETURN i $$) as (item agtype); ``` This returns all items connected to catalog C001 through any relationship path. > [!WARNING] > > Use unconstrained path matching carefully. On large graphs, complexity can explode, impacting performance. ### Retrieve Specific Properties Get attributes for item ISS001: ```sql theme={null} select * from cypher('playground', $$ MATCH (:Item { code: 'ISS001'})-[v:HAS_ATTRIBUTE]->(a:Attribute) RETURN a.name, v.value $$) as (name agtype, value agtype); ``` ### Custom Return Values Return a JSON object list: ```sql theme={null} select * from cypher('playground', $$ MATCH (:Item { code: 'ISS001'})-[v:HAS_ATTRIBUTE]->(a:Attribute) RETURN { name: a.name, value: v.value } $$) as (attr agtype); ``` ## Deleting Data ### Remove Labels ```sql theme={null} -- Add a label SELECT * FROM cypher('playground', $$ MATCH (i1:Item { code: 'ISS001'}) SET i1.newlabel = 'to deleted' RETURN i1 $$) AS (result_a agtype); -- Remove the label SELECT * FROM cypher('playground', $$ MATCH (i1:Item { code: 'ISS001'}) REMOVE i1.newlabel RETURN i1 $$) AS (result_a agtype); ``` ### Delete Edges ```sql theme={null} -- Delete the size attribute edge for T-Shirt SELECT * FROM cypher('playground', $$ MATCH (i1:Item)-[r:HAS_ATTRIBUTE]->(a1:Attribute) WHERE i1.name = 'T-Shirt' AND a1.name='size' DELETE r $$) AS (result_a agtype); ``` ### Delete Vertices ```sql theme={null} -- Delete all size attributes SELECT * FROM cypher('playground', $$ MATCH(a1:Attribute { name: 'size'}) DELETE a1 $$) AS (result_a agtype); ``` ### Delete Vertices with Edges Deleting a vertex with edges will fail: ```sql theme={null} SELECT * FROM cypher('playground', $$ MATCH(a1:Attribute { name: 'color'}) DELETE a1 $$) AS (result_a agtype); ``` This will produce an error: ``` ERROR: Cannot delete a vertex that has edge(s). Delete the edge(s) first, or try DETACH DELETE. ``` Use `DETACH DELETE` to remove both vertex and edges: ```sql theme={null} SELECT * FROM cypher('playground', $$ MATCH(a1:Attribute { name: 'color'}) DETACH DELETE a1 $$) AS (result_a agtype); ``` ### Drop a Graph ```sql theme={null} SELECT drop_graph('playground'); ``` If the graph contains data, you'll get an error. Use cascade to force deletion: ```sql theme={null} SELECT drop_graph('playground', true); ``` ## Bulk Data Import For large datasets, inserting data one by one is inefficient. Instead, import data into relational tables first, then load into the graph. ### Step 1: Create and Populate Tables **Catalog Table:** ```sql theme={null} CREATE TABLE IF NOT EXISTS catalog_raw ( id BIGINT, code TEXT, name TEXT, description TEXT ); INSERT INTO catalog_raw VALUES ('0', 'C001', 'Apparel Catalog', 'Fashion and clothing catalog'), ('1', 'C002', 'Electronics Catalog', 'Electronic devices and accessories'); ``` **Collection Table:** ```sql theme={null} CREATE TABLE IF NOT EXISTS collection_raw ( id BIGINT, code TEXT, name TEXT, season TEXT ); INSERT INTO collection_raw VALUES ('10', 'SS22', 'Spring Summer 2022', 'Spring'), ('11', 'FW22', 'Fall Winter 2022', 'Fall'), ('12', 'SS23', 'Spring Summer 2023', 'Spring'); ``` **Item Table:** ```sql theme={null} CREATE TABLE IF NOT EXISTS item_raw ( id BIGINT, code TEXT, name TEXT, price DECIMAL ); INSERT INTO item_raw VALUES ('100', 'ISS001', 'T-Shirt', 29.99), ('101', 'ISS002', 'Jeans', 79.99), ('102', 'ISS003', 'Sneakers', 129.99), ('103', 'IWS001', 'Winter Coat', 199.99), ('104', 'IWS002', 'Boots', 149.99); ``` **Relationship Tables:** ```sql theme={null} -- BELONGS_TO relationships CREATE TABLE IF NOT EXISTS collection_belongsto_catalog_raw ( start_id BIGINT, end_id BIGINT ); INSERT INTO collection_belongsto_catalog_raw VALUES ('10','0'), ('11','0'), ('12','0'); -- PART_OF relationships CREATE TABLE IF NOT EXISTS item_partof_collection_raw ( start_id BIGINT, end_id BIGINT ); INSERT INTO item_partof_collection_raw VALUES ('100','10'), ('101','10'), ('102','10'), ('103','11'), ('104','11'); ``` ### Step 2: Create Helper Functions ```sql theme={null} CREATE OR REPLACE FUNCTION age_name_to_idx_start(graph_name text, kind_name text, label_name text) RETURNS bigint AS 'SELECT id::bigint<<48 FROM ag_catalog.ag_label WHERE kind = kind_name AND name = label_name AND graph = (SELECT graphid FROM ag_catalog.ag_graph WHERE name = graph_name)' LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION age_name_to_seq(graph_name text, kind_name text, label_name text) RETURNS text AS $$SELECT graph_name || '."' || seq_name || '"' FROM ag_catalog.ag_label WHERE kind = kind_name and name = label_name and graph = (SELECT graphid FROM ag_catalog.ag_graph WHERE name = graph_name)$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; ``` ### Step 3: Create Graph and Labels ```sql theme={null} SELECT ag_catalog.create_graph('playground'); -- Create vertex labels SELECT ag_catalog.create_vlabel('playground', 'Catalog'); SELECT ag_catalog.create_vlabel('playground', 'Collection'); SELECT ag_catalog.create_vlabel('playground', 'Item'); -- Create edge labels SELECT ag_catalog.create_elabel('playground', 'BELONGS_TO'); SELECT ag_catalog.create_elabel('playground', 'PART_OF'); ``` ### Step 4: Import Vertex Data ```sql theme={null} -- Import Catalog data INSERT INTO playground."Catalog" SELECT (age_name_to_idx_start('playground', 'v', 'Catalog') + id)::text::ag_catalog.graphid, row_to_json((SELECT x FROM (SELECT code, name, description) x))::text::ag_catalog.agtype FROM catalog_raw; -- Set sequence value SELECT setval(age_name_to_seq('playground', 'v', 'Catalog'), (SELECT max(id) + 1 FROM catalog_raw)); -- Import Collection data INSERT INTO playground."Collection" SELECT (age_name_to_idx_start('playground', 'v', 'Collection') + id)::text::ag_catalog.graphid, row_to_json((SELECT x FROM (SELECT code, name, season) x))::text::ag_catalog.agtype FROM collection_raw; SELECT setval(age_name_to_seq('playground', 'v', 'Collection'), (SELECT max(id) + 1 FROM collection_raw)); -- Import Item data INSERT INTO playground."Item" SELECT (age_name_to_idx_start('playground', 'v', 'Item') + id)::text::ag_catalog.graphid, row_to_json((SELECT x FROM (SELECT code, name, price) x))::text::ag_catalog.agtype FROM item_raw; SELECT setval(age_name_to_seq('playground', 'v', 'Item'), (SELECT max(id) + 1 FROM item_raw)); ``` ### Step 5: Import Edge Data ```sql theme={null} -- Import BELONGS_TO edges INSERT INTO playground."BELONGS_TO"(start_id, end_id, properties) SELECT (age_name_to_idx_start('playground', 'v', 'Collection') + start_id)::text::ag_catalog.graphid, (age_name_to_idx_start('playground', 'v', 'Catalog') + end_id)::text::ag_catalog.graphid, '{}'::text::ag_catalog.agtype FROM collection_belongsto_catalog_raw; -- Import PART_OF edges INSERT INTO playground."PART_OF"(start_id, end_id, properties) SELECT (age_name_to_idx_start('playground', 'v', 'Item') + start_id)::text::ag_catalog.graphid, (age_name_to_idx_start('playground', 'v', 'Collection') + end_id)::text::ag_catalog.graphid, '{}'::text::ag_catalog.agtype FROM item_partof_collection_raw; ``` ### Step 6: Verify Data ```sql theme={null} SELECT * FROM ag_catalog.cypher('playground', $$ MATCH (c:Catalog)<-[:BELONGS_TO]-(co:Collection)<-[:PART_OF]-(i:Item) RETURN c, co, i LIMIT 5 $$) AS (catalog ag_catalog.agtype, collection ag_catalog.agtype, item ag_catalog.agtype); ``` ## Next Steps This guide covers the basics of using Apache AGE with Relyt ONE. For in-depth Cypher concepts and detailed query syntax, visit the official [Cypher Query Language documentation](https://neo4j.com/docs/cypher-manual/current/). You can also explore: * Advanced Cypher patterns and techniques * Graph algorithms and analytics * Performance optimization strategies * Building production graph applications # Load Data From Object Store Source: https://docs-relytone.data.cloud/docs/load-data Relyt has built-in pg_duckdb support, enabling the use of DuckDB to read CSV, Parquet, and JSON data from object storage and import it into the database. ## 1. Reading Data from S3 ### 1.1 Supported File Formats pg\_duckdb supports the following file formats: * **CSV**: Use `read_csv()` function * **Parquet**: Use `read_parquet()` function * **JSON**: Use `read_json()` function ### 1.2 S3 Path Format #### Basic Format ``` s3://[endpoint]/[bucket]/[prefix]/filename ``` #### Reading Files with Wildcards * Use `*` to match all files in the current directory: ``` s3://[endpoint]/[bucket]/my_data/* ``` * Use `**` to recursively match all files in subdirectories: ``` s3://[endpoint]/[bucket]/my_data/** ``` #### AWS Endpoint Examples * **Format**: `s3.ap-east-1.amazonaws.com` * **Reference**: [https://docs.aws.amazon.com/general/latest/gr/s3.html](https://docs.aws.amazon.com/general/latest/gr/s3.html) ### 1.3 Basic Usage Examples #### CSV Files ``` SELECT * FROM public.read_csv( 's3://[endpoint]/[bucket]/[prefix]/* accessid=xxxxxx secret=yyyyyy' ); ``` #### Parquet Files ``` SELECT * FROM public.read_parquet( 's3://s3.us-west-1.amazonaws.com/my-bucket/parquet_files/* accessid=XXXX secret=YYYY' ); ``` #### JSON Files ``` SELECT * FROM public.read_json( 's3://s3.ap-east-1.amazonaws.com/tpc-h/table.json accessid=XXXX secret=YYYY' ); ``` ## 2. Advanced Parameter Configuration ### 2.1 CSV Parameters `read_csv()` automatically detects format by default, but also supports manual parameter specification: ``` SELECT * FROM public.read_csv( 's3://xxxx...', delim='|', -- Delimiter escape='"', -- Escape character quote='"', -- Quote character header=true -- Whether header is included ); ``` ### 2.2 JSON Parameters ``` SELECT * FROM public.read_json( 's3://xxxxx...', ignore_errors=true -- Ignore JSON parsing failed rows ); ``` ### 2.3 Parquet Parameters ``` SELECT * FROM public.read_parquet( 's3://xxxx...', filename=true, -- Include filename in results file_row_number=true, -- Include row number in results hive_partitioning=true, -- Use path as partition values union_by_name=true -- Merge different file schemas by column name ); ``` ## 3. Data Import Relyt supports two data import methods: `CREATE TABLE AS SELECT` with automatic schema inference and manual `INSERT INTO SELECT`. ### 3.1 CREATE TABLE AS SELECT `CREATE TABLE AS SELECT` creates a new table and automatically infers data types: ``` -- Automatically create table and import data CREATE TABLE my_table AS SELECT * FROM read_parquet('s3://bucket/data.parquet accessid=xxx secret=yyy'); -- Create table from CSV file CREATE TABLE csv_table AS SELECT * FROM read_csv('s3://bucket/data.csv accessid=xxx secret=yyy'); -- Create table from JSON file CREATE TABLE json_table AS SELECT * FROM read_json('s3://bucket/data.json accessid=xxx secret=yyy'); ``` **Features**: * Creates new table with automatic data type inference * Simple syntax, completes table creation and data import in one step * Suitable for rapid data exploration and initial data import ### 3.2 INSERT INTO SELECT `INSERT INTO SELECT` can insert data into existing tables: ``` INSERT INTO target_table SELECT * FROM read_xxx('s3://...'); ``` **Features**: * Inserts data into existing tables * Requires pre-created table structure * Suitable for appending data to existing tables or scenarios requiring precise table structure control ### 3.3 Data Type Handling **Important Note**: When using `INSERT INTO SELECT` method, `read_xxx()` functions return data type as `struct` (i.e., `duckdb.row`), therefore manual column name and data type conversion specification is required. #### Example 1: Parquet File Import ``` -- Create target table CREATE TABLE NATION ( N_NATIONKEY INTEGER NOT NULL, N_NAME VARCHAR NOT NULL, N_REGIONKEY INTEGER NOT NULL, N_COMMENT VARCHAR, N_DUMMY VARCHAR ); -- Import data INSERT INTO nation SELECT r['n_nationkey']::INTEGER, r['n_name']::VARCHAR, r['n_regionkey']::INTEGER, r['n_comment']::VARCHAR, r['n_dummy']::VARCHAR FROM read_parquet( 's3://xxx/nation.parquet accessid=xxx secret=yyyy' ) r; ``` #### Example 2: CSV File Import without Header For CSV files without headers, use `column0`, `column1`, `column2`... as column names: ``` INSERT INTO nation SELECT r['column0']::INTEGER, r['column1']::VARCHAR, r['column2']::INTEGER, r['column3']::VARCHAR, r['column4']::VARCHAR FROM read_csv( 's3://xxx/.../nation.tbl accessid=xxx secret=yyy' ) r; ``` # Faster queries via columnstore Source: https://docs-relytone.data.cloud/docs/pg_duckdb/columnstore_analytics Shows how to migrate heavy queries from Postgres to DuckDB-backed columnstores for sub-second runtimes. When `duckdb.force_execution` is enabled, pg\_duckdb handles query execution but still relies on PostgreSQL to scan row-store tables. For scans without selective filters, this hybrid flow can bottleneck on PostgreSQL’s table scan before DuckDB ever gets to apply its vectorized magic. Converting hot analytical tables into parquet-backed columnstores removes that bottleneck—the data is read natively by DuckDB, which keeps the entire pipeline columnar. ## Why columnstore tables help * Row-store scans stay in PostgreSQL and are serialized tuple-by-tuple into DuckDB batches. * Columnstore tables (backed by parquet files) are read directly by DuckDB, avoiding the conversion step and enabling parallel columnar IO. * You can keep the original OLTP table for writes while exporting snapshots to parquet whenever you need faster analytics. ## Real example: clickstream engagement ### 1. Create the row-store fact table ```sql theme={null} CREATE TABLE event_log ( event_id BIGSERIAL PRIMARY KEY, event_ts TIMESTAMPTZ NOT NULL, user_id INT NOT NULL, region TEXT, device TEXT, session_minutes NUMERIC(10, 2), ad_impressions INT, revenue NUMERIC(10, 2), payload JSONB ); ``` ### 2. Insert 3 million sample rows ```sql theme={null} INSERT INTO event_log ( event_ts, user_id, region, device, session_minutes, ad_impressions, revenue, payload ) SELECT NOW() - (random() * INTERVAL '730 days'), (random() * 200000)::INT, CASE WHEN random() > 0.66 THEN 'NA' WHEN random() > 0.33 THEN 'EMEA' ELSE 'APAC' END, (ARRAY['ios','android','web'])[1 + (random()*2)::INT], ROUND((random() * 120)::numeric, 2), (random() * 40)::INT, ROUND((random() * 25)::numeric, 2), jsonb_build_object('campaign', md5(random()::text)) FROM generate_series(1, 3000000); -- Refresh statistics ANALYZE event_log; ``` ### 3. Benchmark aggregates on the row-store table Run the single-stage aggregation below first with PostgreSQL’s executor, then flip `SET duckdb.force_execution = true;`. DuckDB still trims latency (about 3.0s → 2.1s), but the scan stays in PostgreSQL so both paths remain in the same ballpark. ```sql theme={null} EXPLAIN ANALYZE SELECT date_trunc('hour', event_ts) AS hour_bucket, region, device, SUM(session_minutes) AS total_minutes, AVG(ad_impressions) AS avg_ads, SUM(revenue) AS total_revenue, COUNT(*) AS events_seen FROM event_log GROUP BY 1,2,3 HAVING SUM(session_minutes) > 1000 ORDER BY total_minutes DESC LIMIT 50; ``` | Engine | Table scanned | Runtime observed | Notes | | - | - | - | - | | PostgreSQL | `event_log` | \~3.0 seconds | Row-store scan plus aggregate materialization | | DuckDB | `event_log` | \~2.1 seconds | DuckDB executes, but scan still comes from PostgreSQL | ## Export to parquet for true columnar IO ### 4. Copy the dataset to parquet files Prerequisites: * Access to an S3-compatible object store that DuckDB can reach. Exports to object storage always run with DuckDB automatically, so no GUC changes are needed. Relyt ONE’s built-in cache service further boosts bandwidth/latency for repeated parquet scans—nothing to configure on your end. ```sql theme={null} COPY ( SELECT * FROM event_log ) TO 's3:////event_log/data.parquet accessid=xxx secret=yyy'; ``` ### 5. Create an external table ```sql theme={null} CREATE TABLE event_log_cstore () USING duckdb WITH ( duckdb_external_location = 's3:////event_log/data.parquet accessid=xxx secret=yyy', duckdb_external_format = 'parquet' ); ``` For more details on DuckDB-backed external tables, see [external tables](../external_table). ### 6. Rerun the query against the columnstore ```sql theme={null} EXPLAIN ANALYZE SELECT date_trunc('hour', event_ts) AS hour_bucket, region, device, SUM(session_minutes) AS total_minutes, AVG(ad_impressions) AS avg_ads, SUM(revenue) AS total_revenue, COUNT(*) AS events_seen FROM event_log_cstore GROUP BY 1,2,3 HAVING SUM(session_minutes) > 1000 ORDER BY total_minutes DESC LIMIT 50; ``` | Engine | Table scanned | Runtime observed | Notes | | - | - | - | - | | DuckDB | `event_log_cstore` | \~0.8 seconds | Fully columnar scan, vectorized aggregation | Scanning parquet with DuckDB removes the PostgreSQL scan bottleneck entirely, dropping the aggregation from \~2 seconds to \~0.8 seconds. Refresh the parquet snapshot whenever you need fresher analytics, and continue to use the OLTP `event_log` table for day-to-day writes. # pg_duckdb hands-on Source: https://docs-relytone.data.cloud/docs/pg_duckdb/quick-start Accelerate analytical SQL by enabling pg_duckdb with a single session GUC—no query rewrites or data movement required. Relyt ONE ships with [pg\_duckdb](https://github.com/duckdb/pg_duckdb), a DuckDB-based columnar execution engine. It accelerates analytical SQL workloads on your operational data with no schema changes or ETL. This hands-on guide walks you through enabling pg\_duckdb, running starter queries, and stress-testing a larger dataset so you can feel the speedup directly in `psql` or your favorite client. ## Step 1. Create a sample table and seed data The following SQL creates a transactional `orders` table and inserts a few rows for testing. ```sql theme={null} -- Create a standard PostgreSQL table CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, product_name TEXT, amount DOUBLE PRECISION, order_date DATE ); -- Insert sample rows INSERT INTO orders (product_name, amount, order_date) VALUES ('Laptop', 1200.00, '2024-07-01'), ('Keyboard', 75.50, '2024-07-01'), ('Mouse', 25.00, '2024-07-02'); ``` ## Step 2. Route queries through DuckDB Enable the DuckDB execution engine for the current session. With this single GUC, all supported queries automatically run on the vectorized engine. ```sql theme={null} SET duckdb.force_execution = true; ``` To make DuckDB the default executor for every new connection, set the GUC at the role or database level (changes apply only to sessions started after the ALTER runs): ```sql theme={null} ALTER ROLE SET duckdb.force_execution = true; ALTER DATABASE SET duckdb.force_execution = true; ``` No query rewrites are required—keep using PostgreSQL syntax. ## Step 3. Run analytical queries ### Aggregate revenue by product ```sql theme={null} SELECT product_name, SUM(amount) AS total_sales, COUNT(*) AS order_count FROM orders GROUP BY product_name ORDER BY total_sales DESC; ``` ### Aggregate revenue by day ```sql theme={null} SELECT order_date, SUM(amount) AS daily_sales, COUNT(*) AS order_count FROM orders GROUP BY order_date ORDER BY order_date; ``` These queries now execute on DuckDB’s columnar engine, delivering lower latency and more predictable performance for aggregation-heavy workloads. ## Real analytical workload example For a more realistic benchmark, seed a `sales_log` fact table with three million synthetic transactions and then route a complex window query through DuckDB. ### Create the transactional table ```sql theme={null} CREATE TABLE sales_log ( sale_id SERIAL PRIMARY KEY, sale_date DATE NOT NULL, amount NUMERIC(10, 2), user_id INT, region TEXT, category TEXT, comment TEXT ); ``` ### Insert 3 million sample rows ```sql theme={null} INSERT INTO sales_log ( sale_date, amount, user_id, region, category, comment ) SELECT '2020-01-01'::DATE + (random() * 1500)::INT, (random() * 1000)::NUMERIC(10, 2), (random() * 10000)::INT, CASE WHEN random() > 0.5 THEN 'North America' ELSE 'Asia Pacific' END, 'Category-' || (random() * 50)::INT, md5(random()::TEXT) || md5(random()::TEXT) FROM generate_series(1, 3000000); ``` Refresh planner statistics so both executors have accurate metadata: ```sql theme={null} ANALYZE sales_log; ``` Optionally confirm the on-disk size: ```sql theme={null} SELECT pg_size_pretty(pg_total_relation_size('sales_log')) AS table_size; ``` ### Benchmark the window-heavy query 1. **Run with PostgreSQL’s executor (default)**\ Leave `duckdb.force_execution` unset (or explicitly `SET duckdb.force_execution = false;`) and execute the analytical query below. Record the elapsed time from `EXPLAIN ANALYZE`. 2. **Enable DuckDB and rerun**\ Turn on DuckDB for the current session and immediately run the same SQL again to compare results: ```sql theme={null} SET duckdb.force_execution = true; ``` The query operates directly on the `sales_log` row-store table, grouping three million rows into 10,000 user partitions, applying a moving average window, filtering anomalies, and sorting the top 100 largest deviations: ```sql theme={null} EXPLAIN ANALYZE WITH user_history AS ( SELECT sale_id, user_id, sale_date, amount, AVG(amount) OVER ( PARTITION BY user_id ORDER BY sale_date ROWS BETWEEN 50 PRECEDING AND 1 PRECEDING ) AS user_recent_avg FROM sales_log ) SELECT * FROM user_history WHERE amount > (user_recent_avg * 5) ORDER BY amount DESC LIMIT 100; ``` | Executor | `duckdb.force_execution` | Runtime observed | | - | - | - | | PostgreSQL | `false` (default) | \~5.8 seconds | | DuckDB engine | `true` | \~1.5 second | Your mileage may vary based on hardware and background workload, but the pattern—run once with PostgreSQL, flip the GUC, rerun with DuckDB—makes it easy to validate the speedup yourself. ## Key benefits * **Seamless integration**: Works with existing PostgreSQL SQL and tooling. * **High performance**: Vectorized execution with automatic parallelism for scans and aggregations. * **Zero friction**: A single session parameter (`duckdb.force_execution`) controls the engine. ## Operational tips ### Automatic fallback If a statement includes features not supported by DuckDB, Relyt automatically falls back to the default PostgreSQL executor. No manual intervention is required. ### Inspect the execution engine Use `EXPLAIN` to verify whether DuckDB handled the query: ```sql theme={null} EXPLAIN SELECT product_name, SUM(amount) AS total_sales FROM orders GROUP BY product_name; ``` Look for DuckDB nodes in the plan to confirm the handoff. If you only see PostgreSQL plan nodes, the fallback path was used. # Vector Search Source: https://docs-relytone.data.cloud/docs/vector-search/quick-start This guide will help you quickly get started with vector search functionality through practical SQL examples. ## 1. Create Table and Prepare Data First, we need to create a table with vector fields and insert test data. ### Create Table Structure ``` CREATE TABLE test_tbl ( id serial primary key, embedding vector(3), ts TIMESTAMP ); COMMENT ON COLUMN test_tbl.id IS 'Primary key, auto-increment sequence'; COMMENT ON COLUMN test_tbl.embedding IS '3-dimensional vector field'; COMMENT ON COLUMN test_tbl.ts IS 'Timestamp field'; ``` ### Insert Test Data ``` INSERT INTO test_tbl (embedding, ts) SELECT ARRAY[random(), random(), random()]::real[ ]::vector, now() - '1 days'::interval * (random() * 10)::int FROM generate_series(1, 1000); ``` This statement will insert 1000 records, each containing: * Randomly generated 3-dimensional vectors * Random timestamps within the past 10 days ## 2. Create Vector Index To improve vector search performance, we need to create an HNSW index. ``` CREATE INDEX test_vector_idx ON test_tbl USING vectors (embedding vector_l2_ops); ``` **Index Parameter Descriptions:** * `USING vectors`: Use vector index type * `vector_l2_ops`: Operator class that calculates squared Euclidean distance (L2 distance) ## 3. Execute Vector Search ### Basic Similarity Search Find the 5 most similar vectors to the target vector `[3,1,2]`: ``` SELECT id, embedding <-> '[3,1,2]' as dist FROM test_tbl ORDER BY dist LIMIT 5; ``` **Operator Description:** * `<->`: Calculate L2 distance between two vectors * Smaller distance indicates higher similarity ### Complex Conditional Search Query data from the past 5 days with similarity scores above a threshold: ``` SELECT b.* FROM ( SELECT a.id, a.dist * 10 AS similarity FROM ( SELECT id, embedding <-> '[3, 1, 2]' AS dist FROM test_tbl WHERE ts > now() - '5 days'::interval ORDER BY dist ASC LIMIT 100 ) as a ) as b WHERE b.similarity > 50 OFFSET 0 LIMIT 20; ``` **Query Logic:** 1. Inner query: Filter data from the past 5 days, sort by distance and take top 100 records 2. Middle query: Convert distance to similarity score (multiply by 10) 3. Outer query: Filter records with similarity greater than 50, return 20 results # Pricing Source: https://docs-relytone.data.cloud/pricing/pricing RelytONE offers flexible pricing plans designed to meet your needs at every stage. > [!NOTE] > > The **Pro Plan** is coming soon — stay tuned for its release. ## Member Plan **\$0.00** per month Perfect for learning and exploration in the cloud. **What's included:** * 1 Organization * Up to 5 Projects * 2.5 GB storage (0.5 GB per project) * Unlimited shared compute hours > [!NOTE] > > **Unlimited shared compute hours** are provided on a shared infrastructure with dynamic scheduling. Ideal for development and testing. For production workloads, consider upgrading to the **Pro Plan**. ## Pro Plan **\$9.00** per month *(Coming Soon)* Built for production and scale. **What's included:** * 1 Organization * Up to 50 Projects * 20 GB storage shared across all projects (additional storage at \$0.25/GB) * 500 dedicated compute hours (additional hours at \$0.10/CU hour) * Dedicated resources with flexible specs (up to 16 cores) * Unlimited shared compute > [!NOTE] > > **Understanding Compute Hours:** > > Compute hours are calculated as: **CU size × active hours** > > A CU (Compute Unit) represents instance size at RelytONE. **1 CU = 1 vCPU + 4 GB RAM** > > For example: > > * A 2 CU instance (2 vCPU + 8 GB RAM) running for 10 hours = 20 compute hours > * A 4 CU instance (4 vCPU + 16 GB RAM) running for 5 hours = 20 compute hours **Pricing examples:** *Storage:* * Using 15 GB across all projects: **\$9.00/month** (within included limit) * Using 22 GB across all projects: **\$9.50/month** (\$9.00 + 2 GB × \$0.25) *Compute hours (across 3 projects):* * Project A: 200 hours, Project B: 250 hours, Project C: 50 hours * Total: 500 hours → **\$9.00/month** (within included limit) * Project A: 300 hours, Project B: 200 hours, Project C: 100 hours * Total: 600 hours → **\$19.00/month** (\$9.00 + 100 hours × \$0.10) ## Business Plan **Custom pricing** Tailored solutions for enterprise needs. Contact our sales team to discuss your specific requirements. # Privacy Notice Source: https://docs-relytone.data.cloud/security/privacy-notice Last updated: September 20, 2024 This Privacy Notice describes how DATACLOUD and its affiliates and subsidiaries ("DATACLOUD","we","our", or"us") collect, store, use, disclose, and transfer (hereinafter "process") your personal information in the course of our business through our websites and applications that reference to this Privacy Notice (the "Sites"), our Native Data-Centric Cloud (the "Service"), and other means such as our and our partner's events, sales, and marketing activities. It also provides information about your privacy rights and your available choices. ## **Our service** We provide the Service to our customers and users (collectively,"Customers") according to our agreement with them and solely for their benefit and the benefit of their personnel and other personnel authorized to use the Service ("Authorized Users"). Our customers can efficiently store and analyze all their data on the Service, subject to DATACLOUD's agreement with customers and any applicable laws. This Privacy Notice does not apply to the content that our Customers and their Authorized Users upload and store in the Service ("Customer Content"). In the following situations, you should read customers' privacy notices and direct your queries to them: 1. DATACLOUD is processing Customer Content on behalf of a Customer and the Customer is responsible for the collection and use of your data; and 2. That customer's privacy notice will apply to the customer's collection and use of such Customer Content. The customer's agreement with DATACLOUD governs our processing of Customer Content in these circumstances. For more information about our data collection and use in connection with our Service, see the "When you use the Service" part in Information we automatically collect. ## **1. Information we collect about you** ### **Information you provide to us** When you use the Sites or the Service, we may need you provide some personal information to us, such as your name, email address, and phone number. We will inform you of the type of personal information we collect and the reason why we need it at the point we ask you for it during your usage of the Sites or the Service, including when you sign up to the Service and create an account through our Sites. We will not collect any information without your consent no matter if it is compulsory or may be provided on a voluntary basis. For example, when you use the Sites, we may collect your name, email, phone number, and other information you provide via the Sites when you submit inquiries, complete surveys or download DATACLOUD collateral, provide feedback about our services, or perform other operations that require you provide certain personal information. ### **Information we receive from third parties** We may receive information about you from third parties such as resellers, distributors, business partners, event sponsors, security and fraud detection services, and social media platforms. Such information may include your name, email address, phone number, and similar contact information, as well as purchase, support, and other interaction-related data you have with the Sites and the Service. We may combine this information with the data that we have obtained directly from you. ## **2. How we use your information** We use personal information collected via the Sites, our Service, and other means for any of the following purposes: * to operate, audit,improve, and deliver our Sites and Service; * to provide and facilitate the delivery of requested services, customer service, and support; * to monitor, detect, report, and resolve bugs, errors, and illegal or malicious behavior; * to conduct research and analyze data for better service experience and customer experience; * to maintain your account; * to send you updates, technical notices, confirmations, invoices, and other relevant information; * to communicate with you about our events, partner events, webinars, demos, and to respond to your inquiries, comments, and requests for information; * to understand your preferences and provide you with personalized experiences when using our Sites and Service; * to process contest entries, rewards, and survey responses; * to display and measure engagement with ads across different sites and devices; * to comply with regulatory and legal obligations, as well as to customize content on our platforms and services; * to process your information for short-term or transient use; * to link your information with personal data from third parties to improve services, prevent fraud, and identify usage trends; and * to process your information for other legitimate business purposes, such as data analysis, auditing, generating feedback, and evaluating marketing campaigns. We may store and process personal information in different countries in compliance with the applicable laws. ## **3. How we share your information** We try every effort to ensure the security of your information. We do not share your information with third parties unless: * with our affiliates and subsidiaries, in which case the information will be processed as otherwise described in this Privacy Notice; * where it has been de-identified, including through aggregation or anonymization; * when you instruct us to do so; * with your consent, for example, when you agree to our disclosing your information with other third parties for their own marketing purposes subject to their separate privacy policies; * with third-party vendors who work for us to provide services such as billing, payment card processing, and sales and marketing, as long as they abide confidentiality obligations and the requirement that those service providers do not sell your personal information; * with third-party business partners, including resellers, distributors, and referral partners, who help us fulfill service and information requests and inform prospective and existing clients about DATACLOUD and its offerings. We may participate in joint sales or promotions with selected business partners, in which case we may share relevant personal information if you purchase or express interest in the jointly offered service, promotion, or service. Where you have given consent, these partners may send you marketing communications about their own services. Please note that we do not have control over our partners' use of your information, and they are responsible for managing their own handling of any personal information collected in these circumstances. We recommend that you review the privacy notices of relevant business partners to learn more about how they handle your personal information. * to comply with legal requirements and respond to lawful requests and processes, protect our property and that of our agents, customers, members, and others (including enforcing our agreements, policies, and terms of use), or protect personal safety in emergency situations. * to protect any individual's vital interests, but only when we think it is necessary; and * in connection with or during business transfer, merger, financing, acquisition, or dissolution procedures where there requires sale, transfer, divestiture, or disclosure of all or part of our business or assets. ## **4. International data transfers** In compliance with the applicable laws, we may transfer your personal information to countries other than your country of residence in some cases. Particularly, we may transfer your personal information to other countries where our affiliates, business partners, and service providers are located. The data protection laws in these countries may be different from the laws adopted in the country where you reside. However, we always protect your information following this Privacy Notice and relevant laws. To ensure this protection, we follow the European Commission's Standard Contractual Clauses when transferring personal information from the European Economic Area (EEA) or Switzerland between us, business partners, and service providers. We also utilize additional measures to guarantee the security of your information. ## **5. Your choices and rights** We provide you with options concerning the collection, use, and sharing of your information, and we will honor the choices you make according to relevant laws. Nevertheless, please keep in mind that choosing not to provide certain personal information may prevent you from accessing particular features of the Sites or using the Service. ### **Account information** If you want to modify or delete your account information, please log in to the Sites or the Service and update your profile. ### **Opt out of marketing** You may opt out of receiving promotional emails from us by following the instructions in those emails. If you opt out, we may still send you non-promotional emails, such as communications about your subscription and account. You may also send requests about your contact preferences and changes to your information by emailing [contact@data.cloud](mailto:contact@data.cloud). ### **Your privacy rights** You may have specific rights concerning your personal information, depending on the country in which you are resident. Please review the sections that apply to your jurisdiction. These rights may encompass asking us to provide information about how we collect and process your information, requesting access, correction, or deletion of it. You may also withdraw your consent if we rely on it to process your personal information. To exercise any of your rights concerning applicable data protection laws, you can complete the request form or email us at [contact@data.cloud](mailto:contact@data.cloud). We will respond to any requests we receive following the laws that apply. We may verify the authenticity of your request by using information present in our systems, such as your email address or other data connected with your DATACLOUD cloud account. If required, we may ask you to supply additional information to verify your request. Any data you give us for verification will only be used to maintain a record of your request and process it. As previously mentioned, we may also process personal information that has been submitted by a Customer to our Service. If your personal information has been submitted to the Service by or on behalf of a Customer and you wish to exercise your privacy rights, please direct your request to the relevant Customer. For other inquiries, please contact us at [contact@data.cloud](mailto:contact@data.cloud). ## **6. Additional information for certain jurisdictions** This section provides additional information about our privacy practices for certain jurisdictions. ### **California** If you are a California resident, the California Consumer Privacy Act ("CCPA") stipulates that we specify how we collect, use, retain, and disclose your personal information. This section contains the necessary description. For more details, please read this Privacy Notice in full. **Information we collect and how we share information** DATACLOUD does not sell personal data according to the definition laid out in the CCPA and its regulations. However, we do share personal data (as per CCPA regulations defined in the second table below). The subsections below outline the types of personal data we obtain from you and which third parties we share that information with for business purposes. Table 1: Information we collect and to whom we share the information | **Category** | **Example data** | **Recipient** | | :- | :- | :- | | Identifiers | Name and email address | Service providers Third parties (for purposes described in section "How We Share Your Information") | | Customer records/account registration information | Address, telephone number, and financial information | Service providers Third parties (for purposes described in section "How We Share Your Information") | | Characteristics of protected classifications under California or Federal law | Gender and marital status | Service providers | | Commercial information | Transaction data | Service providers Third parties (for purposes described in section "How We Share Your Information") | | Internet and other network activities | Browsing history | Service providers | | Geolocation data | Location inferred from your IP address | Service providers | | Professional or employment-related data | Employer's name | Service providers Third parties (for purposes described in section "How We Share Your Information") | | Education information | Degrees and certifications | Service providers | Table 2: Personal information shared in the preceding 12 months
**Category** **Recipient** **Why we share**
Identifiers and contact information
  • Social media and advertising platforms
  • Advertisers
  • Ad agencies
  • Other advertising-related service providers
  • Cross-context behavioral advertising (For details about our cookie policies, please see Cookie Notice.)
Analytics and other network activities
DATACLOUD does not use or disclose sensitive personal information unless for purposes authorized by the CCPA. DATACLOUD is not informed of any sales or sharing of personal information about individuals under 16 years old. **How we collect information about you​** For details, see Information we collect about you. **Why we need your information** We collect your personal information to keep in contact with you, to provide and improve our services, and for marketing and promotional purposes. For details about how we use your information listed in the tables above, see How we use your information. **How we retain your information** For details, see How your information is retained and deleted. **Your choices and rights** You can make certain requests with regard to your personal information based on California law. For information about how to make such a request, see Your choices and rights. ### **Other US states** Depending on the applicable laws in your state of residence, you may request: * confirmation that we are processing your personal information; * access to, correction of, or deletion of your personal information; * a portable copy of your personal information that we collect; and * restraint or opt-out of particular processing of your personal information, such as targeted advertising or profiling. If we refuse to act on your request, we will provide instructions on how to dispute the decision. We will respond to any requests in accordance with relevant laws. ### **European Economic Area, UK, and Switzerland** If you are located in the European Economic Area, United Kingdom, or Switzerland, DATACLOUD Technology is responsible for managing your personal information. However, there may be times when our affiliates collect and manage your information, such as during local events, surveys, or training sessions. In these cases, we will inform you through context-specific notifications when we collect your personal information. We do not collect your personal information unless legally permitted. The basis for processing depends on the details of the personal data and the situation in which we collect it. Generally, we collect and process your personal information only when: * It is required to fulfill or execute a contract with you, such as providing the Service or customer support. * Processing your personal data is necessary to comply with the law (such as legal, tax, or accounting requirements), or to guarantee your vital interests and those of other individuals. * You have given us permission to use your personal information, for example, to send you promotional messages. * We have a legitimate interest, such as answering your inquiries and concerns, ensuring the Sites and the Service are secure, detecting and preventing fraud, managing and enhancing the Service, promoting DATACLOUD services, and protecting our rights and interests. If you want to exercise your rights under applicable data protection laws, please contact us by following the instructions provided in Your choices and rights. ## **7. How your information is retained and deleted** We retain your personal information for valid business reasons, such as upholding legal or tax obligations, enforcing our agreements, or fulfilling other legal requirements. We will delete or anonymize your personal information once there are no more valid business reasons to hold onto it. In the rare case that we cannot do so (for example, if your personal information is still saved in backup archives), we will store your personal information securely, restricting any further processing, until it can be deleted. When processing content on behalf of our customers, we will do so for as long as the customer requires, or until we are legally obligated to retain the information by law. ## **8. Changes to this Notice** We may update this Notice occasionally. Each time we change the Notice, we will update the "Last updated" date at the start of this Notice. For any significant changes, we will notify you further, such as by editing the main website page or sending you an email message. ## **9. Contact us** If you have any questions about this Notice or privacy-related issues, please contact us at [contact@data.cloud](mailto:contact@data.cloud). If you interact with us on behalf of your organization, your personal information may be subject to your organization's privacy policies, and you should contact your organization directly with any concerns. # Terms of Service Source: https://docs-relytone.data.cloud/security/terms-of-service Effective Date: September 20, 2024 These DATACLOUD Terms of Service ("Agreement") govern the access to or use of DATACLOUD offerings, and is part of a legal contract between the entity or person ("Customer" or "you") and DATACLOUD ("DATACLOUD", "we", "our", or "us"). This Agreement includes the terms and conditions stated herein, any ancillary documents (such as addendums and exhibits) explicitly deemed part of this Agreement, and any Order Forms that reference this Agreement. The "Effective Date" of this Agreement refers to the earlier of the following two dates: (a) the date on which you first access any DATACLOUD offering through any online setup, registration, or ordering process; or (b) the effective date of the first Order Form that references this Agreement. ## **1. General** 1. You may choose to use one or more services of DATACLOUD according to your own needs. DATACLOUD will provide the corresponding service standards in accordance with the service(s) you choose to use. 2. This Agreement, as the foundational agreement for your use of DATACLOUD services, is legally binding on both parties. DATA CLOUD will publish and display service specifications/terms, [Service Level Agreement](https://data.cloud/legal/service-level-agreement/), service descriptions, technical specifications, usage processes, operational documentation, billing standards, and other content related to specific DATACLOUD services (collectively referred to as "Service Rules") through the DATACLOUD website or other agreed-upon means, which together with this Agreement, constitute binding documents on both parties. Your use of services provided by DATACLOUD is deemed as acceptance of the Service Rules posted on the DATACLOUD website. 3. You understand that the content of the Service Rules publicly announced on the DATACLOUD website may change from time to time. In the event of a change, DATACLOUD shall announce the changes on an appropriate page of the DATACLOUD website 30 days in advance, notifying you of the modification. If you do not agree with the modification of the content, you have the right to terminate this Agreement and stop using the services provided by DATACLOUD; if you continue to use DATA CLOUD's services, it is deemed as acceptance of the modified terms. ## **2. Account** 1. To use DATACLOUD services, you need to register an account through the DATACLOUD console. The account serves as a service identifier for DATACLOUD to provide you with services. Relying on the account, you can access corresponding DATACLOUD services, including self-service subscription, bill inquiry, fee payment, resource management, and receiving notifications. 2. The account is for your personal use only; without DATA CLOUD's consent, you may not provide the account for use by others in any manner. You are responsible for all actions taken under your account, and all operations conducted under the account are considered to be performed by you, for which you shall bear all legal consequences. If there is any unauthorized use under your account, you should immediately notify DATACLOUD so that DATACLOUD can provide you with the necessary assistance. 3. If your account information at DATACLOUD is inaccurate, or if your account information changes, you are required to update it promptly. DATACLOUD has the right to verify your account information. If it is found that your account information is inaccurate, erroneous, or does not meet legal and regulatory requirements, DATACLOUD will notify you to correct it within a specified deadline. 4. You have the right to apply for the cancellation of your account with DATACLOUD. Provided that it does not violate legal and regulatory requirements and follows the rules for account cancellation, DATACLOUD shall cancel your account in accordance with your application. The act of canceling an account is irreversible; once you have completed the cancellation of your account, you will no longer be able to log in to that account. Please proceed with caution. ## **3. Subscription** 1. You can, according to your own needs, place orders online through the DATACLOUD website to subscribe, add, or reduce required services. Once your order is confirmed by the DATA CLOUD system and shown as successfully placed (confirmation methods include but are not limited to both parties affixing their seals, or your online click confirmation at the time of service subscription), it is considered that the service subscription is successful. DATACLOUD will then provide services to you in accordance with the services ordered by DATACLOUD under the contract. 2. DATACLOUD may, for various reasons such as customer feedback, marketing promotions, etc., provide specific services or parts of services (hereinafter referred to as "Complimentary Services") to eligible customers. You understand and agree that Complimentary Services are additional benefits provided by DATACLOUD to its customers. The service content of Complimentary Services (including but not limited to service standards, etc.) may differ from that of services purchased at regular prices. You need to pay attention to and confirm your agreement to accept these terms; otherwise, please do not use the Complimentary Services. 3. DATACLOUD may occasionally offer free trial services such as public beta, private beta, etc., which you can access through voluntary application and by adhering to this Agreement and the related provisions of the free services. You understand that such free services are usually not long-term or permanent, and DATACLOUD does not make any promises regarding the availability and reliability of these services, nor will it bear any responsibility for the results of your use of these services. DATACLOUD reserves the right to potentially make commitments regarding the availability and reliability of such free services and to charge fees for them. Before charging any service fees, DATACLOUD will notify you separately. ## **4. Service Fees** 1. The service fees are based on the charging standards listed in the DATACLOUD website's pricing page on the date the product order is signed. You can choose the specific service type and pay according to the prices listed. For specific charging rules, please refer to the display on the DATACLOUD website pages and abide by the billing models and standards effective at the time as announced on the pages. 2. You can access DATACLOUD services through either a prepaid or postpaid method, depending on the payment method supported by the service you order. For "prepaid" , you need to submit the order and complete payment before DATA CLOUD provides the corresponding service; for "postpaid" , you use the service first and then make the payment, and you must pay the fees within the payment deadline determined by the service rules of the service. Specifically, based on your business credit, you may be granted a "credit limit" by DATACLOUD, allowing you to enjoy the convenience of postpaying for some services that normally require prepaid payments, within the credit limit. You understand that the credit limit you can obtain from DATACLOUD is determined by DATACLOUD's assessment of your business credit, and DATACLOUD reserves the right to adjust it. 3. For service fee settlements that adopt a prepaid model, you are required to precharge and pay per usage. This means you need to recharge your balance in advance into the account associated with the DATACLOUD product you have registered (by transferring funds to a bank account designated by DATA CLOUD). The account balance must meet a certain amount (for example, 500 yuan, but the actual amount is subject to the specific product description) before you can start creating and using product services. The balance can be obtained through various means (for example: recharging, vouchers, etc.). The service of DATACLOUD products generates a usage bill for your actual usage on an hourly basis, measured in natural hours (starting from the whole hour in UTC), and then deducts it from your account balance. You need to ensure in a timely manner that the account balance for your DATACLOUD product is sufficient to pay for the usage bills generated hourly in the past. If the account balance is insufficient or the remaining balance falls below a certain value, DATACLOUD will send you a reminder to recharge your account balance (via email, SMS, or in-console messages, etc.). If the account balance is insufficient, DATACLOUD will provide your account with a certain duration of credit period (for example, you can continue to use the services normally within 24 hours after the corresponding billing hour when the deduction was unsuccessful; the specific credit period is subject to the actual notice you receive from DATACLOUD). You should recharge your account balance promptly to avoid service disruptions. If, after entering the credit stage, there continue to be several billing cycles of insufficient balance lasting several hours, this will trigger certain actions by the DATA CLOUD product on the service units within the product (including freezing, reclaiming, deletion, etc. For specific lifecycle management methods, please refer to the relevant product documentation of the DATACLOUD product). DATACLOUD typically generates the bill for the previous natural hour during the next natural hour period. However, it does not rule out the possibility of billing delays due to force majeure reasons such as network issues or basic cloud services. DATACLOUD will compensate for the delayed bills in a subsequent natural hour billing cycle. After the bill is generated, the account balance will then be deducted. 4. Unless otherwise agreed upon by both parties through a product order or other written means regarding fee settlement and payment, DATACLOUD shall reconcile your service usage for the previous month within the first 5 business days of each calendar month. You shall pay the corresponding service fees to the designated bank account of DATACLOUD within 5 business days upon receiving the bill. You may check your fee consumption status and bill through logging into your product account or the previously specified bill-receiving email address, among other methods. DATACLOUD will provide you with a bill each month, which serves as the evidence of fee settlement between both parties. If you have any objections to the bill, you should raise them to DATACLOUD within 5 business days after receiving the bill. If no objections are raised within the aforementioned period, it will be considered that you have confirmed the bill. For bills in dispute, both parties shall conduct a verification, and the bill confirmed by both parties after verification shall prevail. During the verification period, you should first pay the undisputed portion of the amount. If you do not accept the verification results but do not have conclusive evidence to prove an error in the bill"s charges, then the settlement fee shall be based on the bill provided by DATACLOUD. 5. To avoid ambiguity, it is agreed in this Agreement that the fees are inclusive of taxes. DATACLOUD will issue an official Value-Added Tax (VAT) invoice of the equivalent amount to you within 5 business days from the date of completion of the monthly reconciliation between both parties. In the event of an adjustment to the national tax rate, the total amount including taxes shall be adjusted accordingly. In cases of sales discounts, sales returns, or other situations requiring the issuance of a new invoice or a credit note (red invoice) according to national tax regulations, you are required to return the previously issued invoice to DATACLOUD or provide the necessary information for the issuance of a credit note (red invoice). This will be executed according to the following policy: * If the return of the invoice occurs within the month of issuance and you have not yet conducted tax certification deductions, you can simply return the invoice. * If you have already conducted tax certification deductions for that invoice, or if the time for returning the invoice has exceeded the month of issuance, you should provide DATACLOUD with the necessary information for the issuance of a credit note (red invoice), such as the "VAT Special Invoice Red Letter Information Table". * If DATACLOUD has not yet issued the invoice or has issued the invoice but has not yet delivered it to you, there is no need for you to provide any invoice-related information. After completing the above operations, you may apply for the re-issuance of an invoice based on the actual payment (payable) amount to DATACLOUD, and both parties shall handle the corresponding refund. If the conditions above are not met, re-issuance of invoices and refunds cannot be processed, and DATACLOUD shall not bear any responsibility in this regard. After completing the above operations, you may apply for the re-issuance of an invoice based on the actual payment (payable) amount to DATACLOUD, and both parties shall handle the corresponding refund. If the conditions above are not met, re-issuance of invoices and refunds cannot be processed, and DATACLOUD shall not bear any responsibility in this regard. 6. When your account in DATACLOUD products has no resource occupation or consumption and all billing items have been settled, you may apply for a refund of the balance in your account for DATACLOUD products. Each time you add funds to your DATACLOUD product account, a transaction record is generated. Refund requests must be associated with specific transaction records. When deductions are made from your account balance, these are applied to the balances of individual transaction records. Deductions are processed in chronological order, starting with the earliest transaction. During promotional activities, such as receiving a USD 50 bonus on a USD 100 recharge—effectively increasing your account balance by USD 150—deductions will first apply to the actual recharged amount in the transaction. Once the recharged amount is fully deducted, the bonus balance will then be used. It"s important to note that bonus balances are not eligible for refunds or withdrawals and will be cleared when a refund for the associated transaction is issued. Upon receiving a refund request, DATACLOUD will refund the actual balance of the specified recharge record to your bank account through the original payment method within 5 business days. 7. You should pay fees to DATACLOUD promptly and in full. If you incur overdue payments, DATACLOUD may issue reasonable reminders or demands and is entitled to charge a penalty at the rate of 0.05% of the overdue amount per day. If you fail to pay the service fees in full as agreed, in addition to requiring you to bear the corresponding liability for breach of contract, DATACLOUD also reserves the right to immediately take measures such as suspending or terminating the provision of the relevant services. 8. DATACLOUD may offer various promotional incentives, including limited-time free access, time-sensitive discounts, quantity-limited offers, recharge bonuses, and complimentary services, due to marketing campaigns and product promotion efforts during specified periods. It is understood that all such promotional activities or complimentary service offerings within DATACLOUD’s pricing framework might be temporary, offered in stages, or available in limited quantities, and could be restricted to customers who satisfy certain conditions. You are obligated to adhere to the specific rules when purchasing and utilizing these services. Unless expressly indicated in writing, promotional offers from DATACLOUD are not eligible to be used in conjunction with any other promotions. 9. To avoid ambiguity, it is agreed in this Agreement that the fees are inclusive of taxes. DATACLOUD will issue an official Value-Added Tax (VAT) invoice of the equivalent amount to you within 5 business days from the date of completion of the monthly reconciliation between both parties. In the event of an adjustment to the national tax rate, the total amount including taxes shall be adjusted accordingly. In cases of sales discounts, sales returns, or other situations requiring the issuance of a new invoice or a credit note (red invoice) according to national tax regulations, you are required to return the previously issued invoice to DATACLOUD or provide the necessary information for the issuance of a credit note (red invoice). This will be executed according to the following policy: * If the return of the invoice occurs within the month of issuance and you have not yet conducted tax certification deductions, you can simply return the invoice. * If you have already conducted tax certification deductions for that invoice, or if the time for returning the invoice has exceeded the month of issuance, you should provide DATACLOUD with the necessary information for the issuance of a credit note (red invoice), such as the "VAT Special Invoice Red Letter Information Table". * If DATACLOUD has not yet issued the invoice or has issued the invoice but has not yet delivered it to you, there is no need for you to provide any invoice-related information. After completing the above operations, you may apply for the re-issuance of an invoice based on the actual payment (payable) amount to DATACLOUD, and both parties shall handle the corresponding refund. If the conditions above are not met, re-issuance of invoices and refunds cannot be processed, and DATACLOUD shall not bear any responsibility in this regard. After completing the above operations, you may apply for the re-issuance of an invoice based on the actual payment (payable) amount to DATACLOUD, and both parties shall handle the corresponding refund. If the conditions above are not met, re-issuance of invoices and refunds cannot be processed, and DATACLOUD shall not bear any responsibility in this regard. 10. When your account in DATACLOUD products has no resource occupation or consumption and all billing items have been settled, you may apply for a refund of the balance in your account for DATACLOUD products. Each time you add funds to your DATACLOUD product account, a transaction record is generated. Refund requests must be associated with specific transaction records. When deductions are made from your account balance, these are applied to the balances of individual transaction records. Deductions are processed in chronological order, starting with the earliest transaction. During promotional activities, such as receiving a USD 50 bonus on a USD 100 recharge—effectively increasing your account balance by USD 150—deductions will first apply to the actual recharged amount in the transaction. Once the recharged amount is fully deducted, the bonus balance will then be used. It"s important to note that bonus balances are not eligible for refunds or withdrawals and will be cleared when a refund for the associated transaction is issued. Upon receiving a refund request, DATACLOUD will refund the actual balance of the specified recharge record to your bank account through the original payment method within 5 business days. 11. You should pay fees to DATACLOUD promptly and in full. If you incur overdue payments, DATACLOUD may issue reasonable reminders or demands and is entitled to charge a penalty at the rate of 0.05% of the overdue amount per day. If you fail to pay the service fees in full as agreed, in addition to requiring you to bear the corresponding liability for breach of contract, DATACLOUD also reserves the right to immediately take measures such as suspending or terminating the provision of the relevant services. 12. DATACLOUD may offer various promotional incentives, including limited-time free access, time-sensitive discounts, quantity-limited offers, recharge bonuses, and complimentary services, due to marketing campaigns and product promotion efforts during specified periods. It is understood that all such promotional activities or complimentary service offerings within DATACLOUD’s pricing framework might be temporary, offered in stages, or available in limited quantities, and could be restricted to customers who satisfy certain conditions. You are obligated to adhere to the specific rules when purchasing and utilizing these services. Unless expressly indicated in writing, promotional offers from DATACLOUD are not eligible to be used in conjunction with any other promotions. ## **5. Your Rights and Obligations** 1. Upon successfully ordering services, you have the right to require DATACLOUD to provide services according to this service agreement and as described on relevant pages of the DATACLOUD website, including service descriptions and technical specifications. 2. After subscribing to DATACLOUD"s services, you are entitled to complimentary after-sales support. Additionally, DATACLOUD provides various technical services available for purchase. 3. You are obligated to pay for the services as per the bill reminders received via DATACLOUD"s website prompts or any other means, and in accordance with the provisions of this service agreement. 4. The use of DATACLOUD services shall conform to this Agreement and other rules updated from time to time on the DATACLOUD official website. 5. You are responsible for the integrity and confidentiality of the data stored in DATACLOUD services, as well as the passwords and passphrases used to access and manage various products and services. You shall bear all losses and consequences arising from improper maintenance or confidentiality of the aforementioned data, passwords, and passphrases. 6. Your use of DATACLOUD and your data stored in DATACLOUD products will comply with applicable laws, government regulations, and any other legal requirements, including but not limited to, any data localization or data sovereignty laws, regulations, and any other third-party legal requirements applicable to you. ## **6. DATACLOUD's Rights and Obligations** 1. DATACLOUD shall provide services in accordance with the terms and conditions agreed upon in this Agreement. 2. During the service period, DATACLOUD will provide you with the following after-sales services: * DATACLOUD will offer consulting services through service tickets. Upon receiving a service ticket, DATACLOUD will answer your questions regarding the use of the services within one business day. * DATACLOUD will offer fault support services. You are required to report any issues via an online service ticket. DATACLOUD will swiftly address faults not resulting from your actions, excluding incidents caused by human error, force majeure, or other factors beyond DATA CLOUD"s control. 3. Additionally, you can access other paid after-sales services through DATACLOUD, for which details are available on the relevant pages of the DATACLOUD website. 4. Some services may feature account authorization management, allowing you to grant full or partial operational permissions for the service to one or several designated authorized accounts. In such cases, all actions taken under any authorized account will be regarded as conducted by you through your own account, and you will be responsible for the corresponding obligations and any service fees incurred. 5. DATACLOUD continuously optimizes, enhances, and expands its existing services to offer you a wider variety of service types and functionalities. You fully understand that new or expanded service types and functionalities may require additional fees. Furthermore, DATACLOUD reserves the right to charge for currently free services, adjust service prices up or down, and will announce such adjustments on the DATACLOUD website or notify you directly. The adjusted prices will become effective within the timeframe specified in the announcement or notification, unless otherwise agreed upon by both parties. 6. You fully understand and accept that DATACLOUD offers security protection, management, and monitoring features and services tied to specific services. Despite thorough testing, DATACLOUD cannot assure total compatibility with every software and hardware system, nor guarantee the perfect accuracy of its software and services. In the event of any incompatibilities or software glitches, you are advised to immediately cease using the affected features and swiftly reach out to DATACLOUD for technical assistance. 7. You fully understand and acknowledge that the services provided by DATACLOUD are offered based on the current state of technology and conditions achievable. DATACLOUD will make reasonable efforts and ensure the continuity and security of the services within the scope of its adaptive security capabilities. However, DATACLOUD cannot guarantee that its services will be flawless. Therefore, if there are defects in the services provided by DATACLOUD that are unavoidable given the current level of industry technology, such defects will not be considered a breach of contract by DATACLOUD, nor will DATACLOUD be liable for them. Both parties should cooperate amicably to resolve the issue. 8. You fully understand and acknowledge that DATACLOUD commits to providing services according to the [Service Level Agreement](https://data.cloud/legal/service-level-agreement/). ## **7. User Business Data** 1. DATACLOUD acknowledges and agrees that the data processed, stored, uploaded, downloaded, distributed, or otherwise handled through the services provided by DATACLOUD, constitutes your user business data, and you fully own this data. 2. With respect to user business data, DATACLOUD will not use or disclose it without authorization, except in the following circumstances: * When national authorities lawfully request or access user business data, DATACLOUD is obligated to cooperate according to the relevant laws, regulations, or policy documents and may disclose such data to third parties or administrative and judicial institutions as required; * With mutual agreement between you and DATACLOUD. 3. You are entitled to delete or alter your user business data at your discretion. If you decide to discontinue services or remove data, DATACLOUD will delete your data and cease its retention following your directives. Exercise careful consideration when deleting or modifying data. 4. DATACLOUD offers an AI Copilot feature, leveraging large language models similar to GPT to provide services such as auxiliary programming, data analysis, and problem diagnosis. If you enable this feature, DATACLOUD will only send the involved data metadata (including table descriptions, column names, column types, and column descriptions) to the large language model, which will not access your actual data or database. 5. Upon service term conclusion, early termination (whether mutually agreed or due to other reasons), or in instances of your non-payment, DATACLOUD will maintain your user business data for a predetermined grace period—unless laws, regulations, or specific agreements dictate otherwise. This period is defined in the service terms, product documentation, or descriptions relevant to your subscription. Following this grace period, DATACLOUD will permanently erase all user business data, including any cached or backup copies, ceasing to retain any of your data. 6. Once user business data is deleted, it cannot be recovered. You shall bear the consequences and responsibilities for the deletion of data. You understand and agree that DATACLOUD is under no obligation to continue retaining, exporting, or returning user business data. 7. In accordance with your agreement with DATACLOUD, DATACLOUD stores user business data in the data center you select. DATA CLOUD adheres to its security commitments to users and protects data stored in DATACLOUD data centers in accordance with applicable laws. ## **8. Intellectual Property** 1. The trademark rights, copyrights, or other intellectual property rights held by each party remain individually owned and will not be transferred to the other party or become jointly owned due to the signing or fulfillment of this agreement. 2. Both parties shall respect the intellectual property rights of the other party and third parties. If any third party initiates litigation or claims compensation against one party for infringing on their intellectual property rights or other lawful interests, the responsible party shall independently handle the dispute, compensate the other party for direct economic losses, and indemnify the other party. 3. Intellectual property rights related to this agreement, including but not limited to trademarks, copyrights, patents, etc., are owned by DATACLOUD (except those legally owned by third parties). The purchase or use of products and services does not result in the transfer of any intellectual property rights associated with the products and services. 4. The intellectual property rights of any materials, technologies, software, services, etc., provided by DATACLOUD to you are owned by DATACLOUD (except those legally owned by third parties). You are only entitled to use them in accordance with the terms of this Agreement and shall not in any way infringe upon the intellectual property rights of DATA CLOUD. Without explicit consent from DATACLOUD, you are not authorized to copy, distribute, transfer, license, or make the aforementioned materials, technologies, software, services, and their related intellectual property rights available to others. You shall also not crack the software or systems provided by DATACLOUD, nor engage in reverse engineering, decompilation, disassembly, or any other attempts to discover the source code or circumvent any technical restrictions. ## **9. Confidentiality Clauses** 1. The term "Confidential Information" as mentioned in this Agreement refers to commercial secrets (including financial secrets), technical secrets, business know-how, and/or other information and materials that should be kept confidential (including product information, product plans, pricing, financial and marketing plans, business strategies, customer information, customer data, research and development, software, hardware, API application data interfaces, technical specifications, designs, special formulas, special algorithms, etc.) obtained from the other party, learned of, or generated in the course of fulfilling this Agreement. This applies regardless of the form or medium in which the information and materials are presented, and whether or not the disclosing party has indicated their confidentiality through oral, graphic, written, or other means at the time of disclosure. 2. During the term of this Agreement, both you and DATACLOUD may become aware of each other"s confidential information. Both parties shall take appropriate measures to properly safeguard the confidential information provided by the other party, with a degree of care no less than that which they apply to their own confidential information. The confidential information may only be used for purposes related to this Agreement. Both parties ensure that the confidential information is only known within their respective business heads and employees engaged in the business and strictly limit the employees who have access to the aforementioned confidential information to comply with the confidentiality obligations stipulated in this clause. 3. The confidentiality obligations of both parties shall not be waived by the termination, conclusion, or invalidity of this Agreement. 4. For the purpose of fulfilling this Agreement, the following information shall not be regarded as confidential: * The confidential information was legally owned by the recipient at the time of signing this Agreement or earlier; * The confidential information was public or could be obtained from the public domain at the time it was disclosed to the recipient; * The confidential information was obtained by the recipient from a third party with whom there was no duty of confidentiality or nondisclosure; * The confidential information has become public or could be obtained from the public domain without violating the obligations stipulated in this Agreement; * The confidential information was independently developed by the recipient or its affiliates or subsidiaries without benefiting from the information disclosed by the notifying party or its affiliates or subsidiaries; * The recipient is required to disclose the confidential information by a court or other legal, administrative authorities (through oral questioning, inquiries, document or information requests, subpoenas, civil or criminal investigations, or other procedures); * The recipient discloses the information in order to apply for business qualifications, obtain certain recognitions, or comply with national or industry standards/certifications from administrative departments, industry associations, or other institutions, incorporating information about the other party. In such cases, the recipient shall adhere to the principle of minimal necessary disclosure and require that the institution informed of the confidential information maintains its confidentiality no less strictly than stipulated in this Agreement. 5. Both parties shall exert their utmost efforts to protect the aforementioned confidential information from disclosure. Upon discovery of any leakage of such confidential information, both parties shall cooperate and take all reasonable measures to avoid or mitigate the consequences of the damage. Should such leakage cause loss to the other party, compensation for the direct economic loss incurred shall be provided. ## **10. Amendments and Termination** 1. Pay-as-you-go: Unless otherwise agreed or in cases where other outstanding payments have not been settled, you may use DATA CLOUD"s services upon activating the service. You must ensure that your account balance is sufficient to continuously use the service until a termination scenario stipulated by law or agreed upon in this Agreement occurs. 2. Service Suspension Extension: * For pay-as-you-go users, it"s crucial to keep your account and other payment methods well-funded to ensure uninterrupted service. If your account or payment method falls short, leading to unpaid service fees, DATACLOUD will suspend your pay-as-you-go services. * You have the option to apply for an extension of service without immediate suspension through the service console. DATACLOUD offers a specific amount of credit and/or time extension ("Extension Benefits") for this purpose. During this extension period, you can continue using DATACLOUD services and are expected to pay the service fees at the regular rate. If you haven"t cleared your outstanding service fees by the end of this period, DATACLOUD will suspend your pay-as-you-go services and freeze any related operations in your account. * Your eligibility for Extension Benefits is dynamically evaluated and adjusted by DATACLOUD based on factors such as your spending patterns and creditworthiness, with the status displayed in the service console serving as the definitive guide. * You can either personally turn off the extension credit or have a DATACLOUD staff member end the extension period for you. If you choose to turn off your Extension Benefits, DATACLOUD will suspend the pay-as-you-go services once your account is overdue and the benefits are deactivated. * DATACLOUD will continue to store your data for a designated grace period after service suspension, during which storage fees will still apply. If the outstanding service fees remain unpaid by the end of this grace period, all your data stored on DATACLOUD will be permanently deleted and cannot be recovered. 3. Early Termination: The service term may be terminated early under any of the following circumstances: * Mutual agreement between both parties for early termination; * In the event of your serious breach of this Agreement (including, but not limited to, severe violations of relevant laws and regulations, or severe breaches of any promises made under this Agreement), DATACLOUD reserves the right to terminate the services immediately and delete all your data; * You understand and fully acknowledge that although DATA CLOUD has established (and will continue to improve in line with technological advancements) necessary technical measures to defend against threats to network security, including computer viruses, network intrusions, and attacks (including DDoS), given the limitations, relativity of network security technology, and the unpredictability of such threats, if your website falls victim to such actions causing harm to DATACLOUD or its network or servers (including both local and foreign, as well as international networks and servers) or affects the connectivity between DATACLOUD and the global internet or specific networks, servers, and within DATACLOUD"s internal network, DATACLOUD may decide to suspend or terminate the services. In the event of service termination, fees will be calculated based on the actual months of service provided (with partial months calculated daily), and any remaining funds (if any) will be returned. * DATACLOUD reserves the right to terminate this service agreement by providing a 30-day notice on the DATACLOUD website, through an in-website notification, or via written notice. Upon such termination, DATACLOUD will refund any prepaid amounts that have not been utilized back to your DATACLOUD account. * You understand and agree that due to technological upgrades, service system enhancements, changes in business strategy, or in response to significant technological, regulatory policy changes at the national level, DATA CLOUD does not guarantee the perpetual provision of any particular service. DATACLOUD has the right to alter the form, specifications, or other aspects of the services provided (such as service prices and billing models). DATA CLOUD will make every effort and attempt to notify you in advance of terminating such a service or making such changes, using one or multiple methods such as website announcements, in-site messages, emails, or text messages. ## **11. BREACH OF CONTRACT** 1. IF YOU VIOLATE ANY OF THE PROMISES, WARRANTIES, SERVICE USAGE RULES, OR OBLIGATIONS STIPULATED IN THIS AGREEMENT, OR IF DATA CLOUD, BASED ON ITS JUDGMENT, DEEMS YOUR USE OF THE SERVICES TO BE ABNORMAL, DATACLOUD RESERVES THE RIGHT, DEPENDING ON THE CIRCUMSTANCES AND AT ITS SOLE DISCRETION, TO TAKE ONE OR MORE OF THE FOLLOWING ACTIONS: (1) LIMIT OR SUSPEND THE USE OF SERVICES; (2) TERMINATE THE SERVICES AND THIS AGREEMENT; (3) PURSUE YOUR LEGAL RESPONSIBILITY; (4) OTHER MEASURES DEEMED APPROPRIATE BY DATACLOUD. ANY LOSS TO THE USER RESULTING FROM DATACLOUD’S ACTIONS OF SUSPENDING OR TERMINATING SERVICES BASED ON THE AFOREMENTIONED PROVISIONS SHALL BE BORNE BY YOU. 2. SHOULD YOUR VIOLATION OF RELEVANT LAWS, REGULATIONS, OR THE PROVISIONS OF THIS AGREEMENT OR RELATED RULES RESULT IN ANY LOSS TO DATACLOUD, CLAIMS FROM OTHER USERS, ANY THIRD PARTY, OR PENALTIES FROM ADMINISTRATIVE AUTHORITIES, YOU SHALL FULLY COMPENSATE DATACLOUD, OTHER USERS, OR RELATED THIRD PARTIES FOR THE ACTUAL LOSSES INCURRED, INCLUDING REASONABLE ATTORNEY FEES. 3. YOU UNDERSTAND AND AGREE THAT DUE TO THE SPECIFIC NATURE OF COMPUTERS AND THE INTERNET, THE FOLLOWING SITUATIONS DO NOT CONSTITUTE A BREACH OF CONTRACT BY DATACLOUD: * DATACLOUD NEEDS TO TEMPORARILY INTERRUPT SERVICES FOR SYSTEM AND SERVER CONFIGURATION, MAINTENANCE, OR UPGRADES; * YOUR WEBSITE ACCESS SPEED IS REDUCED DUE TO CONGESTION ON THE INTERNET. 4. IF YOU ARE UNABLE TO USE THE SERVICES NORMALLY FOR A CONTINUOUS 72 HOURS DUE TO REASONS ATTRIBUTABLE TO DATACLOUD, YOU MAY TERMINATE THE SERVICES, EXCEPT FOR REASONS BEYOND DATA CLOUD"S CONTROL. 5. UNDER NO CIRCUMSTANCES SHALL DATACLOUD BE LIABLE FOR ANY INDIRECT, CONSEQUENTIAL, PUNITIVE, INCIDENTAL, OR SPECIAL DAMAGES, INCLUDING ANY LOSS OF PROFITS INCURRED BY USING DATA CLOUD SERVICES (EVEN IF YOU HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH LOSSES). 6. TO THE EXTENT PERMITTED BY LAW, THE TOTAL AMOUNT OF COMPENSATION DATACLOUD IS LIABLE FOR UNDER THIS AGREEMENT AND THE SERVICES PROVIDED TO YOU (WHETHER BASED ON CONTRACT, TORT, OR ANY OTHER THEORY OF LIABILITY) SHALL NOT EXCEED THE TOTAL AMOUNT OF FEES YOU HAVE PAID TO DATACLOUD FOR THE SERVICES; IF THE SERVICE PERIOD YOU USE EXCEEDS 12 MONTHS, DATACLOUD’S MAXIMUM LIABILITY SHALL NOT EXCEED THE TOTAL FEES YOU HAVE ACTUALLY PAID TO DATACLOUD FOR THE SERVICES IN THE 12 MONTHS PRECEDING THE OCCURRENCE OF THE DAMAGE (FOR CLARITY, THIS REFERS TO CASH ACTUALLY PAID FOR THE ACTUAL DURATION/QUANTITY OF SERVICES USED, EXCLUDING PREPAID BUT UNCONSUMED FEES, VOUCHERS, ETC.). ## **12. Notifications** 1. When using DATACLOUD services, you must provide DATACLOUD with true and effective contact information (including your email address, telephone number, contact address, etc.). If there is any change in your contact information, you are obligated to promptly update the relevant information and maintain a reachable status. Your member account for receiving in-site messages and system notifications (including sub-accounts) will also be considered as your valid contact information. 2. DATACLOUD will send various notifications to one or several of the aforementioned contact methods. The content of these notifications may have a significant impact on your rights and obligations, either positively or negatively, so you must ensure to pay close attention to them in a timely manner. 3. DATACLOUD will notify you through the aforementioned contact methods. Written notices sent electronically, including announcements, mobile text messages to your provided contact number, emails to your provided email address, system messages, and in-site messages to your account, will be considered delivered once successfully sent. For written notices sent via paper medium, they will be deemed delivered on the fifth natural day after being posted to the provided contact address. 4. You must ensure that the contact information you provide is accurate and up-to-date. If the contact information provided is incorrect or if you fail to notify of changes to your contact information in a timely manner, resulting in legal documents not being delivered or not delivered on time, you will bear any legal consequences that may arise from this. ## **13. Force Majeure** 1. If the fulfillment of the terms of this service becomes impossible, unnecessary, or meaningless due to force majeure or other unforeseen events, the party affected by the force majeure or unexpected event shall not be held responsible. 2. Force majeure or unexpected events refer to objective events that are unforeseeable, insurmountable, unavoidable, and have a significant impact on one or both parties. This includes natural disasters such as floods, earthquakes, epidemics, and social events like wars, disturbances, governmental actions, interruptions in telecommunication backbone networks, hacking, internet congestion, technical adjustments by telecommunications departments, and government regulations. ## **14. Applicable Law and Dispute Resolution** 1. The establishment, effectiveness, interpretation, amendment, supplementation, termination, enforcement, and dispute resolution of this Agreement shall be governed by the applicable laws; in the absence of relevant legal provisions, commercial practices and/or industry practices shall be referred to. 2. Disputes arising from or related to your use of DATACLOUD services shall be resolved through negotiation between DATA CLOUD and you. Should negotiations fail, either party may bring litigation to the court where this Agreement is signed. ## **15. Miscellaneous** 1. The service descriptions, pricing details on the DATACLOUD website relevant pages, and the product orders you have confirmed and agreed to (including any special terms for products, if any, service descriptions, operational documents, etc.) are all integral parts of this agreement. In case of any inconsistency, the order of application shall be (1) service descriptions, pricing details, and other ordering pages, followed by (2) the general terms and conditions of this agreement. 2. Should the contents of this Agreement change, DATACLOUD shall notify you by announcing the modifications on an appropriate section of the DATACLOUD website 30 days in advance; if you continue to use DATACLOUD services, it will be considered as your acceptance of the relevant modifications made by DATA CLOUD. 3. DATACLOUD reserves the right, upon prior notice, to transfer all or part of the rights and obligations under this Agreement to an affiliate of DATACLOUD. 4. DATACLOUD"s waiver of its rights under this Agreement due to your negligence or breach shall not be considered as a waiver of any other or subsequent similar act of negligence or breach. 5. Nothing contained in this Agreement shall be construed as creating a joint venture, partnership, or employment relationship between you and DATACLOUD. Neither party has any authority to create any obligation on behalf of the other party, whether express or implied, except as otherwise provided in this Agreement or agreed upon by both parties in accordance with the terms of this Agreement. 6. The warranty provisions, confidentiality provisions, intellectual property provisions, applicable law and dispute resolution provisions, and other provisions under this Agreement shall not be invalidated by the termination of this Agreement. 7. BY READING AND CLICKING TO AGREE TO THIS AGREEMENT OR OTHERWISE OPTING TO ACCEPT THIS AGREEMENT, YOU INDICATE THAT YOU HAVE FULLY READ, UNDERSTOOD, AND ACCEPTED ALL THE CONTENTS OF THIS AGREEMENT, AND HAVE REACHED AN AGREEMENT WITH DATA CLOUD. THIS AGREEMENT SHALL BE ESTABLISHED AND TAKE EFFECT WHEN YOU CONFIRM THROUGH A WEB PAGE CLICK OR OPT TO ACCEPT THIS AGREEMENT IN ANY OTHER WAY.