# SurrealDB documentation - Integrate

> AI agents, embedding, integrations, migrating. This is one of the bundles the SurrealDB documentation is split into. The page index at https://surrealdb.com/docs/llms.txt lists every bundle, and https://surrealdb.com/docs/llms-full.txt holds every page. Each page starts with a "Source:" line naming its canonical URL, and every page is also available individually by appending `.md` to its URL. In code examples, a fenced block whose title contains "output" holds the result of the block above it rather than runnable code, and a qualifier such as "Example output" or "Possible output" means the value shown is one of several possible ones. Inside a block, a "//-" comment marks a value the statement above it returned, while "--" is an ordinary comment.

---

Source: https://surrealdb.com/docs/integrate/ai-agents

# AI agents

MCP servers, Agent Skills, and framework integrations for SurrealDB. The ways SurrealDB fits into AI tooling, and what it gives an agent.

SurrealDB connects to AI tooling in three places: the assistant you write code with, the framework your application is built on, and the database your agent stores its knowledge in. This page covers each one and where to go next.

<img src="~/assets/img/diagrams/light/hub-ai-agents-light.webp" darkSrc="~/assets/img/diagrams/hub-ai-agents.webp" alt="Three ways SurrealDB meets AI tooling. The assistant you code with uses MCP tools and Agent Skills. Your application's framework, such as LangChain, LlamaIndex, CrewAI, PydanticAI or Agno, connects through maintained integrations. Agent Memory is a memory and knowledge layer running on SurrealDB, which keeps an agent's memory in a SurrealDB of its own." />

## Ways to integrate

**[MCP](/docs/integrate/ai-agents/mcp.md)** - Give an AI tool a set of tools to call. The hosted [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) connects Claude, Cursor, and other clients to your SurrealDB Cloud account with one URL, so an assistant can deploy instances, query their data, and read logs while you work. A database you run yourself publishes the same data tools through [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md), from SurrealDB 3.1.

**[Agent Skills](/docs/integrate/ai-agents/agent-skills.md)** - Install packaged knowledge into a coding agent. The official skills cover SurrealQL, vector search, and the Python SDK, so generated queries match how SurrealDB actually behaves instead of guessing at an API.

**[AI frameworks](/docs/integrate/integrations/ai-frameworks/overview.md)** - Use SurrealDB from the agent library you already have. LangChain, LlamaIndex, CrewAI, PydanticAI, Agno, and others connect through maintained integrations for vector stores, memory, and retrieval.

**[SurrealDB Agent Memory](/docs/agent-memory.md)** - A memory and knowledge layer for agents, running in front of SurrealDB. Use it when an agent needs to remember across sessions, and to keep straight what was said, what is true now, and what used to be true, without designing that model yourself.

## What the database gives an agent

An agent needs somewhere to keep state, a way to query it that fits the question being asked, and retrieval fast enough to answer in the loop. SurrealDB does all three in one engine, so documents, graph relationships and vector indexes live in one store instead of three that have to be kept in sync.

**Memory** - Store conversation context, artefacts, and entity records as documents, and model the relationships between users, tasks, tools, and outcomes as a graph. Agents can then traverse those connections rather than re-reading everything. Partition memory per tenant or per session while keeping one query model.

**Retrieval** - Combine structured filters with [vector indexes and similarity search](/docs/learn/data-models/vector-search/vector-indexes.md) so a lookup can be semantic, exact, or both. That covers RAG and hybrid retrieval without a second system.

**Knowledge graphs** - Follow links between concepts, permissions, and resources inside the database, so a question can reach supporting facts in a few hops instead of several round-trips through application code.

**Tools the agent can call** - Express logic in SurrealQL, including [database functions](/docs/reference/query-language/functions/database-functions.md) for reusable server-side behaviour and [HTTP functions](/docs/reference/query-language/functions/database-functions/http.md) for reaching external APIs from the query layer.

Because schemas and indexes can change as your workflows change, the same deployment serves low-latency reads for live agents and batch jobs for backfills or evaluation.

## Next steps

- [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) - connect your AI tool to SurrealDB Cloud
- [Agent Skills](/docs/integrate/ai-agents/agent-skills.md) - install SurrealQL and SDK knowledge into a coding agent
- [AI frameworks overview](/docs/integrate/integrations/ai-frameworks/overview.md) - compare the framework integrations
- [Build an AI agent](/docs/learn/tutorials/walkthroughs/build-an-ai-agent.md) - a worked example, end to end

---

Source: https://surrealdb.com/docs/integrate/ai-agents/agent-skills

# Agent Skills

Official SurrealDB agent skills for use in agentic coding workflows.

AI coding agents perform best when they have the right context for the job. Each Agent Skill is a self-contained package of instructions, reference material, and resources that an agent can pick up and apply whenever the task calls for it.

SurrealDB publishes a set of official skills that give your agent deep knowledge of SurrealQL, vector search, the Python SDK, and more. Built on the [Agent Skills](https://agentskills.io/) open standard, they work across all major coding agents including Claude Code, GitHub Copilot, Cursor, Cline, and many others.

## Installation

### Using the Skills CLI

The quickest way to get started is to install every SurrealDB skill in one go:

```bash
npx skills add surrealdb/agent-skills
```

If you only need a subset, pick the ones relevant to your project:

```bash
npx skills add surrealdb/agent-skills --skill surrealql
```

### Manual setup

Alternatively, clone the repository and copy the skills into your agent's context directory:

```bash
git clone https://github.com/surrealdb/agent-skills.git
```

After cloning, move the `skills/` folder to wherever your coding agent looks for context files. Check your agent's documentation for the exact path.

## Available skills

### SurrealQL

A comprehensive reference for the SurrealQL query language, including syntax, schema design, graph traversals, and idiomatic patterns.

```bash
npx skills add surrealdb/agent-skills --skill surrealql
```

> [!NOTE]
> Useful for:
> · Authoring SurrealQL queries
> · Defining and maintaining schemas
> · Navigating graph relationships and working with record IDs
> · Transitioning from traditional SQL to SurrealQL
> · Configuring live queries for real-time data

### SurrealDB Vector

Covers vector search in SurrealDB, including creating HNSW indexes, running KNN queries, and applying similarity scoring.

```bash
npx skills add surrealdb/agent-skills --skill surrealdb-vector
```

> [!NOTE]
> Useful for:
> · Setting up HNSW vector indexes on tables
> · Running KNN queries with distance operators
> · Implementing semantic search, RAG pipelines, or recommendation engines
> · Fine-tuning HNSW parameters (EFC, M, M0, distance function, type)

### SurrealDB Python

Guidance for using the SurrealDB Python SDK in both client/server mode (WebSocket) and embedded mode (in-memory or file-based).

```bash
npx skills add surrealdb/agent-skills --skill surrealdb-python
```

> [!NOTE]
> Useful for:
> · Connecting to SurrealDB from Python applications
> · Working with the `surrealdb` package (synchronous and asynchronous)
> · Running SurrealDB embedded in Python without a separate server
> · Performing CRUD operations from Python code

## Discovering community skills

The [skills.sh directory](https://skills.sh) catalogues skills published by the wider community. You can also search directly from the command line:

```bash
npx skills find QUERY
```

## Further reading

- [SurrealDB Agent Skills](https://github.com/surrealdb/agent-skills)
- [Agent Skills documentation](https://agentskills.io/home)

---

Source: https://surrealdb.com/docs/integrate/ai-agents/mcp

# SurrealDB MCP Server

Connect Claude, Cursor, and other AI tools to SurrealDB Cloud. One URL is all the configuration needs.

The SurrealDB MCP Server connects AI tools to your SurrealDB Cloud account. Add one URL to Claude, Cursor, or any other MCP client, sign in with your Surreal ID, and your assistant can work on your databases alongside you: deploy an instance, query the data inside it, look into why something is slow, and keep track of what it all costs.

```text
https://mcp.surrealdb.com
```

The server is hosted for you, so there is nothing to install and nothing to keep running. It acts as you: it sees only the organisations you belong to, respects the role you hold in each one, and asks you to confirm anything that cannot be undone.

> [!NOTE]
> This page covers the hosted server for SurrealDB Cloud. To give an assistant tools against a database you run yourself, see [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md).

## What is MCP?

[Model Context Protocol](https://modelcontextprotocol.io) is an open standard for connecting AI assistants to outside tools and data. A server publishes a set of tools, and a client such as Claude or Cursor calls them on your behalf. Instead of copying a connection string into a chat window and pasting query results back out, your assistant works with SurrealDB directly.

## What you can do

- **Deploy and manage instances** - create an instance, pause one you are not using, resize it as traffic grows, or upgrade it to a newer version of SurrealDB.
- **Work with your data** - ask a question in plain language and let the assistant write and run the SurrealQL, or have it create tables and seed records while you build.
- **Look into problems** - pull up instance status, metrics, and logs next to the query you were just writing.
- **Manage your team** - invite people to an organisation, change what they can do, and withdraw invitations.
- **Keep an eye on cost** - check usage and invoices, and estimate what an instance will cost before you create it.
- **Give agents long-term memory** - create and manage [SurrealDB Agent Memory](/docs/agent-memory.md) contexts, then store and recall memories from them.

## Connect your AI tool

Most clients need nothing but the URL. Follow the guide for your tool:

- [MCP in Claude](/docs/integrate/ai-agents/mcp/claude.md)
- [MCP in Cursor](/docs/integrate/ai-agents/mcp/cursor.md)

For anything else, add `https://mcp.surrealdb.com` as a remote MCP server. The usual shape is:

```json
{
  "mcpServers": {
    "surrealdb": {
      "url": "https://mcp.surrealdb.com"
    }
  }
}
```

Some clients differ: VS Code uses a `servers` object with `"type": "http"`, and Windsurf and Antigravity use `serverUrl` in place of `url`. Once the server is connected, ask your assistant to list your organisations. If it comes back with them, you are set up.

## Signing in

### With your Surreal ID

If your client supports sign-in, this is all it takes: the client opens a browser window, you sign in with the same Surreal ID you use for SurrealDB Cloud, and you approve the connection. No credentials go into a config file, and you can disconnect from the client whenever you like.

A signed-in connection can use every tool the server offers, limited only by your role in each organisation.

### With a personal access token

Use a token when your client cannot open a browser, or when something runs unattended. Create one in the [account portal](https://account.surrealdb.com/tokens), tick the permissions it should carry, and pass it to your client as a header:

```json
{
  "mcpServers": {
    "surrealdb": {
      "url": "https://mcp.surrealdb.com",
      "headers": {
        "Authorization": "Bearer <your-token>"
      }
    }
  }
}
```

A token carries only the permissions you selected when you created it:

| Permission | Lets your assistant |
| --- | --- |
| `read:cloud` | See your organisations, instances, SurrealDB Agent Memory contexts, usage, and logs |
| `write:cloud-instances` | Deploy, resize, pause, upgrade, and delete instances |
| `query:cloud-instances` | Read and write the data inside your instances |
| `write:cloud-organization` | Create organisations, and manage members, roles, and invitations |
| `write:cloud-billing` | Update billing details and manage SurrealDB Agent Memory plans |
| `write:cloud-spectron` | Create SurrealDB Agent Memory contexts and manage who may use them |
| `query:spectron-contexts` | Store and recall agent memory in a SurrealDB Agent Memory context |

Include `read:cloud` alongside any of the others. Without it your assistant cannot look up which organisation or instance to act on, so the write permissions have nothing to work with.

> [!IMPORTANT]
> A personal access token stands in for your whole account and does not expire on its own. Give it only the permissions the job needs, keep it out of files you commit, and delete it in the account portal when you are finished with it.

## Available tools

You never call the tools by hand. Your assistant picks what it needs, and most clients show you the call before it runs. Read-only tools are marked as safe, so a client can approve them without asking you every time.

| Group | What your assistant can do |
| --- | --- |
| **Profile and organisations** | Check who you are signed in as, list the organisations you can work in, and create or rename one |
| **Members and invitations** | See who has access to an organisation, invite someone, change their role, or withdraw an invitation |
| **Instances** | List instances and their details, deploy a new one, pause, resume, resize, upgrade, adjust backups, or delete |
| **Instance data** | Run SurrealQL and record operations inside a running instance |
| **Monitoring and usage** | Read an instance's status, metrics, logs, and usage |
| **Billing** | Fill in billing details, check whether an organisation can deploy yet, and read usage and invoices |
| **Catalogue** | Look up the regions, instance types, and SurrealDB versions available to you |
| **Terms** | Fetch the SurrealDB Cloud terms and record your acceptance |
| **SurrealDB Agent Memory contexts** | Create and configure memory contexts, and control who may use them |
| **SurrealDB Agent Memory** | Store, search, recall, and reflect on what an agent has learned |

The regions, instance types, and versions are also offered as MCP resources, for clients that prefer them to tool calls. Clients with a prompt menu get a **Deploy a Cloud Instance** wizard, which walks through the choices, prices the result, and waits for your go-ahead.

To see the exact tool surface your client has, ask your assistant which SurrealDB tools it can use.

## Working with your data

The same connection that manages an instance can also query it. Ask a question, and your assistant chooses the namespace and database, writes the SurrealQL, and shows you what came back. [Example usages](/docs/integrate/ai-agents/mcp/examples.md) has prompts to try.

Two things have to be true first. The instance must be running, so resume it if you paused it. And it must be on **SurrealDB 3.1 or later**, the version that began answering these calls. If it is older, ask your assistant to upgrade it.

Inside an instance, these are the tools your assistant works with:

| Tool | What it does |
| --- | --- |
| `use` | Choose the namespace and database to work in |
| `query` | Run SurrealQL |
| `select`, `create`, `insert`, `upsert`, `update`, `delete`, `relate` | Read and change records without writing a full statement |
| `run` | Call a database function |
| `list` | List namespaces, databases, tables, indexes, and users |
| `info` | Describe the schema, or the engine itself |

A database you run yourself publishes the same set. See [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md) for how they behave there.

SurrealDB Agent Memory contexts work the same way. Your assistant can `remember`, `recall`, `context`, `reflect`, `forget`, `upload`, and `inspect` against a context you own, described in the [SurrealDB Agent Memory MCP tools reference](/docs/agent-memory/integrations/mcp-server/tools-reference.md).

## Deploying an instance

Creating an instance costs money, so the server never quietly does it. Your assistant first checks whether the organisation is ready to deploy, and reports anything standing in the way: no free instances left on the plan, billing details missing, or no payment method on file.

Clearing those blockers is a conversation. The assistant asks for the billing contact and address it needs, then hands you a secure checkout link so you can add a card yourself. Card details never pass through the assistant. Once the payment goes through, it can check readiness again and deploy.

Ask for an estimate before it creates anything. The assistant can price a configuration, show you the monthly cost, and wait for you to agree.

## What the server will not do

- **Delete an instance on a guess.** Deletion is permanent and takes the instance's backups with it, so the assistant has to name the instance exactly as it stands right now. A stale or mistaken name is refused.
- **Handle your card.** Payment details are only ever entered by you, on a secure checkout page. No tool accepts a card number.
- **Accept terms for you.** Your assistant can fetch the documents and link you to them; the agreement is yours to give.
- **Show a secret twice.** New SurrealDB Agent Memory keys and access tokens appear once, when they are created. Store them somewhere safe there and then.

Clients often let you auto-approve tools to save clicks. Reserve that for the read-only ones, and keep the confirmation step on anything that changes or removes something.

## Troubleshooting

| What you see | What to do |
| --- | --- |
| Your client says the server needs authentication | Sign in again from the client, or check the personal access token still exists in the [account portal](https://account.surrealdb.com/tokens) |
| A tool reports a missing permission | Your token was created without it. Permissions are fixed once a token exists, so create a new token with that box ticked |
| Sign-in is refused because your email is not verified | Verify the email address on your Surreal ID, then sign in again |
| Your assistant loses the connection after a while | Idle connections are dropped. Reconnect in the client and carry on |
| An instance cannot be queried | It is paused or still starting. Wait until it reports as ready, or ask your assistant to resume it |
| An instance says it needs a newer version | Data tools need SurrealDB 3.1 or later. Ask your assistant to upgrade the instance |
| Your assistant cannot find an organisation you named | It is looking for the organisation's identifier rather than its display name. Ask it to list your organisations first |

## Next steps

- [MCP in Claude](/docs/integrate/ai-agents/mcp/claude.md) - set it up in Claude Code, Claude Desktop, or the Claude app
- [MCP in Cursor](/docs/integrate/ai-agents/mcp/cursor.md) - set it up in Cursor
- [Example usages](/docs/integrate/ai-agents/mcp/examples.md) - prompts that show what the server can do
- [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md) - the MCP server inside SurrealDB, for databases you run yourself
- [Agent Skills](/docs/integrate/ai-agents/agent-skills.md) - teach your assistant SurrealQL and SDK patterns to go with these tools

---

Source: https://surrealdb.com/docs/integrate/ai-agents/mcp/claude

# MCP in Claude

Add the SurrealDB MCP Server to Claude Code, Claude Desktop, or the Claude app.

Claude can reach your SurrealDB Cloud account through the [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md). Setup takes a minute, and you sign in with your Surreal ID in the browser, so there are no credentials to paste.

## Claude Code

Add the server:

```bash
claude mcp add --transport http surrealdb https://mcp.surrealdb.com
```

Run `/mcp` inside Claude Code, choose **surrealdb**, and authenticate. A browser window opens for you to sign in and approve the connection.

Check it worked:

```bash
claude mcp list
```

**surrealdb** should be listed as connected. Ask Claude which SurrealDB organisations it can see, and it should answer with yours.

To connect it for one project rather than everywhere, add `--scope project`. The entry is written to `.mcp.json` in the repository, which you can commit for your team. Everyone still signs in as themselves.

## Claude Desktop and the Claude app

Open **Settings → Connectors → Add custom connector** and fill in:

| Field | Value |
| --- | --- |
| Name | `SurrealDB` |
| URL | `https://mcp.surrealdb.com` |

Claude opens a browser window for you to sign in. Once it closes, start a new conversation and open the tools menu in the composer. The SurrealDB tools appear there.

## Using a personal access token instead

If you would rather not sign in through the browser, or you are running Claude somewhere without one, create a token in the [account portal](https://account.surrealdb.com/tokens) and pass it as a header:

```bash
claude mcp add --transport http surrealdb https://mcp.surrealdb.com \
  --header "Authorization: Bearer <your-token>"
```

Tick only the permissions the work needs. [Signing in](/docs/integrate/ai-agents/mcp.md#signing-in) lists what each one allows.

## Try it

> Show me the SurrealDB instances in my organisation, and tell me which of them are paused.

Claude lists your organisations, picks the one you meant, and reports each instance with its state. [Example usages](/docs/integrate/ai-agents/mcp/examples.md) has more to try, including deploying an instance and querying its data.

## Removing it

```bash
claude mcp remove surrealdb
```

In Claude Desktop and the Claude app, open **Settings → Connectors** and remove the SurrealDB connector.

## Troubleshooting

| What you see | What to do |
| --- | --- |
| `claude mcp list` shows the server as failed | Run `/mcp` and authenticate. Until you sign in, only the sign-in tool works |
| The browser window never opens | Sign in from `/mcp` again, and check nothing is blocking pop-ups |
| Claude cannot see the tools in Claude Desktop | Quit and reopen the app completely, then start a new conversation |
| A tool reports a missing permission | You are using a personal access token created without it. Create a new token with that box ticked |

---

Source: https://surrealdb.com/docs/integrate/ai-agents/mcp/cursor

# MCP in Cursor

Add the SurrealDB MCP Server to Cursor and sign in with your Surreal ID.

With the [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) connected, Cursor's agent can reach your SurrealDB Cloud account while you work: check what is deployed, query a database, and read logs without leaving the editor.

## Add the server

Cursor reads `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` for one project. Add a `surrealdb` entry:

```json
{
  "mcpServers": {
    "surrealdb": {
      "url": "https://mcp.surrealdb.com"
    }
  }
}
```

If the file already lists other servers, add this entry alongside them.

## Sign in

Open **Settings → MCP**, find **surrealdb**, and click **Connect**. Cursor opens a browser window where you sign in with your Surreal ID and approve the connection. The indicator beside the server turns green when it is ready.

Nothing about your account is stored in `mcp.json`, so a project-level file is safe to commit. Everyone who opens the project signs in as themselves.

## Check it worked

In the chat panel, ask:

> Which SurrealDB Cloud organisations can you see?

Cursor should answer with your organisations. To see the whole tool surface, ask which SurrealDB tools it has available.

## Using a personal access token instead

For a machine that cannot open a browser, create a token in the [account portal](https://account.surrealdb.com/tokens) and add it as a header:

```json
{
  "mcpServers": {
    "surrealdb": {
      "url": "https://mcp.surrealdb.com",
      "headers": {
        "Authorization": "Bearer <your-token>"
      }
    }
  }
}
```

Give the token only the permissions you want the agent to have. [Signing in](/docs/integrate/ai-agents/mcp.md#signing-in) lists what each one allows.

> [!WARNING]
> A token in a project-level `.cursor/mcp.json` will be committed with the repository. Keep tokens in the global `~/.cursor/mcp.json` instead.

## Try it

> Create a `task` table in my dev instance with a title and a done flag, insert two rows, then show me the ones that are not done.

Cursor picks the instance, sets the namespace and database, and runs the SurrealQL, showing you each call as it goes. [Example usages](/docs/integrate/ai-agents/mcp/examples.md) has more, including deploying an instance and investigating a slow query.

## Removing it

Delete the `surrealdb` entry from `mcp.json`. Cursor stops offering the tools in new sessions.

## Troubleshooting

| What you see | What to do |
| --- | --- |
| The indicator stays red | Click **Connect** in **Settings → MCP** and complete the sign-in. Check the URL has no trailing path |
| Tools do not appear in chat | Reload the window after editing `mcp.json` |
| The agent asks you to authenticate on every request | Sign in through **Settings → MCP** rather than answering in chat, so Cursor stores the connection |
| A tool reports a missing permission | You are using a personal access token created without it. Create a new token with that box ticked |

---

Source: https://surrealdb.com/docs/integrate/ai-agents/mcp/embedded

# Embedded MCP

Connect AI agents and editors to a SurrealDB server you run yourself, through the built-in MCP server over HTTP or stdio.

_(since v3.1.0)_

SurrealDB ships a built-in [Model Context Protocol](https://modelcontextprotocol.io) server, so agents and editors can list schema, run SurrealQL, and change records through a standard set of tools. The same access control applies as on [`/sql`](/docs/reference/protocols/http-protocol.md#sql) and RPC: `DEFINE USER` permissions, table `PERMISSIONS`, and server capability flags all decide what a tool can do.

This page covers the server inside the SurrealDB binary, for databases you run yourself. For SurrealDB Cloud, the hosted [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) reaches the same data tools remotely and adds organisation, instance, and billing management on top.

Both publish the **same data tools**. What differs is how your editor connects and who shares the database.

## When to use `surreal db mcp` vs `surreal db start`

| | **`surreal db mcp`** (stdio) | **`surreal db start`** + **`/mcp`** (HTTP) |
| --- | --- | --- |
| **How it works** | Your editor spawns SurrealDB as a child process; MCP runs over stdin and stdout | You run a server; the editor connects to `http://…/mcp` |
| **Database** | Embedded in the MCP process (default `memory`, or a local file path) | The same instance your app, CLI, or SurrealDB Studio uses |
| **Authentication** | Owner-level access on every tool call - no login step | Normal SurrealDB auth (Bearer JWT, HTTP Basic, …) |
| **Best for** | Learning MCP, solo local development, quickest editor setup | Shared databases, teams, remote instances, production patterns |
| **Editor config** | `command` and `args` in MCP settings | `url` and auth headers |

The diagram below shows the two arrangements, and the order in which a tool call picks its namespace and database, described in [Selecting a namespace and database per call](#selecting-a-namespace-and-database-per-call).

<img src="~/assets/img/diagrams/light/ops-mcp-topologies-light.webp" darkSrc="~/assets/img/diagrams/ops-mcp-topologies.webp" alt="Two ways to run MCP. With surreal db mcp, the editor spawns the process and talks to it over stdin and stdout; the process holds an embedded datastore, in memory by default or at a local file path, and every tool call runs with an owner-level session, with no login step and no network. With surreal db start, the editor sends HTTP requests to /mcp with a Bearer JWT or HTTP Basic, on the same server that the application, Studio and the CLI use, under that server's users and permissions. A tool call takes its namespace and its database separately from the first of these that is set: its own namespace and database arguments, the surreal-ns and surreal-db request headers, the session's use selection on handshake revisions only, and the server's configured defaults." />

**Use `surreal db mcp`** when you want the lowest-friction path on a machine you trust: paste a config, restart the editor, and experiment. Think of it as a self-contained database for your assistant.

**Use `surreal db start` and `/mcp`** when the agent should work against a database that already exists, or one that other clients share. That is the right model for least-privilege users, TLS, audit logging, and anything beyond trusted solo development.

> [!TIP]
> New to MCP? Start with `surreal db mcp` in your coding assistant, then move to HTTP once you want the agent on the same instance as your application.

## Transports

### HTTP (`/mcp`)

When you run `surreal db start`, the server exposes **`POST /mcp`** on the same bind address as the REST API. Authenticate with the same headers you use elsewhere, for example `Authorization: Bearer <jwt>` or HTTP Basic.

```bash
surreal db start --user root --pass secret --bind 127.0.0.1:8000 memory
# MCP endpoint: http://127.0.0.1:8000/mcp
```

For a non-loopback hostname (a public FQDN, a Kubernetes service name, or a load-balancer host), the transport rejects the request with `403 Forbidden: Host header is not allowed` until you opt in. Set `SURREAL_MCP_ALLOWED_HOSTS` to your hostnames, or `SURREAL_MCP_ALLOW_ALL_HOSTS=true` behind a trusted proxy. See [Configuration](#configuration).

> [!WARNING]
> Run `/mcp` behind TLS in production. The session header acts like a bearer token for the life of the session: anyone who holds it can repeat tool calls as the same user until the session expires, five minutes after the last request by default.

### Stdio (`surreal db mcp`)

For local editor integrations, use the dedicated subcommand. It runs the MCP server in the same process as an embedded datastore:

```bash
surreal db mcp --user root --pass secret --ns main --db main memory
```

Every tool call over stdio runs with owner-level access. There is no network handshake to attach credentials to, so there is nothing to narrow the permissions with. **Do not expose this entry point to untrusted users.**

See [`surreal db mcp`](/docs/reference/cli/db/commands/mcp.md) for its flags and environment variables, including `SURREAL_MCP_NS`, `SURREAL_MCP_DB`, and the shared `SURREAL_MCP_*` limits below.

## Connect an editor

For stdio, the editor launches SurrealDB itself, so the config is a command and its arguments.

**Cursor**

`~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (project):

```json
{
  "mcpServers": {
    "surrealdb": {
      "command": "surreal",
      "args": ["mcp", "--user", "root", "--pass", "secret",
          "--ns", "main", "--db", "main", "memory"]
    }
  }
}
```

Restart Cursor, then check that **Settings → MCP** shows `surrealdb` as connected.

**VS Code**

`.vscode/mcp.json` uses a `servers` object and a `type` field:

```json
{
  "servers": {
    "surrealdb": {
      "type": "stdio",
      "command": "surreal",
      "args": ["mcp", "--user", "root", "--pass", "secret",
          "--ns", "main", "--db", "main", "memory"]
    }
  }
}
```

Reload the window after editing the file, and enable agent mode in your MCP-capable extension.

**Claude Desktop**

`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS, or `%APPDATA%\Claude\claude_desktop_config.json` on Windows:

```json
{
  "mcpServers": {
    "surrealdb": {
      "command": "surreal",
      "args": ["mcp", "--user", "root", "--pass", "secret",
          "--ns", "main", "--db", "main", "memory"]
    }
  }
}
```

Quit and reopen Claude Desktop completely, then start a new conversation.

If the editor cannot find the binary, use the full path from `which surreal` (macOS and Linux) or `where surreal` (Windows) as `command`.

> [!NOTE]
> `--user` and `--pass` create the root user on a **new** datastore, the same as [`surreal db start`](/docs/reference/cli/db/commands/start.md). They do not authenticate each MCP call, because stdio runs every call as owner. Prefer an `env` block (`SURREAL_USER`, `SURREAL_PASS`) over literals in `args` so credentials stay out of committed config. To keep data between sessions, replace `memory` with a [file-backed path](/docs/reference/cli/db/commands/start.md#datastore-configuration) such as `surrealkv://tmp/surreal-mcp`.

For HTTP, point the editor at a server you are already running and attach credentials as headers:

```json
{
  "mcpServers": {
    "surrealdb": {
      "url": "http://127.0.0.1:8000/mcp",
      "headers": {
        "Authorization": "Basic <base64-encoded username:password>"
      }
    }
  }
}
```

Once connected, ask the assistant which SurrealDB tools it has. It should list `query`, `select`, `use`, and the rest of the set below.

## Published tools

`tools/list` publishes these tools, and the names are stable:

| Tool | Purpose |
| --- | --- |
| `query` | Run SurrealQL and return serialised results |
| `gql` | Run an [ISO GQL](/docs/learn/querying/gql/overview.md) query (on by default from 3.3.0; on 3.2.x needs `--allow-experimental gql`) |
| `graphql` | Run a [GraphQL](/docs/learn/querying/graphql/overview.md) query against the configured schema |
| `select`, `create`, `insert`, `upsert`, `update`, `delete`, `relate` | Data manipulation helpers |
| `run` | Call a database function with typed arguments |
| `list` | List namespaces, databases, tables, indexes, users, … |
| `use` | Select the namespace and database context |
| `info` | Schema or engine information for a scope |

Legacy names such as `list_tables`, `use_database`, and `version` are no longer published. Use `list` and `use` instead.

When an agent inspects the schema with `info` or `list`, any [`COMMENT`](/docs/reference/query-language/statements/define/overview.md#comments-on-definitions) on tables and fields is included. Put query-relevant detail in those comments (record-ID conventions, how to compare a field, graph paths) so the agent does not have to guess from names alone.

From SurrealDB 4.0, each tool in `tools/list` also carries an `outputSchema` that describes every result it can return, including an error. A result carries its data in that shape as `structuredContent`, so a client can validate it and read it without parsing the text content.

Each tool also carries annotation hints that clients use to decide what to auto-approve. `gql` is annotated as neither read-only nor safe, because the GQL dialect parses `INSERT`, `SET`, `REMOVE`, and `DELETE` as well as reads.

> [!NOTE]
> Before SurrealDB 3.3.0, `gql` was annotated as read-only and non-destructive, so a client could auto-approve a GQL statement that modified data.

## Protocol versions

_(since v3.3.0)_

The server states which MCP specification revisions it implements rather than inheriting them from the SDK it links against, and it advertises **`2026-07-28`**. An unknown version in a request degrades to that revision.

`2026-07-28` removes the `initialize` handshake and protocol sessions: a request carries its own protocol version, identity, and capabilities, and anything spanning requests must be named on each one. Earlier handshake-based revisions are served on the same endpoint, so clients built against them keep working unchanged.

### Selecting a namespace and database per call

Because a stateless request has no session to hold a selection, every tool except `use` takes optional `namespace` and `database` arguments. Resolution takes the first value it finds, filling each part independently:

1. The tool call's own `namespace` and `database` arguments
2. The `surreal-ns` and `surreal-db` request headers
3. The handshake session's `use` selection, on the revisions that still have one
4. The server's configured defaults

A call may therefore override the database while inheriting the namespace. A request that names its own scope never changes the connection's state, so the override cannot leak into a later call.

`use` stays in `tools/list` under every revision so the tool surface does not vary by protocol version. Under `2026-07-28` it returns an error pointing at the per-call arguments instead of selecting anything.

> [!NOTE]
> The server also identifies itself to clients as `surrealdb`. Before 3.3.0 it reported the name of the MCP SDK crate it was built with.

## Configuration

MCP-specific limits are read once from the environment, with the prefix `SURREAL_MCP_`. HTTP body size uses the server-wide cap.

| Variable | Default | Effect |
| --- | --- | --- |
| `SURREAL_MCP_QUERY_TIMEOUT_SECS` | 60 | Outer timeout on each tool execution (`0` disables) |
| `SURREAL_MCP_MAX_RESULT_BYTES` | 256 KiB | Cap on serialised tool output (`0` disables) |
| `SURREAL_MCP_RUN_MAX_ARGS` | 64 | Maximum arguments to `run` |
| `SURREAL_MCP_PARAMS_MAX_KEYS` | 256 | Maximum top-level keys in parameter objects |
| `SURREAL_MCP_PARAMS_MAX_QL_BYTES` | 4 KiB | Maximum byte length of a `$ql` string inside a `*_data` payload |
| `SURREAL_MCP_SCHEMA_RESOURCE_MAX_TABLES` | 200 | Cap on tables enriched in the database schema resource |
| `SURREAL_MCP_ALLOWED_HOSTS` _(since v3.2.1)_ | loopback only | Exact `Host` values accepted for HTTP `/mcp` (replaces the loopback default) |
| `SURREAL_MCP_ALLOW_ALL_HOSTS` _(since v3.2.1)_ | `false` | Accept any `Host` (trusted-proxy escape hatch; overrides the allowlist) |
| `SURREAL_HTTP_MAX_MCP_BODY_SIZE` | 4 MiB | Maximum HTTP body size for `/mcp` |

Full tables live under [Environment variables](/docs/reference/cli/db/environment-variables.md). [Observability metrics](/docs/operate/observability/metrics.md) include `surrealdb.mcp.*` counters and histograms from 3.1.0.

## Security checklist

- Prefer a least-privilege `DEFINE USER` (for example a custom role with table-level `PERMISSIONS`) over root credentials for agent clients.
- Lock down capabilities (`--deny-funcs`, `--allow-net`, …) so a hijacked session cannot reach `http::*` or other high-risk functions.
- Set `--allow-origin` explicitly for browser-based MCP clients, and avoid `*` in production.
- On a public hostname, set `SURREAL_MCP_ALLOWED_HOSTS`, or `SURREAL_MCP_ALLOW_ALL_HOSTS` only behind a trusted proxy. The default allowlist is loopback-only.
- Forward the `surrealdb::mcp::audit` tracing target to your SIEM. Audit records include the tool name, subject, namespace, database, and outcome, but never query text or row payloads.

## Troubleshooting

| Symptom | Things to check |
| --- | --- |
| The editor shows the server as disconnected | Is `surreal` on your `PATH`? Use the full path as `command`, or run the same command in a terminal to see the error |
| The tools list is empty | Restart the editor after editing MCP config, and confirm the binary is 3.1 or later |
| `403 Forbidden: Host header is not allowed` | HTTP `/mcp` accepts loopback hosts by default. Set `SURREAL_MCP_ALLOWED_HOSTS` to your hostname, or `SURREAL_MCP_ALLOW_ALL_HOSTS=true` behind a trusted proxy. Needs 3.2.1 or later |
| A tool call times out | The default timeout is 60 seconds (`SURREAL_MCP_QUERY_TIMEOUT_SECS`). Narrow the query |
| A result comes back truncated | Output is capped at 256 KiB by default. Paginate or aggregate in SurrealQL |
| Permission errors over HTTP | The user lacks rights for the operation. Sign in with different credentials, or adjust `DEFINE USER` and table `PERMISSIONS` |

## Next steps

- [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) - the hosted server for SurrealDB Cloud instances
- [Example usages](/docs/integrate/ai-agents/mcp/examples.md) - prompts to try once an assistant is connected
- [`surreal db mcp` CLI reference](/docs/reference/cli/db/commands/mcp.md) - flags and environment variables
- [Agent Skills](/docs/integrate/ai-agents/agent-skills.md) - installable SurrealQL and SDK skills for coding agents
- [AI frameworks](/docs/integrate/integrations/ai-frameworks/overview.md) - using SurrealDB from LangChain, CrewAI, and others

---

Source: https://surrealdb.com/docs/integrate/ai-agents/mcp/examples

# Example usages

Prompts that show what an assistant can do with the SurrealDB MCP Server, from deploying an instance to querying its data.

These are prompts to try once you have connected the [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) to your AI tool. Each one explains what the assistant does behind the prompt, so you know what to expect before you ask.

## See what you have

> What SurrealDB instances do I have, and which ones are paused?

The assistant lists your organisations, picks the one you meant or asks which, and reports every instance with its region, size, version, and state. This is a good first prompt, because it confirms the connection is working.

> Which of my instances is on an old version of SurrealDB?

It reads the version of each instance and compares them against the versions available to deploy.

## Deploy an instance

> I need a small instance in Frankfurt for a side project. What would it cost, and can my organisation deploy it?

The assistant looks up the regions and instance types available to you, puts a configuration together, prices it, and checks whether the organisation can deploy at all: free instances left on the plan, billing details filled in, payment method on file. You get the cost and any blockers before anything is created.

> Go ahead and deploy it, and tell me how to connect once it is up.

Only after you say so does it create the instance. It then reports the new instance and how to reach it. If billing is not set up yet, it asks for the contact details it needs and hands you a secure checkout link to add a card yourself.

Clients with a prompt menu also offer a **Deploy a Cloud Instance** wizard, which walks the same path step by step.

## Query and shape your data

> In my dev instance, create a `task` table with a title and a done flag, add a couple of rows, then show me the ones that are not done.

The assistant selects the namespace and database, writes the SurrealQL, and shows you both the statements and the results. The instance has to be running and on SurrealDB 3.1 or later.

> How many orders did we take last week, grouped by status?

It inspects the schema to find the right table and fields, then writes the aggregate query rather than asking you for the shape of your data.

> Something looks wrong with the `customer` table. What does its schema actually say?

It describes the table, its fields, and its indexes, which is often faster than opening a dashboard to check a definition. If you have put operational detail in [`COMMENT`](/docs/reference/query-language/statements/define/overview.md#comments-on-definitions) clauses, that text comes back with the schema and steers the next query.

## Investigate a problem

> My production instance felt slow this morning. Have a look and tell me what you find.

The assistant checks the instance's status, pulls metrics for the window you describe, and reads the logs around it. Because it can also query the database, it can follow a hunch about a missing index in the same conversation.

> Compare CPU and memory over the last day against the same period last week.

It requests both windows and summarises the difference.

## Manage your team

> Invite alex@example.com to the Acme organisation as a developer, and show me who else has access.

It lists the roles the organisation offers, sends the invitation with the role you chose, and reports current members along with any invitations still outstanding.

## Keep costs in check

> What have we spent on SurrealDB this month, and which instance accounts for most of it?

The assistant reads usage for the organisation and for each instance, and pulls up recent invoices.

> Pause anything in the sandbox organisation that nobody has touched this week.

It works out which instances are idle from their usage, tells you what it plans to pause, and waits for you to confirm. Paused instances keep their data.

## Give an agent long-term memory

> Set up a SurrealDB Agent Memory context for this project in Frankfurt, then remember that we settled on event sourcing for the orders service.

The assistant creates the [SurrealDB Agent Memory](/docs/agent-memory.md) context, registers a scope path for the project, and stores the decision in it.

> What do we already know about the orders service?

It recalls what has been stored for that project and answers from it, so a decision made weeks ago still turns up in today's conversation.

## Getting better results

- **Name the instance or organisation** when you have more than one. Otherwise the assistant has to stop and ask.
- **Ask for a plan first** on anything expensive or irreversible: "tell me what you would change, then wait".
- **Let it check before it deploys.** Readiness and cost checks cost nothing, and they stop a deploy failing halfway.
- **Keep approvals on write tools.** Auto-approving read-only tools saves clicks; auto-approving the rest removes the pause that lets you catch a mistake.

## Next steps

- [SurrealDB MCP Server](/docs/integrate/ai-agents/mcp.md) - what each group of tools does, and how signing in works
- [Agent Skills](/docs/integrate/ai-agents/agent-skills.md) - teach your assistant idiomatic SurrealQL to go with these tools
- [Embedded MCP](/docs/integrate/ai-agents/mcp/embedded.md) - the same data tools against a database you run yourself

---

Source: https://surrealdb.com/docs/integrate/embedding

# Embedding SurrealDB

How to embed SurrealDB into your application. Detailed instructions for each supported programming language.

Instead of connecting to a remote server, you can run SurrealDB directly inside your application process. Embedded mode gives you the full query engine with no network overhead, which is useful for local-first applications, edge deployments, and testing.

## Embedding languages

Each language's embedding guide is in its SDK reference:

- [.NET](/docs/reference/dotnet/embedding.md)
- [Go](/docs/reference/golang/embedding.md)
- [Java](/docs/reference/java/concepts/embedded-databases.md)
- [JavaScript](/docs/reference/javascript/concepts/embedded-engines.md)
- [Python](/docs/reference/python/concepts/embedded-databases.md)
- [Rust](/docs/reference/rust/embedding.md)

The [Swift](/docs/reference/swift.md) and [Kotlin](/docs/reference/kotlin.md) SDKs, which cover iOS and Android apps, connect to a SurrealDB server over HTTP or WebSocket, and do not run a database inside the app.

## Browser embedding options

When embedding SurrealDB in web browsers, you have two options:

**SurrealDB 4.x**

- **SurrealKV over OPFS**: SurrealDB can store and persist data within the web browser with SurrealKV, which keeps its files in the browser's Origin Private File System (OPFS). The database has to run in a dedicated web worker, and one database can be open in one tab at a time.

- **SDK**: Alternatively, you can use the SurrealDB SDK to connect to a remote SurrealDB instance instead of storing data in the browser.

Embedding in a browser uses the JavaScript SDK's [WebAssembly engine](/docs/reference/javascript/engines/wasm.md) (`@surrealdb/wasm`). It connects with `mem://` for an in-memory database or `surrealkv://` for persistent storage, and can run inside a Web Worker so that queries do not block the page. A `surrealkv://` database only opens inside a dedicated worker. IndexedDB (`indxdb://`) was removed in SurrealDB 4.0, and a `surrealkv://` database copies the data of an IndexedDB database with the same name when it is first opened. [Embedded engines](/docs/reference/javascript/concepts/embedded-engines.md#running-in-a-web-worker) shows both setups.

**SurrealDB 3.x**

- **IndexedDB**: SurrealDB can be configured to use IndexedDB to store and persist data within the web browser. SurrealDB first serialises both keys and values into a Uint8Array and uses IndexedDB as a binary key-value store. This gives good performance, and all of the functionality that SurrealDB offers when it runs in other ways.

- **SDK**: Alternatively, you can use the SurrealDB SDK to connect to a remote SurrealDB instance instead of using IndexedDB for local persistence.

Embedding in a browser uses the JavaScript SDK's [WebAssembly engine](/docs/reference/javascript/engines/wasm.md) (`@surrealdb/wasm`). It connects with `mem://` for an in-memory database or `indxdb://` for IndexedDB persistence, and can run inside a Web Worker so that queries do not block the page. [Embedded engines](/docs/reference/javascript/concepts/embedded-engines.md#running-in-a-web-worker) shows both setups.

## Storage

- [Storage engines](/docs/integrate/embedding/storage-engines.md) - which engine an embedded database can use, and what each gives up

---

Source: https://surrealdb.com/docs/integrate/embedding/storage-engines

# Storage engines

What a storage engine does for SurrealDB. How to think about choosing one.

SurrealDB sits on top of a storage engine - the component that persists keys and values on disk (or in memory) inside transactions. The query engine speaks SurrealQL; the storage engine decides how durability, concurrency, and replication behave underneath.

Different engines optimise for different deployment shapes. A single embedded process cares about latency and simplicity; a distributed cluster cares about fault tolerance and horizontal capacity. The engine you pick ties your operational playbook to concrete behaviours such as compaction, backup and recovery.

**SurrealDB 4.x**

Typical options you will see in SurrealDB deployments include SurrealKV for on-disk storage, which is the only on-disk engine from SurrealDB 4.0 and suits embedded and local-first workloads where lower resident memory and simpler in-process behaviour are priorities, and SurrealMX (`memory`) for in-process or server in-memory workloads. In a browser, SurrealKV stores its files in the Origin Private File System (OPFS). RocksDB and IndexedDB were removed in SurrealDB 4.0, and SurrealKV converts data from either when it opens it.

**SurrealDB 3.x**

Typical options you will see in SurrealDB deployments include RocksDB for mature local disk storage in write-heavy server workloads, SurrealMX (`memory`) for in-process or server in-memory workloads, and SurrealKV for embedded and local-first workloads where lower resident memory and simpler in-process behaviour are priorities.

In-memory modes are ideal for tests and scratch work, and can also be used in embedded deployments when you enable Redis-like SurrealMX persistence. See [Deployment models](/docs/operate/self-hosted/deployment-models.md) for how engines map to hosting models.

To choose an engine, start from your hosting model (embedded, single server, cluster) and read about [deployment models](/docs/operate/self-hosted/deployment-models.md) together with [architecture](/docs/learn/data-models/architecture.md). Then follow the embedding guides for your language under [embedding SurrealDB](/docs/integrate/embedding.md) for what your SDK supports today - capabilities vary by platform and release.

---

Source: https://surrealdb.com/docs/integrate/integrations

# Integrations

Integrations connecting SurrealDB to AI frameworks and embeddings. Also agents and data tools.

This section collects guides for wiring SurrealDB into the rest of your stack: AI and agent frameworks, embeddings and model providers, data movement (ELT, automation, and similar), and related topics. Each page focuses on a specific tool or pattern so you can find a starting point quickly.

This section assumes a certain level of familiarity with SurrealDB itself. If more general orientation and tutorials are needed first, be sure to start with [What is SurrealDB?](/docs/what-is-surrealdb.md) and the [Querying](/docs/learn/querying.md) section of the docs.

## Backend platforms

- [Encore](/docs/integrate/integrations/backend-platforms/encore.md) - build and verify a complete TypeScript backend for durable AI agent memory using type-safe API, Pub/Sub and cron primitives with SurrealDB vector search and graph relationships

## Agent rules

- [Agent rules](/docs/integrate/integrations/agent-rules.md) - rule files that teach an assistant your project's conventions

## Authentication

- [Better Auth](/docs/integrate/integrations/authentication/better-auth/overview.md) - use SurrealDB as the database behind Better Auth
- [Getting started](/docs/integrate/integrations/authentication/better-auth/getting-started.md) - wire the adapter up and run your first sign-in
- [Plugins](/docs/integrate/integrations/authentication/better-auth/plugins.md) - which Better Auth plugins the adapter supports
- [Transactions & limitations](/docs/integrate/integrations/authentication/better-auth/transactions-and-limitations.md) - what the adapter cannot do yet, and why

## Data management

- [Data management integrations](/docs/integrate/integrations/data-management/overview.md) - the pipeline and testing tools that connect to SurrealDB
- [Airbyte](/docs/integrate/integrations/data-management/airbyte.md) - move data in and out with an Airbyte connector
- [Fivetran](/docs/integrate/integrations/data-management/fivetran.md) - managed pipelines into SurrealDB
- [n8n](/docs/integrate/integrations/data-management/n8n.md) - automate workflows against a database
- [Qyrus](/docs/integrate/integrations/data-management/qyrus.md) - test-data generation

## Editors

- [SurrealQL editor support](/docs/integrate/integrations/editors.md) - highlighting, diagnostics and completion in VS Code and JetBrains, and the language server behind them
- [SurrealQL in CodeMirror](/docs/integrate/integrations/editors/codemirror.md) - embed a SurrealQL editor in a web page

## Embeddings providers

- [Embeddings provider integrations](/docs/integrate/integrations/embeddings-providers/overview.md) - which providers are covered, and what each needs
- [OpenAI](/docs/integrate/integrations/embeddings-providers/openai.md) - embed with OpenAI models
- [Mistral](/docs/integrate/integrations/embeddings-providers/mistral.md) - embed with Mistral models
- [Fastembed](/docs/integrate/integrations/embeddings-providers/fastembed.md) - embed locally, without an API call
- [Python quickstart](/docs/integrate/integrations/embeddings-providers/python-quickstart.md) - end to end from Python
- [Rust quickstart](/docs/integrate/integrations/embeddings-providers/rust-quickstart.md) - end to end from Rust

## Frontend frameworks

- [TanStack DB](/docs/integrate/integrations/frontend-frameworks/tanstack-db.md) - back TanStack DB collections with SurrealDB tables, in pre-release

## Vercel

- [Vercel](/docs/integrate/integrations/vercel.md) - credentials, connection types and schema setup for SurrealDB on Vercel
- [Next.js](/docs/integrate/integrations/vercel/nextjs.md) - query from Server Components, Server Actions and Route Handlers, with live updates in the browser
- [AI SDK](/docs/integrate/integrations/vercel/ai-sdk.md) - vector search and graph tools for models, and chat history in SurrealDB
- [Eve](/docs/integrate/integrations/vercel/eve.md) - tools and a memory provider for eve agents
- [Vercel Sandbox](/docs/integrate/integrations/vercel/vercel-sandbox.md) - run SurrealDB inside a sandbox, or give sandboxed code read-only access

---

Source: https://surrealdb.com/docs/integrate/integrations/agent-rules

# Agent rules

Agent rules for working with SurrealDB.

We've prepared a set of agent rules to help your agents generate better code.

- [SurrealQL](https://github.com/surrealdb/docs.surrealdb.com/blob/main/public/integrations/agent-rules/surrealql.mdc)
- [Vector indexes and queries](https://github.com/surrealdb/docs.surrealdb.com/blob/main/public/integrations/agent-rules/surrealdb-vector.mdc)
- [SurrealDB Python SDK](https://github.com/surrealdb/docs.surrealdb.com/blob/main/public/integrations/agent-rules/surrealdb-python.mdc)
- [SurrealDB running embedded in Python](https://github.com/surrealdb/docs.surrealdb.com/blob/main/public/integrations/agent-rules/surrealdb-python-embedded.mdc)

Place these files in your project directory under `.cursor/rules`. If you are using a different IDE, take a look at the following instructions.

## How to configure agent rules on main IDEs:

- [Cursor rules](https://cursor.com/docs/context/rules)
- [Zed rules](https://zed.dev/docs/ai/overview)
- [OpenCode rules](https://opencode.ai/docs/rules/)

If you are working as a team, consider using the Cursor standard and configure your specific IDE accordingly. For example, for OpenCode you can configure your `opencode.json` like this:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "instructions": [".cursor/rules/*.md"]
}
```

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/agno

# Agno

This section contains information about the Agno framework and how to integrate it with SurrealDB.

[Agno](https://github.com/agno-agi/agno) is a Python framework for building multi-agent systems with shared memory, knowledge and reasoning.

Agno stores an agent's knowledge base in a vector database, and its `SurrealDb` class uses a SurrealDB table with an HNSW index for that. This page shows how to configure it. The tutorial [Build an AI agent with Python](/docs/learn/tutorials/walkthroughs/build-an-ai-agent.md#getting-started-with-agno) has a complete program that loads a PDF of Thai recipes into the knowledge base and asks an agent a question about it.

## Setup

Start a SurrealDB server that accepts the `root` user with the password `secret`, for example with Docker:

```shell
docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass secret
```

## Configure the vector database

Connect with the SurrealDB Python SDK, then pass the client to `SurrealDb`:

```python
from agno.vectordb.surrealdb import SurrealDb
from surrealdb import Surreal

client = Surreal(url="ws://localhost:8000")
client.signin({"username": "root", "password": "secret"})
client.use(namespace="main", database="main")

surrealdb = SurrealDb(
    client=client,
    collection="recipes",  # Table name for storing documents
    efc=150,  # HNSW construction time/accuracy trade-off
    m=12,  # HNSW max number of connections per element
    search_ef=40,  # HNSW search time/accuracy trade-off
)
```

`collection` names the table that holds the documents and their embeddings. `efc` and `m` set the `EFC` and `M` parameters of the HNSW index, and `search_ef` sets the size of the candidate list that a search uses, as in the `<|K,EF|>` [KNN operator](/docs/reference/query-language/language-primitives/operators.md#hnsw). Larger values give more accurate results and make building the index or searching it slower.

## Use it in a knowledge base

Pass the vector database to a knowledge base as its `vector_db`, together with an embedder such as `OpenAIEmbedder()`, and give the knowledge base to an `Agent`. Agno embeds the documents when the knowledge base loads, stores them in the `recipes` table, and searches the table when the agent needs context for a question.

## Developer resources

* View [Cookbook (Sync)](https://docs.agno.com/vectordb/surrealdb)
* View [Cookbook (Async)](https://docs.agno.com/vectordb/surrealdb)
* View [Agno documentation](https://docs.agno.com/vectordb/surrealdb)

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/camel

# CAMEL

This section contains information about the Camel framework and how to integrate it with SurrealDB.

[🐫 CAMEL](https://www.camel-ai.org) is an open-source community dedicated to finding the scaling laws of agents. We believe that studying these agents on a large scale offers valuable insights into their behaviours, capabilities, and potential risks. To facilitate research in this field, we implement and support various types of agents, tasks, prompts, models, and simulated environments.

## Setup

You can run SurrealDB locally or start with a [free SurrealDB Cloud account](/docs/operate/instances.md).

For local, two options:

1. [Install SurrealDB](/docs/running/installation.md) and run [SurrealDB](/docs/running/in-memory.md). Run in-memory with:

    ```sh
    surreal db start -u root -p secret
    ```

2. [Run with Docker](/docs/running/docker.md).

    ```sh
    docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start
    ```

## Example

```python
import os

from camel.storages.vectordb_storages import (
    SurrealStorage,
    VectorDBQuery,
    VectorRecord,
)


def main():
    url = os.getenv("SURREAL_URL", "ws://localhost:8000/rpc")
    table = os.getenv("SURREAL_TABLE", "tb")
    vector_dim = int(os.getenv("SURREAL_VECTOR_DIM", 4))
    namespace = os.getenv("SURREAL_NAMESPACE", "ns")
    database = os.getenv("SURREAL_DATABASE", "db")
    user = os.getenv("SURREAL_USER", "user")
    password = os.getenv("SURREAL_PASSWORD")

    # Raise an error if password is not set
    if not password:
        raise ValueError(
            "Environment variable SURREAL_PASSWORD is not set. "
            "Please set it before running."
        )

    # Initialize the SurrealStorage instance with provided parameters
    storage = SurrealStorage(
        url=url,
        table=table,
        namespace=namespace,
        database=database,
        user=user,
        password=password,
        vector_dim=vector_dim,
    )

    # Clear existing data in storage
    storage.clear()

    # Print the current status after clearing
    print("[Step 1] After clear:", storage.status())

        vec1 = VectorRecord(vector=[1, 2, 3, 4],
        payload={"name": "test_1"})
        vec2 = VectorRecord(vector=[5, 6, 7, 8],
        payload={"name": "test_2"})
        vec3 = VectorRecord(vector=[9, 10, 11, 12],
        payload={"name": "test_3"})
        vec4 = VectorRecord(vector=[13, 14, 15, 16],
        payload={"name": "test_4"})
    storage.add([vec1, vec2, vec3, vec4])
    print("[Step 2] After add:", storage.status())

    res = storage.client.query_raw(
        "SELECT * FROM lyz_tb WHERE payload.name = 'test_3';"
    )["result"][0]["result"][0]["id"].id
    print("[Step 3] Query Result ID for 'test_3':", res)

    storage.delete(ids=[res])
    print("[Step 4] After delete 'test_3':", storage.status())

    res = storage.query(
        VectorDBQuery(query_vector=[1.1, 2.1, 3.1, 4.1], top_k=2)
    )
    print("[Step 5] Vector Query Result:", res)
```

The output should look like this:

```text
[Step 1] After clear: vector_dim=4 vector_count=0oceanbasech
[Step 2] After add: vector_dim=4 vector_count=4
[Step 3] Query Result ID for 'test_3': lov5h16x6uog7l2xtsqp
[Step 4] After delete 'test_3': vector_dim=4 vector_count=3
[Step 5] Vector Query Result:
[VectorDBQueryResult(record=VectorRecord(vector=[],
id='9803ae3a-18da-4152-a522-48e1939a3604',
payload={'name': 'test_2'}), similarity=0.027665393972965968),
VectorDBQueryResult(record=VectorRecord(vector=[],
id='de3d085c-ed1b-4d23-9d12-d9fc64ae1e00',
payload={'name': 'test_1'}), similarity=0.00010404203326297434)]
```

## Resources

* [Camel documentation](https://docs.camel-ai.org/)

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/cocoindex

# CocoIndex

Incremental data pipelines for AI agents with declarative SurrealDB graph and vector targets.

[CocoIndex](https://cocoindex.io) is an incremental indexing framework for AI agents and LLM applications. You declare what should exist in a target store - documents, embeddings, knowledge graphs - and CocoIndex keeps it in sync, reprocessing only the delta on each run.

The SurrealDB connector writes to normal tables, relation (graph edge) tables, and vector indexes. CocoIndex tracks declared records across runs: it upserts changes, skips unchanged records, and removes records that are no longer declared. Related tables in the same database reconcile inside a single atomic transaction.

## How it works

1. **Declare sources** - Walk local files, S3, Google Drive, and other connectors; transform with chunking, embeddings, or LLM extraction.
2. **Declare targets** - Mount SurrealDB `TableTarget` and `RelationTarget` states with optional `TableSchema` (SCHEMAFULL) or schemaless tables.
3. **Reconcile** - On each run, CocoIndex compares the declared state with the previous run and applies upserts and deletions. Schema and vector indexes can be managed automatically when `managed_by` is `"system"`.
4. **Query** - Use SurrealQL for full-text search, graph traversals, and vector similarity on the resulting data. All data can be manually queried at its namespace and database in the same way as with any other SurrealDB instance.

## Key capabilities

- **Incremental sync** - Memoised pipeline steps and target-state reconciliation avoid reprocessing unchanged inputs.
- **Graph-native writes** - Relation tables with polymorphic `from` / `to` endpoints map cleanly to SurrealDB `RELATE` edges.
- **Schema lifecycle** - Optional `TableSchema` with `ColumnDef`; CocoIndex can define fields and drop undeclared columns on re-run.
- **Vector indexes** - Declare HNSW indexes on embedding fields; metric and dimension changes trigger index recreation. Pipelines can embed locally with `SentenceTransformerEmbedder` (Rust uses [FastEmbed](https://crates.io/crates/fastembed) internally) so you can exercise vector targets without requiring an API key.
- **Python and Rust** - Pipelines are typically authored in Python; the Rust SDK exposes the same target-state model for native binaries and examples.

## Local embeddings

CocoIndex pipelines that write vectors to SurrealDB often use `SentenceTransformerEmbedder` - models run on your machine and download once, similar to the zero-key graph demos below. The Rust SDK loads them via FastEmbed; Python uses the `sentence-transformers` library with the same Hugging Face model names. The full [`conversation_to_knowledge`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/conversation_to_knowledge) example uses this for entity resolution.

To sanity-check local embeddings with SurrealDB directly - or to pick a model before you wire up a CocoIndex pipeline - see the [FastEmbed integration guide](/docs/integrate/integrations/embeddings-providers/fastembed.md). It covers ONNX models, vector dimensions, and worked examples in Python and Rust without an API key.

## Podcast → knowledge graph

CocoIndex's flagship SurrealDB example is [`conversation_to_knowledge`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/conversation_to_knowledge), in which podcast episodes become a graph of **sessions**, **statements**, **people**, **technologies**, **organisations**, and **mention** edges.

| Input | What happens |
|-------|----------------|
| `input/*.txt` (YouTube URLs) | **yt-dlp** downloads audio → **AssemblyAI** transcribes with speaker labels → **LLM** extracts claims and entities → entity resolution → SurrealDB graph |
| `input/*.json` (pre-transcribed) | Skips download/transcription; still uses LLM extraction in the full example |

The zero-key demos below use the same interview with musician and YouTuber Rick Beato and Alice in Chains guitarist Jerry Cantrell ([YouTube link](https://www.youtube.com/watch?v=vBlfo0GVqqE)) with a pre-transcribed [`input/sample.json`](#appendix-samplejson). Curated statements stand in for LLM extraction so you can see reconciliation without API keys. CocoIndex does **not** fetch transcripts in these demos.

When connecting with SurrealDB Studio or `surreal db sql`, use the **same namespace and database** your program configures - for example `cocoindex` / `beato_cantrell`, unless you set that explicitly.

## Getting started

Start SurrealDB:

```bash title="Run SurrealDB"
surreal db start --user root --pass secret
```

**Python**

Install CocoIndex with the SurrealDB extra:

```bash title="Install"
pip install "cocoindex[surrealdb]"
```

Copy [`input/sample.json`](#appendix-samplejson) into an `input` directory next to `main.py`. The script mounts `session`, `statement`, `person`, `tech`, and `org` tables plus `session_statement`, `person_session`, `person_statement`, and polymorphic `statement_mentions` relations - the same shape as the full podcast example.

```bash title="Run (twice - second pass reconciles away the Sabbath branch)"
export COCOINDEX_DB=/tmp/cocoindex_beato
export SURREALDB_URL=ws://127.0.0.1:8000/rpc
export SURREALDB_NS=cocoindex
export SURREALDB_DB=beato_cantrell
INCLUDE_SABBATH=1 python main.py
INCLUDE_SABBATH=0 python main.py
```

`COCOINDEX_DB` stores CocoIndex's local change-tracking state between runs. `INCLUDE_SABBATH=1` declares the Tony Iommi / Black Sabbath influence branch; setting it to `0` on the second run removes those nodes and edges.

```python title="main.py"
"""Rick Beato × Jerry Cantrell → SurrealDB knowledge graph (no API keys)."""
from __future__ import annotations

import asyncio
import json
import os
from collections.abc import AsyncIterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import cocoindex as coco
from cocoindex.connectors import surrealdb

SURREAL_DB = coco.ContextKey[surrealdb.ConnectionFactory]("surreal_db")
SESSION_ID = 100
INCLUDE_SABBATH = os.environ.get("INCLUDE_SABBATH", "1") != "0"


@dataclass
class Session:
    id: int
    youtube_id: str
    name: str
    transcript: str
    description: str | None = None
    date: str | None = None


@dataclass
class Statement:
    id: int
    statement: str


@dataclass
class Entity:
    id: str
    name: str


def statement_seeds(include_sabbath: bool) -> list[dict[str, Any]]:
    seeds = [
        {
            "id": 200,
            "text": "Songwriting begins with collecting riffs; most Alice in Chains songs start from a riff idea curated over time.",
            "speakers": ["Jerry Cantrell"],
            "persons": ["Jerry Cantrell"],
            "techs": ["Riffs", "Songwriting"],
            "orgs": ["Alice in Chains"],
        },
        # ...talk box, Seattle scene, and recording-vibe statements...
    ]
    if include_sabbath:
        seeds.append(
            {
                "id": 204,
                "text": "Tony Iommi and Black Sabbath were foundational guitar influences; Dave Jerden helped expand Alice in Chains' studio sound.",
                "speakers": ["Jerry Cantrell"],
                "persons": ["Jerry Cantrell", "Tony Iommi", "Dave Jerden"],
                "techs": ["Guitar tone"],
                "orgs": ["Black Sabbath", "Alice in Chains"],
            }
        )
    return seeds


@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    builder.provide(
        SURREAL_DB,
        surrealdb.ConnectionFactory(
            url=os.environ.get("SURREALDB_URL", "ws://127.0.0.1:8000/rpc"),
            namespace=os.environ.get("SURREALDB_NS", "cocoindex"),
            database=os.environ.get("SURREALDB_DB", "beato_cantrell"),
            credentials={
                "username": os.environ.get("SURREALDB_USER", "root"),
                "password": os.environ.get("SURREALDB_PASS", "secret"),
            },
        ),
    )
    yield


@coco.fn(memo=True)
async def declare_graph() -> None:
    session_data = json.loads(Path("input/sample.json").read_text())
    transcript = "\n".join(
        f"({u['speaker']}) {u['text']}" for u in session_data["utterances"]
    )
    seeds = statement_seeds(INCLUDE_SABBATH)

    session_table = await surrealdb.mount_table_target(
        SURREAL_DB, "session", await surrealdb.TableSchema.from_class(Session)
    )
    statement_table = await surrealdb.mount_table_target(
        SURREAL_DB, "statement", await surrealdb.TableSchema.from_class(Statement)
    )
    entity_schema = await surrealdb.TableSchema.from_class(Entity)
    person_table = await surrealdb.mount_table_target(SURREAL_DB, "person", entity_schema)
    tech_table = await surrealdb.mount_table_target(SURREAL_DB, "tech", entity_schema)
    org_table = await surrealdb.mount_table_target(SURREAL_DB, "org", entity_schema)

    session_statement = await surrealdb.mount_relation_target(
        SURREAL_DB, "session_statement", session_table, statement_table
    )
    person_session = await surrealdb.mount_relation_target(
        SURREAL_DB, "person_session", person_table, session_table
    )
    person_statement = await surrealdb.mount_relation_target(
        SURREAL_DB, "person_statement", person_table, statement_table
    )
    statement_mentions = await surrealdb.mount_relation_target(
        SURREAL_DB,
        "statement_mentions",
        statement_table,
        [person_table, tech_table, org_table],
    )

    session_table.declare_record(
        row=Session(
            id=SESSION_ID,
            youtube_id=session_data["id"],
            name=session_data["title"],
            description=session_data.get("description"),
            transcript=transcript,
            date=session_data.get("date"),
        )
    )

    people: set[str] = {"Rick Beato", "Jerry Cantrell"}
    techs: set[str] = set()
    orgs: set[str] = set()

    for seed in seeds:
        statement_table.declare_record(
            row=Statement(id=seed["id"], statement=seed["text"])
        )
        session_statement.declare_relation(from_id=SESSION_ID, to_id=seed["id"])
        for speaker in seed["speakers"]:
            people.add(speaker)
            person_statement.declare_relation(from_id=speaker, to_id=seed["id"])
        people.update(seed["persons"])
        techs.update(seed["techs"])
        orgs.update(seed["orgs"])
        for person in seed["persons"]:
            statement_mentions.declare_relation(
                from_id=seed["id"], to_id=person, to_table=person_table
            )
        for tech in seed["techs"]:
            statement_mentions.declare_relation(
                from_id=seed["id"], to_id=tech, to_table=tech_table
            )
        for org in seed["orgs"]:
            statement_mentions.declare_relation(
                from_id=seed["id"], to_id=org, to_table=org_table
            )

    for name in people:
        person_table.declare_record(row=Entity(id=name, name=name))
        person_session.declare_relation(from_id=name, to_id=SESSION_ID)
    for name in techs:
        tech_table.declare_record(row=Entity(id=name, name=name))
    for name in orgs:
        org_table.declare_record(row=Entity(id=name, name=name))


app = coco.App(coco.AppConfig(name="beato_cantrell_demo"), declare_graph)

if __name__ == "__main__":
    asyncio.run(app.update())
```

For LLM extraction, entity resolution, and live YouTube ingestion, follow CocoIndex's [podcast-to-knowledge-graph tutorial](https://cocoindex.io/docs/examples/podcast-to-knowledge-graph/) and the [`conversation_to_knowledge`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/conversation_to_knowledge) source. The [SurrealDB connector reference](https://cocoindex.io/docs/connectors/surrealdb) covers connection setup, `TableSchema.from_class`, vector indexes, and relation tables in full. For local embedding models, see [FastEmbed](/docs/integrate/integrations/embeddings-providers/fastembed.md).

**Rust**

The Rust SDK is not yet published on [crates.io](https://crates.io); use a path or git dependency on the [CocoIndex repository](https://github.com/cocoindex-io/cocoindex) (`rust/sdk/cocoindex`, feature `surrealdb`).

Copy [`input/sample.json`](#appendix-samplejson) into an `input` directory next to your Rust project and depend on the local SDK:

```toml title="Cargo.toml"
[dependencies]
cocoindex = { path = "../cocoindex/rust/sdk/cocoindex", features = ["surrealdb"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
```

```bash title="Run"
export SURREALDB_URL=127.0.0.1:8000
export SURREALDB_NS=cocoindex
export SURREALDB_DB=beato_cantrell
cargo run
```

The program runs twice in one invocation - the second pass drops the Tony Iommi / Black Sabbath branch to show reconciliation. It mounts the same tables and relations as the Python example above.

For LLM extraction, entity resolution, and live YouTube ingestion, use the full [`conversation_to_knowledge` Rust example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/conversation_to_knowledge) (`ASSEMBLYAI_API_KEY`, `OPENAI_API_KEY`, `yt-dlp`). For vector indexes and schema evolution tests, see the [SDK SurrealDB tests](https://github.com/cocoindex-io/cocoindex/blob/main/rust/sdk/cocoindex/tests/surrealdb_target.rs). For local embedding models outside CocoIndex, see [FastEmbed](/docs/integrate/integrations/embeddings-providers/fastembed.md).

Code:

```rust
//! Rick Beato × Jerry Cantrell → SurrealDB knowledge graph (no API keys).
//!
//! Loads a pre-transcribed interview JSON (`input/sample.json`, sourced from
//! YouTube captions for https://www.youtube.com/watch?v=vBlfo0GVqqE) and
//! declares sessions, statements, people, gear/techniques, bands, and mention
//! edges. Curated claims stand in for LLM extraction in the full CocoIndex pipeline.

use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::LazyLock;

use cocoindex::prelude::*;
use cocoindex::surrealdb::{self, ColumnDef, Graph, TableSchema};
use serde::Deserialize;

static GRAPH: LazyLock<ContextKey<Graph>> = LazyLock::new(|| ContextKey::new("main_db"));

const PERSON: &str = "person";
const TECH: &str = "tech";
const ORG: &str = "org";

const SESSION_ID: i64 = 100;
const STMT_RIFFS: i64 = 200;
const STMT_TALKBOX: i64 = 201;
const STMT_SEATTLE: i64 = 202;
const STMT_VIBE: i64 = 203;
const STMT_SABBATH: i64 = 204;

#[derive(Debug, Clone, Deserialize)]
struct LocalInput {
    id: String,
    title: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    date: Option<String>,
    utterances: Vec<Utterance>,
}

#[derive(Debug, Clone, Deserialize)]
struct Utterance {
    speaker: String,
    text: String,
}

/// Curated claims - in the full CocoIndex pipeline an LLM extracts these from the transcript.
struct StatementSeed {
    id: i64,
    text: &'static str,
    speakers: &'static [&'static str],
    persons: &'static [&'static str],
    techs: &'static [&'static str],
    orgs: &'static [&'static str],
}

fn statement_seeds(include_sabbath_branch: bool) -> Vec<StatementSeed> {
    let mut seeds = vec![
        StatementSeed {
            id: STMT_RIFFS,
            text: "Songwriting begins with collecting riffs; most Alice in Chains songs start from a riff idea curated over time.",
            speakers: &["Jerry Cantrell"],
            persons: &["Jerry Cantrell"],
            techs: &["Riffs", "Songwriting"],
            orgs: &["Alice in Chains"],
        },
        StatementSeed {
            id: STMT_TALKBOX,
            text: "The I Want Blood sessions leaned on talk box tones, including a Heil talk box and a Jeff Beck-style bag talk box.",
            speakers: &["Jerry Cantrell"],
            persons: &["Jerry Cantrell", "Jeff Beck"],
            techs: &["Talk box", "Heil talk box", "Guitar layering"],
            orgs: &[],
        },
        StatementSeed {
            id: STMT_SEATTLE,
            text: "The early Seattle scene had real camaraderie between bands, and Alice in Chains rarely stockpiled unused songs.",
            speakers: &["Jerry Cantrell"],
            persons: &["Jerry Cantrell"],
            techs: &[],
            orgs: &["Alice in Chains", "Seattle grunge scene"],
        },
        StatementSeed {
            id: STMT_VIBE,
            text: "Recording is about catching the vibe, not perfection - rock and roll finds the audience it is meant to reach.",
            speakers: &["Jerry Cantrell"],
            persons: &["Jerry Cantrell"],
            techs: &["I Want Blood"],
            orgs: &[],
        },
    ];
    if include_sabbath_branch {
        seeds.push(StatementSeed {
            id: STMT_SABBATH,
            text: "Tony Iommi and Black Sabbath were foundational guitar influences; Dave Jerden helped expand Alice in Chains' studio sound.",
            speakers: &["Jerry Cantrell"],
            persons: &["Jerry Cantrell", "Tony Iommi", "Dave Jerden"],
            techs: &["Guitar tone"],
            orgs: &["Black Sabbath", "Alice in Chains"],
        });
    }
    seeds
}

fn load_session() -> Result<LocalInput> {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("input/sample.json");
    let raw = std::fs::read_to_string(&path)
        .map_err(|e| Error::engine(format!("read {}: {e}", path.display())))?;
    serde_json::from_str(&raw).map_err(|e| Error::engine(format!("parse sample.json: {e}")))
}

fn transcript_text(session: &LocalInput) -> String {
    session
        .utterances
        .iter()
        .map(|u| format!("({}) {}", u.speaker, u.text))
        .collect::<Vec<_>>()
        .join("\n")
}

async fn build_graph(app: &App, session: &LocalInput, include_sabbath_branch: bool) -> Result<()> {
    let seeds = statement_seeds(include_sabbath_branch);
    let transcript = transcript_text(session);
    let session = session.clone();

    let stats = app
        .run(move |ctx| {
            let seeds = seeds;
            let session = session;
            let transcript = transcript;
            async move {
                let session_target = surrealdb::mount_table_target_with_schema(
                    &ctx,
                    &GRAPH,
                    "session",
                    Some(TableSchema::new([
                        ("youtube_id", ColumnDef::new("string")),
                        ("name", ColumnDef::new("string")),
                        ("description", ColumnDef::new("string").nullable()),
                        ("transcript", ColumnDef::new("string")),
                        ("date", ColumnDef::new("string").nullable()),
                    ])?),
                )
                .await?;
                let statement_target = surrealdb::mount_table_target_with_schema(
                    &ctx,
                    &GRAPH,
                    "statement",
                    Some(TableSchema::new([("statement", ColumnDef::new("string"))])?),
                )
                .await?;
                let entity_schema = TableSchema::new([("name", ColumnDef::new("string"))])?;
                let person_target = surrealdb::mount_table_target_with_schema(
                    &ctx,
                    &GRAPH,
                    PERSON,
                    Some(entity_schema.clone()),
                )
                .await?;
                let tech_target = surrealdb::mount_table_target_with_schema(
                    &ctx,
                    &GRAPH,
                    TECH,
                    Some(entity_schema.clone()),
                )
                .await?;
                let org_target = surrealdb::mount_table_target_with_schema(
                    &ctx,
                    &GRAPH,
                    ORG,
                    Some(entity_schema),
                )
                .await?;

                let session_statement = surrealdb::mount_relation_target(
                    &ctx,
                    &GRAPH,
                    "session_statement",
                    &session_target,
                    &statement_target,
                )
                .await?;
                let person_session = surrealdb::mount_relation_target(
                    &ctx,
                    &GRAPH,
                    "person_session",
                    &person_target,
                    &session_target,
                )
                .await?;
                let person_statement = surrealdb::mount_relation_target(
                    &ctx,
                    &GRAPH,
                    "person_statement",
                    &person_target,
                    &statement_target,
                )
                .await?;
                let statement_mentions = surrealdb::mount_relation_target_many(
                    &ctx,
                    &GRAPH,
                    "statement_mentions",
                    &[&statement_target],
                    &[&person_target, &tech_target, &org_target],
                    None,
                )
                .await?;

                session_target.declare_record(
                    &ctx,
                    SESSION_ID,
                    &serde_json::json!({
                        "youtube_id": session.id,
                        "name": session.title,
                        "description": session.description,
                        "transcript": transcript,
                        "date": session.date,
                    }),
                )?;

                let mut people: HashSet<&str> = HashSet::from(["Rick Beato", "Jerry Cantrell"]);
                let mut techs: HashSet<&str> = HashSet::new();
                let mut orgs: HashSet<&str> = HashSet::new();

                for seed in &seeds {
                    statement_target.declare_record(
                        &ctx,
                        seed.id,
                        &serde_json::json!({ "statement": seed.text }),
                    )?;
                    session_statement.declare_relation(&ctx, SESSION_ID, seed.id)?;

                    for speaker in seed.speakers {
                        people.insert(speaker);
                        person_statement.declare_relation(&ctx, *speaker, seed.id)?;
                    }
                    for person in seed.persons {
                        people.insert(person);
                    }
                    for tech in seed.techs {
                        techs.insert(tech);
                    }
                    for org in seed.orgs {
                        orgs.insert(org);
                    }
                    for person in seed.persons {
                        statement_mentions.declare_relation_between(
                            &ctx,
                            "statement",
                            seed.id,
                            PERSON,
                            *person,
                        )?;
                    }
                    for tech in seed.techs {
                        statement_mentions.declare_relation_between(
                            &ctx,
                            "statement",
                            seed.id,
                            TECH,
                            *tech,
                        )?;
                    }
                    for org in seed.orgs {
                        statement_mentions.declare_relation_between(
                            &ctx,
                            "statement",
                            seed.id,
                            ORG,
                            *org,
                        )?;
                    }
                }

                for name in people {
                    person_target.declare_record(
                        &ctx,
                        name,
                        &serde_json::json!({ "name": name }),
                    )?;
                    person_session.declare_relation(&ctx, name, SESSION_ID)?;
                }
                for name in techs {
                    tech_target.declare_record(&ctx, name, &serde_json::json!({ "name": name }))?;
                }
                for name in orgs {
                    org_target.declare_record(&ctx, name, &serde_json::json!({ "name": name }))?;
                }

                Ok(())
            }
        })
        .await?;

    println!("  {stats}");
    Ok(())
}

async fn print_counts(graph: &Graph) -> Result<()> {
    println!(
        "  session: {}, statement: {}, person: {}, tech: {}, org: {}, mentions: {}",
        graph.count("session").await?,
        graph.count("statement").await?,
        graph.count(PERSON).await?,
        graph.count(TECH).await?,
        graph.count(ORG).await?,
        graph.count("statement_mentions").await?,
    );
    Ok(())
}

fn env_or(key: &str, default: &str) -> String {
    std::env::var(key).unwrap_or_else(|_| default.to_string())
}

fn print_query_hints() {
    println!("\nInspect in SurrealDB Studio (or surreal db sql with `surreal db sql --user root --pass secret --ns cocoindex --db beato_cantrell`):");
    println!("  namespace: cocoindex");
    println!("  database:  beato_cantrell");
    println!("\nExample queries:");
    println!("  SELECT name FROM person;");
    println!("  SELECT statement FROM statement WHERE statement CONTAINS 'riff';");
    println!("  SELECT statement FROM statement WHERE statement CONTAINS 'talk box';");
    println!(
        "  SELECT id, ->statement_mentions->org.name AS bands FROM statement WHERE ->statement_mentions->org;"
    );
}

#[tokio::main]
async fn main() -> Result<()> {
    let session = load_session()?;
    println!(
        "Loaded transcript: {} ({} utterances)\n",
        session.title,
        session.utterances.len()
    );

    let graph = Graph::connect(
        &env_or("SURREALDB_URL", "127.0.0.1:8000"),
        &env_or("SURREALDB_NS", "cocoindex"),
        &env_or("SURREALDB_DB", "beato_cantrell"),
        &env_or("SURREALDB_USER", "root"),
        &env_or("SURREALDB_PASS", "secret"),
    )
    .await?;

    let dir = tempfile::tempdir()?;
    let app = Environment::builder()
        .db_path(dir.path().join("cocoindex_lmdb"))
        .provide_key(&GRAPH, graph.clone())
        .build()
        .await?
        .app("beato_cantrell_demo")
        .await?;

    println!("Run 1 - full graph (includes Tony Iommi / Black Sabbath branch)");
    build_graph(&app, &session, true).await?;
    print_counts(&graph).await?;

    println!("\nRun 2 - narrower extraction (Sabbath influence branch reconciled away)");
    build_graph(&app, &session, false).await?;
    print_counts(&graph).await?;

    print_query_hints();
    Ok(())
}
```

## Inspect the graph

After either demo completes, open SurrealDB Studio with namespace **cocoindex** and database **beato_cantrell**. The schema designer shows the session-centric graph CocoIndex declared:

![SurrealDB Studio schema designer showing session, statement, person, tech, and org tables with session_statement, person_session, person_statement, and statement_mentions relation tables after the Beato - Cantrell demo.](~/assets/img/integrations/cocoindex_schema.png)

Example queries:

```surql title="Example queries"
SELECT name FROM person;
SELECT statement FROM statement WHERE statement CONTAINS 'riff';
SELECT statement FROM statement WHERE statement CONTAINS 'talk box';
SELECT ->statement_mentions->org.name AS bands FROM statement
    WHERE statement CONTAINS 'Alice';
```

After the second run (`INCLUDE_SABBATH=0` in Python, or the built-in second pass in Rust), the Tony Iommi / Black Sabbath statement and its mention edges are gone - reconciliation removed anything no longer declared.

## Appendix: sample.json

Create an `input` directory next to your demo program and save the following as `input/sample.json`. Utterance excerpts were polished from YouTube auto-captions for the [Rick Beato × Jerry Cantrell interview](https://www.youtube.com/watch?v=vBlfo0GVqqE).

<details>
<summary>Show <code>input/sample.json</code></summary>

```json title="input/sample.json"
{
  "id": "vBlfo0GVqqE",
  "title": "Jerry Cantrell: Creating the Iconic Sound of Alice In Chains",
  "channel": "Rick Beato",
  "description": "Rick Beato interviews Jerry Cantrell about Alice in Chains, songwriting, guitar tones, the Seattle scene, and the solo album I Want Blood.",
  "date": "2024-09-17",
  "utterances": [
    {
      "speaker": "A",
      "text": "Jerry, welcome. I'm listening to your new solo record and it has all these great riffs. Do you just sit around and put ideas on your phone? How do you keep track of everything?"
    },
    {
      "speaker": "B",
      "text": "I'm probably a collector and curator of riffs. It always starts there. Sometimes I'll hum something into a phone, but most songs begin when I stumble across a riff and think, that's cool."
    },
    {
      "speaker": "A",
      "text": "Walk me through how a riff becomes an Alice in Chains song."
    },
    {
      "speaker": "B",
      "text": "The music always comes first to me. It begins with the riff and then it develops into what I think is a piece of music that makes a great song."
    },
    {
      "speaker": "B",
      "text": "We leaned heavily on the talk box on this record - the Heil talk box and some older flavors I had not hit that hard in a while, plus a Jeff Beck-style bag talk box I had never played before."
    },
    {
      "speaker": "A",
      "text": "Let's talk about the Seattle scene when Dirt and Jar of Flies were happening."
    },
    {
      "speaker": "B",
      "text": "Seattle at that time had a real camaraderie between bands. We were all pushing each other, but Alice in Chains always put out what we wrote - no pile of unused B-sides sitting around."
    },
    {
      "speaker": "A",
      "text": "Your new solo album is called I Want Blood. How is that different from a band record?"
    },
    {
      "speaker": "B",
      "text": "It's a collaborative thing whether I'm in the band or on a solo record. There's a whole group of people and a producer - it's still a band effort, just with my name on the cover."
    },
    {
      "speaker": "B",
      "text": "It's not about perfection, it's about catching the vibe. Rock and roll is not supposed to be for everybody - it finds the people it is meant to speak to."
    },
    {
      "speaker": "A",
      "text": "Who were the guitar influences that shaped your sound?"
    },
    {
      "speaker": "B",
      "text": "Tony Iommi and Black Sabbath were huge for me early on - that dark, heavy feel. Jimmy Page too, and the way producers like Dave Jerden helped expand what we could do in the studio."
    }
  ]
}
```

</details>

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/crewai

# CrewAI

How to plug SurrealDB into CrewAI as a memory and vector-search layer.

[CrewAI](https://github.com/joaomdmoura/crewAI) lets you orchestrate role-playing AI agents that collaborate to complete complex tasks.
This guide shows how to use SurrealDB as the memory backend for CrewAI, giving agents:

- **Entity memory** for domain objects (products, people, places)
- **Short-term memory** for recent conversations
- **Vector search** to recall relevant information by semantic similarity

The sample below creates two agents that recommend music festival trips:

1. **Researcher** - finds festivals and saves them to SurrealDB
2. **Planner** - queries those saved festivals to build a weekend itinerary

## Install

```bash
# CrewAI, SurrealDB Python SDK, and an embedder (OpenAI here; swap if you like)
pip install "crewai[tools]" surrealdb openai

# (optional) run SurrealDB locally - single binary, no deps
docker run --pull always -p 8000:8000 surrealdb/surrealdb:latest \
       start --user root --pass secret file:/data/db
````

SurrealDB v2 ships native HNSW indexes, so you get ANN vector search without an extra service.

## SurrealDB storage adapter

Create `src/mycrew/surreal_storage.py`:

```python
from __future__ import annotations

import asyncio, hashlib, logging, os, threading
from typing import Any, Dict, List, Optional

import openai
from crewai.memory.storage.rag_storage import RAGStorage
from surrealdb import Surreal, AsyncSurreal

logger = logging.getLogger(__name__)
_EMBED_DIM = 1536  # OpenAI text-embedding-3-small


# ────────────────────────── embeddings ──────────────────────────
def _embed(text: str,
           api_key: Optional[str] = None,
           model: str = "text-embedding-3-small",
           dimensions: int = _EMBED_DIM) -> List[float]:
    """Return an L2-normalised embedding vector."""
    resp = openai.Embedding.create(
        model=model,
        input=[text],
        api_key=api_key or os.getenv("OPENAI_API_KEY"),
        dimensions=dimensions,
    )
    vec = resp["data"][0]["embedding"]
    norm = sum(x * x for x in vec) ** 0.5 or 1.0
    return [x / norm for x in vec]


# ─────────────────────────── storage ────────────────────────────
class SurrealStorage(RAGStorage):
    """CrewAI RAGStorage backend backed by SurrealDB v2."""

    _lock = threading.Lock()
    _tables_ready: set[str] = set()

    def __init__(
        self,
        typ: str,
        *,
        allow_reset: bool = True,
        embedder_config: Optional[Dict[str, Any]] = None,
        crew: Optional[Any] = None,
        url: str = "ws://localhost:8000/rpc",
        namespace: str = "crew",
        database: str = "memories",
        user: str = "root",
        password: str = "secret",
    ):
        super().__init__(typ, allow_reset, embedder_config, crew)
        self.url, self.ns, self.db = url, namespace, database
        self.user, self.pw = user, password
        self.table = f"mem_{typ.replace('-', '_')}"
        self._adb = AsyncSurreal(url)   # async client
        self._sdb = Surreal(url)        # sync client (DDL)
        self._embed_api_key = (embedder_config or {}).get("api_key")

    # ─────────── helpers ───────────
    def _run(self, coro):
        """Run *coro* in any context (sync script or async crew)."""
        try:
            loop = asyncio.get_running_loop()
            if loop.is_running():
                return asyncio.ensure_future(coro)
        except RuntimeError:
            pass
        return asyncio.run(coro)

    # ─────────── sync API (called by CrewAI) ───────────
    def save(self, value: Any, metadata: Dict[str, Any]):
        self._run(self._save_async(value, metadata))

    def search(
        self,
        query: str,
        limit: int = 3,
        filter: Optional[Dict[str, Any]] = None,
        score_threshold: float = 0.0,
    ):
        return self._run(
            self._search_async(query, limit, filter, score_threshold)
        )

    def reset(self):
        self._run(self._reset_async())

    # ─────────── async internals ───────────
    async def _save_async(self, value: Any, metadata: Dict[str, Any]):
        await self._ensure_schema()
        vec = _embed(str(value), self._embed_api_key)
        rec = {
            "id": hashlib.sha1(str(value).encode()).hexdigest(),
            "text": value,
            "metadata": metadata or {},
            "embedding": vec,
        }
        async with self._adb as db:
            await db.signin({"username": self.user, "password": self.pw})
            await db.use(self.ns, self.db)
            await db.create(self.table, rec)

    async def _search_async(
        self,
        query: str,
        limit: int,
        filter: Optional[Dict[str, Any]],
        score_threshold: float,
    ):
        await self._ensure_schema()
        vec = _embed(query, self._embed_api_key)

        filter_params, where_clause = {}, ""
        if filter:
            conds = []
            for i, (k, v) in enumerate(filter.items()):
                pname = f"f{i}"
                conds.append(f"metadata.{k} == ${pname}")
                filter_params[pname] = v
            where_clause = " AND " + " AND ".join(conds)

        async with self._adb as db:
            await db.signin({"username": self.user, "password": self.pw})
            await db.use(self.ns, self.db)
            rs = await db.query(
                f"""
                SELECT *,
                       vector::distance::knn() AS score
                FROM {self.table}
                WHERE embedding <|{limit}|> $vec{where_clause}
                ORDER BY score ASC;
                """,
                {"vec": vec, **filter_params},
            )
        rows = rs[0]["result"]
        return [
            {
                "id": r["id"],
                "metadata": r["metadata"],
                "context": r["text"],
                "score": r["score"],
            }
            for r in rows
            if (score_threshold == 0 or r["score"] <= score_threshold)
        ]

    async def _reset_async(self):
        async with self._adb as db:
            await db.signin({"username": self.user, "password": self.pw})
            await db.use(self.ns, self.db)
            await db.query(f"REMOVE TABLE {self.table};")
        self._tables_ready.discard(self.table)

    # ─────────── table / index setup ───────────
    async def _ensure_schema(self):
        if self.table in self._tables_ready:
            return
        with self._lock:
            if self.table in self._tables_ready:
                return
            self._sdb.signin({"username": self.user, "password": self.pw})
            self._sdb.use(self.ns, self.db)
            self._sdb.query(
                f"""
                DEFINE TABLE {self.table} SCHEMALESS;
                DEFINE FIELD id        ON {self.table} TYPE string;
                DEFINE FIELD text      ON {self.table} TYPE string;
                DEFINE FIELD metadata  ON {self.table} TYPE object;
                DEFINE FIELD embedding ON {self.table} TYPE array;
                DEFINE INDEX IF NOT EXISTS {self.table}_vec_idx
                  ON {self.table} FIELDS embedding
                  HNSW DIMENSION {_EMBED_DIM} DIST COSINE;
                """
            )
            self._tables_ready.add(self.table)
```

## Wire it into a crew

Create `src/mycrew/crew.py`:

```python
import asyncio, logging
from typing import Optional

from crewai import Agent, Task, Crew
from crewai.memory.entity.entity_memory import EntityMemory
from crewai.memory.short_term.short_term_memory import ShortTermMemory

from mycrew.surreal_storage import SurrealStorage, _EMBED_DIM

logging.basicConfig(level=logging.INFO)

async def create_crew(
    openai_api_key: Optional[str] = None,
    surreal_url: str = "ws://localhost:8000/rpc",
) -> Crew:
    embed_cfg = {"api_key": openai_api_key}

    researcher = Agent(
        name="GeoResearcher",
        role="Geo-intelligence analyst",
        goal="collect up-to-date info on travel destinations",
    )

    planner = Agent(
        name="TripPlanner",
        role="Personal itinerary planner",
        goal="craft a perfect 48-hour city break",
    )

    entity_mem = EntityMemory(
        storage=SurrealStorage("entity",
                               url=surreal_url,
                               embedder_config=embed_cfg)
    )
    short_mem = ShortTermMemory(
        storage=SurrealStorage("short-term",
                               url=surreal_url,
                               embedder_config=embed_cfg)
    )

    t1 = Task(
        description="Find vibrant European cities with art festivals in June 2025.",
        expected_output="Top 3 candidate cities with festival names and dates.",
        agent=researcher,
    )

    t2 = Task(
        description="Design a relaxed 2-day itinerary for the best candidate.",
        expected_output="Detailed schedule with cafes, galleries, evening events.",
        agent=planner,
        context=[t1],
    )

    crew = Crew(
        memory=True,
        entity_memory=entity_mem,
        short_term_memory=short_mem,
    )
    crew.add_agents(researcher, planner)
    crew.add_tasks(t1, t2)
    return crew

async def main():
    crew = await create_crew()
    result = await crew.run()
    print(result)

if __name__ == "__main__":
    asyncio.run(main())
```

Run the crew:

```bash
python -m mycrew.crew
```

## Customising further

| Piece             | How to tweak it                                                                                 |
| ----------------- | ----------------------------------------------------------------------------------------------- |
| Embedding model   | Swap `_embed()` for JinaAI, Instructor, or a local transformer; adjust `_EMBED_DIM`.            |
| Similarity metric | Change `DIST COSINE` to `L2` or `DOT` to match your embeddings.                                 |
| Metadata filters  | Extend the simple `filter` mapping to support CrewAI’s richer operators (`$gt`, `$in`, …).      |
| Remote / Cloud DB | Replace `ws://localhost:8000/rpc` with `wss://<YOUR-ENDPOINT>/rpc` and supply a token/password. |

## Resources

* [Vector Search reference guide](/docs/learn/data-models/vector-search/overview.md)
* [Using SurrealDB as a Vector Database](/docs/learn/data-models/vector-search/overview.md)
* [Python SDK docs](/docs/reference/python.md)
* [DEFINE INDEX statement](/docs/reference/query-language/statements/define/indexes.md)

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/dagster

# Dagster

This section contains information about the Dagster framework and how to integrate it with SurrealDB.

Dagster is a tool for building data pipelines and workflows, and is widely used by data engineers and data scientists.

## Install

```bash title="Install"
pip install dagster surrealdb openai  # or swap out OpenAI for any embedder
# optional - launch a local SurrealDB daemon
docker run -p 8000:8000 surrealdb/surrealdb:latest \
       start --user root --pass secret file:/data/db
```

## A Dagster "SurrealResource"

```python title="src/dagster_surreal.py"
import dagster as dg
from surrealdb import Surreal
from typing import List, Sequence, Optional
import hashlib, json, os, contextlib

_EMBED_DIM = 1536  # match your embedder

def embed(text: str) -> List[float]:
    """Tiny helper - replace with your preferred model."""
    import openai
    resp = openai.Embedding.create(
        model="text-embedding-3-small",
        input=[text],
        dimensions=_EMBED_DIM,
        api_key=os.getenv("OPENAI_API_KEY"),
    )
    return resp["data"][0]["embedding"]


class SurrealConfig(dg.Config):
    url: str = dg.Field(str, default_value="ws://localhost:8000/rpc")
    namespace: str = dg.Field(str, default_value="dagster")
    database: str = dg.Field(str, default_value="vector")
    user: str = dg.Field(str, default_value="root")
    password: str = dg.Field(str, default_value="secret")


@dg.resource(config_schema=SurrealConfig)
class SurrealResource:
    """
    A very small wrapper that exposes .add() and .query() like dagster-qdrant.
    """

    def __init__(self, context):
        cfg: SurrealConfig = context.resource_config
        self.url = cfg.url
        self.namespace = cfg.namespace
        self.database = cfg.database
        self.user = cfg.user
        self.password = cfg.password

    # - helpers ----------------------------------------------------------
    def _ensure_table(self, table: str):
        with Surreal(self.url) as db:
            db.signin({"username": self.user, "password": self.password})
            db.use(self.namespace, self.database)
            db.query(
                """
                DEFINE TABLE $table SCHEMALESS;
                DEFINE FIELD id        ON $table TYPE string;
                DEFINE FIELD text      ON $table TYPE string;
                DEFINE FIELD embedding ON $table TYPE array;
                DEFINE INDEX IF NOT EXISTS ${table}_vec
                       ON $table FIELDS embedding
                       HNSW DIMENSION $dim DIST COSINE;
                """,
                {
                    "table": table,
                    "dim": _EMBED_DIM
                }
            )

    # - public API -------------------------------------------------------
    def add(self, collection_name: str, documents: Sequence[str]):
        self._ensure_table(collection_name)
        with Surreal(self.url) as db:
            db.signin({"username": self.user, "password": self.password})
            db.use(self.namespace, self.database)
            for doc in documents:
                rec = {
                    "id": hashlib.sha1(doc.encode()).hexdigest(),
                    "text": doc,
                    "embedding": embed(doc),
                }
                db.create(collection_name, rec)

    def query(
        self,
        collection_name: str,
        query_text: str,
        limit: int = 3,
        score_threshold: float = 0.4,
    ):
        self._ensure_table(collection_name)
        vec = embed(query_text)
        with Surreal(self.url) as db:
            db.signin({"username": self.user, "password": self.password})
            db.use(self.namespace, self.database)
            result = db.query(
                """
                SELECT text,
                       vector::similarity::cosine(embedding, $vec) AS score
                FROM $table
                WHERE embedding <|$limit|> $vec
                ORDER BY score DESC
                """,
                {
                    "table": collection_name,
                    "vec": vec,
                    "limit": limit
                }
            )
            rows = result[0]["result"]
            return [r for r in rows if r['score'] <= score_threshold or score_threshold == 0]

    # Use the resource as a context-manager inside assets
    @contextlib.contextmanager
    def get_client(self):
        try:
            yield self
        finally:
            pass  # No need to close since we use context managers for each operation
```

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/google-agent

# Google Agent

Google Agent is a framework for building and deploying agents.

Vertex AI Agent Builder is a framework for developing and deploying agents in Google Cloud. Any agent running on Vertex AI Agent Engine or the open-source ADK runtime can be [surfaced through Agentspace](https://cloud.google.com/products/agentspace), which makes it available to everyone in your organisation.

## TL;DR

*Build the agent with ADK → deploy to Agent Engine → "Add to Agentspace"* - the SurrealDB retrieval tool keeps working unchanged, giving your Gemini-based agent sub-second RAG over your own vector index, all inside Google Cloud.

Below is a concise walkthrough that shows:

1. creating a SurrealDB-powered retrieval tool
2. wiring it into an **ADK** agent
3. deploying that agent to Agent Engine
4. registering it in Agentspace so employees can chat with it from the Agentspace UI.

## Prerequisites

**Bash**

```bash
pip install google-adk google-genai surrealdb    # ADK + Gemini SDK + SurrealDB
docker run -p 8000:8000 surrealdb/surrealdb:latest \
       start --user root --pass secret file:/data/db   # optional local DB
export GOOGLE_API_KEY=<your-Gemini-key>
```

**PowerShell**

```powershell
pip install google-adk google-genai surrealdb    # ADK + Gemini SDK + SurrealDB
docker run -p 8000:8000 surrealdb/surrealdb:latest `
       start --user root --pass secret file:/data/db   # optional local DB
$env:GOOGLE_API_KEY = "<your-Gemini-key>"
```

## Prepare SurrealDB (one-time DDL)

```surql
DEFINE TABLE kb_docs SCHEMALESS;
DEFINE FIELD id        ON kb_docs TYPE string;
DEFINE FIELD text      ON kb_docs TYPE string;
DEFINE FIELD source    ON kb_docs TYPE string;
DEFINE FIELD embedding ON kb_docs TYPE array;

-- 1 536-D cosine HNSW (matches Gemini embeddings)
DEFINE INDEX IF NOT EXISTS kb_vec
  ON kb_docs FIELDS embedding
  HNSW DIMENSION 1536 DIST COSINE;
```

## Custom "Surreal Retrieve" tool

```python
from typing import List, Dict, Any, Optional
from google import genai
from surrealdb import AsyncSurreal
from surrealdb.exception import SurrealException
import os
import json
import hashlib
import logging
from dataclasses import dataclass
from contextlib import asynccontextmanager

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class SurrealConfig:
    """Configuration for SurrealDB connection."""
    url: str = "ws://localhost:8000/rpc"
    namespace: str = "agent"
    database: str = "demo"
    username: str = "root"
    password: str = "secret"

class SurrealRetriever:
    """SurrealDB-powered retrieval tool for Google Agent."""
    
    def __init__(
        self,
        config: Optional[SurrealConfig] = None,
        api_key: Optional[str] = None
    ):
        """Initialize the retriever.
        
        Args:
            config: Optional SurrealDB configuration
            api_key: Optional Google API key
        """
        self.config = config or SurrealConfig()
        self.api_key = api_key or os.environ.get("GOOGLE_API_KEY")
        if not self.api_key:
            raise ValueError("Google API key is required")
            
        genai.configure(api_key=self.api_key)
        self.embedder = genai.Client().models.get_embedding_model("models/embedding-001")
        
    @asynccontextmanager
    async def _get_connection(self) -> AsyncSurreal:
        """Get a database connection with proper authentication.
        
        Yields:
            Connected AsyncSurreal instance
            
        Raises:
            SurrealException: If connection fails
        """
        db = AsyncSurreal(self.config.url)
        try:
            await db.signin({
                "username": self.config.username,
                "password": self.config.password
            })
            await db.use(self.config.namespace, self.config.database)
            yield db
        except SurrealException as e:
            logger.error(f"Failed to connect to SurrealDB: {str(e)}")
            raise SurrealException(f"Connection failed: {str(e)}")
        finally:
            await db.close()

    async def _embed(self, text: str) -> List[float]:
        """Generate embeddings for text.
        
        Args:
            text: Text to embed
            
        Returns:
            List of embedding values
            
        Raises:
            Exception: If embedding generation fails
        """
        try:
            return self.embedder.embed(content=text).embedding
        except Exception as e:
            logger.error(f"Failed to generate embeddings: {str(e)}")
            raise Exception(f"Embedding generation failed: {str(e)}")

    async def retrieve(self, question: str, k: int = 4) -> str:
        """Retrieve top-k passages related to question from SurrealDB.
        
        Args:
            question: Search query
            k: Number of results to return
            
        Returns:
            Formatted string of matching passages
            
        Raises:
            SurrealException: If database operations fail
        """
        try:
            qv = await self._embed(question)
            async with self._get_connection() as db:
                result = await db.query("""
                    SELECT text, source,
                           vector::similarity::cosine(embedding, $vec) AS score
                    FROM kb_docs
                    WHERE embedding <|$k|> $vec
                    ORDER BY score DESC
                """, {
                    "vec": qv,
                    "k": k
                })
                
                rows = result[0]["result"]
                return "\n".join(
                    f"- {r['text']} (src: {r['source']})"
                    for r in rows
                )
        except SurrealException as e:
            logger.error(f"Retrieval failed: {str(e)}")
            raise SurrealException(f"Retrieval failed: {str(e)}")

    async def ingest(self, docs: List[Dict[str, str]]) -> None:
        """Ingest documents into SurrealDB.
        
        Args:
            docs: List of documents with text and source
            
        Raises:
            SurrealException: If database operations fail
        """
        try:
            async with self._get_connection() as db:
                for doc in docs:
                    rec = {
                        "id": hashlib.sha1(doc["text"].encode()).hexdigest(),
                        "text": doc["text"],
                        "source": doc["source"],
                        "embedding": await self._embed(doc["text"]),
                    }
                    await db.create("kb_docs", rec)
                logger.info(f"Ingested {len(docs)} documents")
        except SurrealException as e:
            logger.error(f"Ingestion failed: {str(e)}")
            raise SurrealException(f"Ingestion failed: {str(e)}")

    async def ensure_schema(self) -> None:
        """Ensure the required table and index exist.
        
        Raises:
            SurrealException: If schema operations fail
        """
        try:
            async with self._get_connection() as db:
                await db.query("""
                    DEFINE TABLE IF NOT EXISTS kb_docs SCHEMALESS;
                    DEFINE FIELD id        ON kb_docs TYPE string;
                    DEFINE FIELD text      ON kb_docs TYPE string;
                    DEFINE FIELD source    ON kb_docs TYPE string;
                    DEFINE FIELD embedding ON kb_docs TYPE array;
                    DEFINE INDEX IF NOT EXISTS kb_vec
                        ON kb_docs FIELDS embedding
                        HNSW DIMENSION 1536 DIST COSINE;
                """)
                logger.info("Schema ensured successfully")
        except SurrealException as e:
            logger.error(f"Schema setup failed: {str(e)}")
            raise SurrealException(f"Schema setup failed: {str(e)}")

# Example usage
async def main():
    retriever = SurrealRetriever()
    
    try:
        # Ensure schema exists
        await retriever.ensure_schema()
        
        # Ingest sample documents
        await retriever.ingest([
            {
                "text": "Nikola Tesla patented the first practical AC induction motor in 1888.",
                "source": "wiki/Tesla"
            },
            {
                "text": "The Wright brothers achieved powered flight on 17 Dec 1903.",
                "source": "wiki/Wright"
            },
        ])
        
        # Test retrieval
        result = await retriever.retrieve(
            "Who invented the AC motor and when?",
            k=2
        )
        print(result)
        
    except Exception as e:
        logger.error(f"Error: {str(e)}")
        raise

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
```

## Build an ADK agent that uses the tool

```python
from typing import Optional
from adk import Agent, Tool
from surreal_tool import SurrealRetriever
import asyncio
import logging
from contextlib import asynccontextmanager

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize retriever
retriever = SurrealRetriever()

@Tool
async def knowledge_search(query: str) -> str:
    """Search SurrealDB for passages relevant to the query.
    
    Args:
        query: Search query
        
    Returns:
        Formatted string of matching passages
    """
    try:
        return await retriever.retrieve(query, k=4)
    except Exception as e:
        logger.error(f"Knowledge search failed: {str(e)}")
        return f"Error searching knowledge base: {str(e)}"

@asynccontextmanager
async def get_agent():
    """Get an agent instance with proper setup and teardown.
    
    Yields:
        Configured Agent instance
    """
    try:
        agent = Agent(
            name="Surreal-Facts-Bot",
            llm="gemini-pro",
            instructions="""
You are a helpful assistant that must cite retrieved passages verbatim.
When knowledge is required, call knowledge_search().
""",
            tools=[knowledge_search],
        )
        logger.info("Agent created successfully")
        yield agent
    except Exception as e:
        logger.error(f"Failed to create agent: {str(e)}")
        raise

async def main():
    """Run the agent."""
    try:
        async with get_agent() as agent:
            response = await agent.chat("Who invented the AC motor and when?")
            print(response)
            logger.info("Agent execution completed successfully")
    except Exception as e:
        logger.error(f"Agent execution failed: {str(e)}")
        raise

if __name__ == "__main__":
    asyncio.run(main())
```

Run locally (`python agent.py`) to verify the agent calls your SurrealDB tool.

## Deploy to **Vertex AI Agent Engine**

Create `agent.yaml` (full schema in the ADK docs):

```yaml
name: surreal-facts
entrypoint: agent:agent        # python-module:object
requirements:
  - surrealdb
  - google-genai
  - google-adk
  - google-cloud-aiplatform
```

```bash
gcloud ai agent-engines deploy surreal-facts \
  --agent-spec=agent.yaml \
  --region=us-central1
```

## Publish in **Agentspace**

Agentspace can list any agent that's running on Agent Engine.

* **Console path:** *Agentspace → Agent Gallery → "Add agent" → Source: Agent Engine*
* **CLI (preview):**

```bash
gcloud ai agentspace agent-galleries add-agent \
  --agent-engine=projects/$PROJECT/locations/us-central1/agentEngines/surreal-facts
```

Once added, employees will see **"Surreal Facts Bot"** in the gallery and can chat with it from the Agentspace UI; every time it needs knowledge it silently calls your SurrealDB index.

## Operational notes

<table>
  <thead>
    <tr>
      <th>Topic</th>
      <th>Guidance</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Networking</strong></td>
      <td>Run SurrealDB on Cloud Run, GKE, or a VM inside the same VPC; use Private Service Connect so the Agent Engine can reach it.</td>
    </tr>
    <tr>
      <td><strong>Security</strong></td>
      <td>Protect the DB with <code>DEFINE ACCESS</code> tokens or basic auth; Agentspace inherits IAM & VPC-SC you already set in Agent Builder (<a href="https://cloud.google.com/agentspace/docs/overview">Google Cloud</a>).</td>
    </tr>
    <tr>
      <td><strong>Hybrid search</strong></td>
      <td>Mix Boolean filters with the <code>&lt;|K|&gt;</code> operator (<code>WHERE source ~ 'wiki' AND embedding &lt;|3|&gt;</code>).</td>
    </tr>
    <tr>
      <td><strong>Updates</strong></td>
      <td>New docs can be inserted at any time; SurrealDB's HNSW index updates incrementally, or run <a href="/docs/reference/query-language/statements/rebuild.md"><code>REBUILD INDEX</code></a> during low-traffic windows.</td>
    </tr>
  </tbody>
</table>

## Resources

- [Google Next 25 Updates: ADK, Agentspace, Application Integration](https://www.googlecloudcommunity.com/gc/Cloud-Product-Articles/Google-Next-25-Updates-ADK-Agentspace-Application-Integration/ta-p/898343)
- [DEFINE INDEX statement](/docs/reference/query-language/statements/define/indexes.md)
- [Vertex AI Agent Builder](https://cloud.google.com/products/agent-builder)
- [A Foundational Framework for Agentic AI Ecosystems: Enabling](https://medium.com/google-cloud/a-foundational-framework-for-agentic-ai-ecosystems-enabling-development-discovery-and-2aeb120949f6)
- [Introduction to Google Agentspace](https://cloud.google.com/agentspace/docs/overview)
- [REBUILD statement](/docs/reference/query-language/statements/rebuild.md)

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/hermes

# Hermes

Give a Hermes agent a persistent filesystem in SurrealDB, as a toolset it calls explicitly and as a memory provider that files and recalls every turn.

[Hermes](https://hermes-agent.nousresearch.com) is Nous Research's terminal agent. [SurrealDB filesystem](https://github.com/surrealdb/surrealfs) gives it somewhere durable to keep its work: a `file` table in SurrealDB, plus the tools to hand that table to a model. It supports files and folders and full-text and semantic search, and everything in it is queryable with SurrealQL, because it is an ordinary table.

**SurrealDB filesystem** ships two Hermes plugins. They install separately and either one works on its own:

- **The toolset** registers 14 `surrealfs_*` tools and a bundled skill, so the agent reads and writes the filesystem when it decides to.
- **The memory provider** files every completed turn into the same filesystem and searches it for context before each turn.

They are better together: the provider's recall surfaces the notes the agent wrote with the tools.

> [!NOTE]
> This page covers **SurrealDB filesystem** on a SurrealDB instance you run. For hosted memory with fact extraction and semantic recall, see the [SurrealDB Agent Memory integration for Hermes](/docs/agent-memory/integrations/frameworks/hermes.md), which is a separate provider.

## Requirements

- Python 3.12+
- A SurrealDB 3.x server, [installed locally](/docs/running/installation.md) or on [SurrealDB Cloud](/docs/operate/instances.md)
- A Hermes install

Install Hermes if you do not have it, and follow the [installation guide](https://hermes-agent.nousresearch.com/docs/getting-started/installation) through to `Installation Complete`:

```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
```

## Prepare a database

Start SurrealDB with a persistent backend, either [installed directly](/docs/running/installation.md):

```bash
surreal db start --user root --pass secret surrealkv://surrealfs.db
```

or [with Docker](/docs/running/docker.md):

```bash
docker run --rm --pull always -p 8000:8000 -v ./data:/data \
  surrealdb/surrealdb:latest start --user root --pass secret surrealkv://data/surrealfs.db
```

Then define the `file` table. The schema command reads the same `SURREALDB_*` variables as everything else, and it is safe to re-run:

```bash
python -m surrealfs.schema
```

Add `--include-user` for the optional `user` table and record access that the `file` table's `owner` permissions need for multi-tenancy, or `--print` to dump the DDL without connecting to anything.

A file's `parent` is a record link and its `path` is a computed field derived from the parent chain:

```surql
DEFINE FIELD path ON file COMPUTED (
    ($this.parent.path || '') + '/' + <string>$this.filename
) TYPE string;
```

Nothing stores a path, so moving or renaming a folder is a single `UPDATE` and every descendant's path follows automatically. A folder is a record with no content, `hash` is maintained by an event, and the HNSW and BM25 indexes behind the two search modes are part of the same schema.

## Connection settings

Both plugins read the same environment variables and default to a local server, so the defaults already work against `surreal db start` on your own machine.

| Variable | Default | Purpose |
| --- | --- | --- |
| `SURREALDB_URL` | `ws://localhost:8000/rpc` | Server to connect to |
| `SURREALDB_USER` / `SURREALDB_PASS` | `root` / `root` | Credentials |
| `SURREALDB_NAMESPACE` / `SURREALDB_DATABASE` | `surrealfs` / `demo` | Where the `file` table lives |
| `SURREALFS_SEMANTIC` | unset | `1` adds a vector arm to search and recall |

Put these in `$HERMES_HOME/.env` rather than your shell profile. Hermes cron jobs run with a sanitised environment, so a scheduled [indexer](#keep-the-vectors-current) reads its connection details from that file.

## The toolset

Hermes runs from its own virtualenv, so install the package there rather than into your project. `surrealfs` is not on PyPI yet, so install it from Git:

```bash
uv pip install --python ~/.hermes/hermes-agent/venv/bin/python \
  "surrealfs @ git+https://github.com/surrealdb/surrealfs.git"
hermes plugins enable surrealfs
hermes chat --toolsets surrealfs
```

Installing the package is what makes the plugin discoverable, because it registers through the `hermes_agent.plugins` entry point. Nothing in the plugin imports Hermes: the plugin contract is a `register` function and a manifest, so there is no extra dependency to install.

To run from a checkout instead, symlink the plugin directory into Hermes' plugin folder. The package still has to be importable by Hermes' interpreter:

```bash
ln -s "$PWD/surrealfs/integrations/hermes" ~/.hermes/plugins/surrealfs
```

### The tools

| Group | Tools |
| --- | --- |
| Read | `surrealfs_ls` `surrealfs_glob` `surrealfs_cat` `surrealfs_read_bytes` `surrealfs_tail` |
| Write | `surrealfs_write_file` `surrealfs_write_bytes` `surrealfs_edit` `surrealfs_touch` `surrealfs_mkdir` |
| Organise | `surrealfs_cp` `surrealfs_mv` `surrealfs_rm` |
| Search | `surrealfs_search` |

The prefix is deliberate. Hermes keeps one flat tool namespace that its own `read_file` and `write_file` already sit in, and the prefix also tells the model which filesystem it is addressing: the built-in file tools are the local disk, `surrealfs_*` is the shared one in SurrealDB. Every tool description says so too.

The plugin opens its own connection per call, and every result comes back as JSON, errors included. Handlers are registered as async, so Hermes awaits them on whichever event loop it is using.

### The bundled skill

`surrealfs:notes` teaches the agent to keep its notes and memories in SurrealDB filesystem, and how to lay them out:

| Path | Holds |
| --- | --- |
| `/home/<agent>/` | The agent's own working files |
| `/home/<agent>/memories/` | Turns filed by the memory provider |
| `/preferences/<user>/` | What the agent learns about the user |
| `/projects/<name>/` | Per-project notes, plans and to-do lists |

Paths are absolute and there is no working directory. Everything outside `/home/` is shared, which is how an agent hands something to its user or to another agent working for the same person.

Hermes advertises plugin skills nowhere: they are absent from the system prompt's `<available_skills>` index and from `skills_list()`, and resolve only by exact qualified name. The plugin therefore registers a `pre_llm_call` hook that names the skill on the first turn of each session. Hermes appends that to the user message and never persists it, so the system prompt stays byte-stable and the prompt cache holds.

## The memory provider

The provider needs two installs, because it is two different things. The *directory* is what Hermes scans to discover memory providers, and the *package* is what the provider imports. Providers are found by directory, never through the `hermes_agent.plugins` entry point:

```bash
hermes plugins install surrealdb/surrealfs/surrealfs/integrations/hermes_memory
uv pip install --python ~/.hermes/hermes-agent/venv/bin/python \
  "surrealfs @ git+https://github.com/surrealdb/surrealfs.git"
hermes memory setup surrealfs-memory
```

`hermes plugins install` accepts a subdirectory of a repository and takes the installed name from `plugin.yaml`, which is why the directory lands as `surrealfs-memory`. That is the name Hermes matches the active-provider setting against.

> [!NOTE]
> Answer **N** to install's `Enable now?` prompt. That prompt belongs to the general plugin manager, which this directory does not go through: `kind: exclusive` routes it to memory discovery instead, and `hermes memory setup` is what activates it.

`hermes memory setup` walks every setting below, offering the current value or the default, writes what you change to `$HERMES_HOME/.env`, activates the provider in `~/.hermes/config.yaml`, and then connects, so a wrong URL surfaces during setup rather than as a per-turn warning. Only one provider can be active at a time. To activate one by hand:

```yaml
memory:
  provider: surrealfs-memory
```

Two commands report on it afterwards. `hermes memory` lists the discovered providers and whether each reports itself available. `hermes surrealfs-memory status` re-runs the connection check at any time, naming the database it resolved and counting the turns filed there.

Upgrades are two commands for the same reason installs are: `hermes plugins update surrealfs-memory` for the directory, and the `uv pip install` again for the package. Run the second again whenever `hermes memory` starts reporting the provider unavailable, because a virtualenv rebuild strips it.

### Settings

Beyond the [connection settings](#connection-settings), the provider adds two of its own:

| Variable | Default | Purpose |
| --- | --- | --- |
| `SURREALFS_AGENT_USER` | Your Unix username | The agent's home under `/home` |
| `SURREALFS_MEMORY_DIR` | `/home/<agent>/memories` | Folder to file turns under |

Set `SURREALFS_AGENT_USER` whenever two agents would otherwise share a home: two Hermes installs owned by different people against one database, or an agent running under the same account as its human. `hermes-tobie` alongside the human's own `/home/tobie` is the shape to aim for. On a VM or sandbox where the agent has an account to itself, the default already matches the machine.

### What gets filed

Each completed turn becomes its own file:

```text
/home/hermes-tobie/memories/default/2026-08-06/a1b2c3-142251003.md
```

```markdown
# 2026-08-06 14:22:51 UTC

session: a1b2c3

## User

how do I get paid for the consulting work

## Assistant

You invoice monthly through ...

## Tools

→ surrealfs_search({"query": "invoice"})
→ surrealfs_cat({"path": "/projects/acme/contract.md"})
```

Each turn gets its own file rather than sharing one per session, because a search hit is then a single exchange with its snippet centred on the match. The `## Tools` section records which files were read and which commands ran. It is often the substance of the turn and appears in neither message's text, and it is omitted when the turn made no tool calls.

Turns where both sides carry no signal are skipped: a prompt like "ok" or "thanks", answered briefly. A trivial prompt with a long answer is still filed, because "go ahead" followed by a design document is a turn worth keeping. Anything that is not a primary agent is skipped too, so a cron run's system prompt is never filed as a memory and cannot corrupt what the agent believes about the user.

The filename ends in a wall-clock stamp (`HHMMSSmmm`) rather than a turn number. A counter has to live somewhere, and in-process is the one place it cannot: `hermes --resume` starts a second process on the same session id and restarts counting at one, so turn one of the resumed conversation would overwrite turn one of the original.

Two other things are filed under the same profile subtree:

- **Hermes' own memory.** When the built-in memory tool writes to `MEMORY.md` or `USER.md`, the same change is applied to `<memories>/<profile>/builtin/memory.md` or `.../user.md`. That mirrors what those files say rather than logging the writes, so recall reads the current state.
- **Messages about to be compressed away.** Before Hermes compresses a long conversation it asks each provider what to preserve. This provider writes the doomed messages out verbatim, tool calls included, and hands the compressor a pointer to the file, so the detail survives at full fidelity and the agent can read it back with `surrealfs_cat`.

> [!IMPORTANT]
> Everything filed here goes to the SurrealDB at your `SURREALDB_URL` and nowhere else. Hermes hands memory providers the turn's full message list; this provider writes part of it to your own database, and it leaves your machine only if you pointed it at a remote server yourself.

### What gets recalled

Before each turn the provider searches the whole filesystem, excluding other agents' homes. The notes the agent wrote itself under `/preferences/` and `/projects/` are the highest-signal memories present, so excluding them would mean the bundled `surrealfs:notes` skill and the provider ignored each other's work.

Filed turns are held to two of the five recalled slots, and the current conversation's own turns are never recalled at all. Recall reads the tree it writes, and one turn per file means short documents, which the ranking favours. Without a cap the top five drifts into verbatim transcript and the curated notes stop showing up.

The prompt is cut down to search terms before it reaches the index: stopwords out, a dozen terms at most. Every word in a whole paragraph is another `OR` branch, and matching records are read back in full to be ranked.

The search runs after the previous turn rather than during the current one, through Hermes' `queue_prefetch` and `prefetch` pair, so nothing waits on it, in particular not the embedding round trip that `SURREALFS_SEMANTIC=1` adds. The cost is that a recall is one turn behind: switch topic abruptly and the first turn on the new subject still carries context for the old one.

The provider registers no tools of its own. The 14 `surrealfs_*` tools from the toolset already cover explicit reads and writes, and a second set would collide in Hermes' flat tool namespace.

### Homes and profiles

Turns are filed under `/home/<agent>/memories/<profile>/`. The path has two segments, because there are two ways for memories to end up in one database that should not mix.

`<agent>` is `SURREALFS_AGENT_USER`, or the Unix account the agent runs as. A database shared between people holds one home per agent, plus the humans' own. The notes skill already treats `/home/<username>/` as the agent's working directory, so the memories sit inside the folder the agent already owns, and recall reads that home and no other.

`<profile>` comes from the `hermes_home` that Hermes passes to `initialize()`: `default` for `~/.hermes`, and the directory name for anything under `<root>/profiles/`. It separates one agent's own profiles, which share a home and a machine account.

Everything outside `/home/` stays shared. `/preferences/`, `/projects/`, and anything else written with the `surrealfs_*` tools is the handover point between an agent and its user, or between two agents working for the same person. Anything that must not be shared at all belongs in a `SURREALDB_DATABASE` of its own, and since `.env` lives in `$HERMES_HOME`, that is already per-profile.

> [!WARNING]
> `hermes backup` captures none of this. It walks `HERMES_HOME`, and the memories are in SurrealDB. Use [`surreal db export`](/docs/reference/cli/db/commands/export.md) instead.

## Semantic search

`SURREALFS_SEMANTIC=1` adds a vector arm to `surrealfs_search` and to recall, so a note about invoicing surfaces for a query of "how do I get paid". Both arms run and are fused by rank, because full-text scores are BM25 and vector scores are distances. The full-text arm matches a file that shares any term with the query, so search works before any vector exists; the vector arm is what makes ranking follow meaning rather than shared words.

It needs `OPENAI_API_KEY` and the `embed` extra, which neither plugin's install pulls in.

### Keep the vectors current

Skip this unless you set `SURREALFS_SEMANTIC=1`. A file is not embedded as it is written, so recall matches on meaning only for what the indexer has already reached. Recall keeps working on its full-text arm the whole time the vectors are behind.

Hermes has no way for a plugin to declare a daemon of its own, but its scheduler runs scripts without an agent, which covers this without a systemd unit or a terminal left open:

```bash
uv pip install --python ~/.hermes/hermes-agent/venv/bin/python \
  "surrealfs[embed] @ git+https://github.com/surrealdb/surrealfs.git"

mkdir -p "${HERMES_HOME:-$HOME/.hermes}/scripts"
cat > "${HERMES_HOME:-$HOME/.hermes}/scripts/surrealfs-embed.sh" <<'SCRIPT'
#!/usr/bin/env bash
set -a; . "${HERMES_HOME:-$HOME/.hermes}/.env"; set +a
exec ~/.hermes/hermes-agent/venv/bin/python -m surrealfs.embed --once
SCRIPT

hermes cron create 'every 5m' --no-agent --name surrealfs-embed \
  --script surrealfs-embed.sh
```

`--no-agent` skips the inference layer entirely, so a `--once` pass per tick costs no tokens and replaces the polling loop the daemon would otherwise run. The script must live under `$HERMES_HOME/scripts/`, because paths outside it are rejected. Cron sanitises the subprocess environment and `OPENAI_API_KEY` is on the blocklist, so the key and the `SURREALDB_*` details both have to come from the `.env` the script sources.

An idle pass prints nothing, and empty output is a silent tick, so you hear from this only when it has news. A pass that embedded something reports `embedded 4 file(s)`, and a pass that fails exits non-zero, which Hermes reports as an alert. `hermes cron runs` has the history.

Two things to know before relying on it. The scheduler ticks inside the gateway daemon, so this runs only while that does; run `hermes gateway install` if it is not already a service. And a five-minute period means a file written now is matchable by meaning in up to five minutes, and by term immediately. Lower the interval if that gap matters, at a cost of one `SELECT` per tick that returns nothing when there is no work.

## Browse the filesystem

Point the agents at a shared SurrealDB, a [Cloud instance](/docs/operate/instances.md) for example, and everyone on the team can run the file browser on their own machine to see and edit the same tree the agents write to:

```bash
pip install "surrealfs[browser]"
surrealfs-browser                # http://127.0.0.1:7933
```

The tree is on the left and the open file is on the right. Text is editable and saves back to the table, markdown renders with a source toggle, agent-authored HTML renders in a sandboxed iframe, images display, and the search box is the same hybrid search behind the agent's own tool calls.

Credentials come from a `.env` in the working directory or from the environment, which wins over the file. Every variable has a command-line form too; run `surrealfs-browser --help` for the list. Add `SURREALDB_AUTH_LEVEL` when the credentials are not root ones: the server infers the user kind from the signin payload, and a database-scoped Cloud credential needs `database`. All three levels are system users, so they bypass the `file` table's `owner = $auth.id` permissions and everyone sharing the database sees the one shared tree, which is the point.

> [!WARNING]
> The browser binds loopback. `--host 0.0.0.0` exposes it, and anyone who can then reach the port has whatever access those credentials do, because the page has no login of its own.

## Next steps

- [SurrealDB filesystem](https://github.com/surrealdb/surrealfs) - the repository, the full schema in `surrealfs/schema/file.surql`, and the plain async Python API to build your own integration on
- [Hermes toolset README](https://github.com/surrealdb/surrealfs/blob/main/surrealfs/integrations/hermes/README.md) - the tools, the prefix, and the bundled skill
- [Hermes memory provider README](https://github.com/surrealdb/surrealfs/blob/main/surrealfs/integrations/hermes_memory/README.md) - what gets filed, what gets recalled, and how homes and profiles divide it
- [Keeping the vectors current under Hermes](https://github.com/surrealdb/surrealfs/blob/main/docs/hermes-indexer.md) - the indexer cron job in full
- [SurrealDB Agent Memory integration for Hermes](/docs/agent-memory/integrations/frameworks/hermes.md) - hosted memory with fact extraction and semantic recall, as an alternative provider

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/kreuzberg

# Kreuzberg

Integrate Kreuzberg document intelligence extraction pipelines with SurrealDB.

Kreuzberg is a polyglot document intelligence framework that allows you to extract text, metadata, images, and structured information from PDFs, Office documents, images, and 91+ formats.

The `kreuzberg-surrealdb` package connects Kreuzberg's document extraction pipeline to SurrealDB. It handles schema creation, content deduplication, optional chunking and embedding, and index configuration.

## How it works

1. **Extract** - Kreuzberg parses the source documents and runs OCR where needed.
2. **Connect** - The connector receives the extracted output and manages the SurrealDB connection.
3. **Store** - Each document is hashed (SHA-256) for deduplication, optionally chunked and embedded, then written to SurrealDB under an auto-generated schema.
4. **Search** - Full-text (BM25), vector (HNSW), and hybrid (RRF) search are available immediately after ingestion.

## Key capabilities

- **Schema management** - `setup_schema()` creates tables, indexes, and analyzers. No manual DDL required.
- **Deduplication** - Deterministic record IDs derived from content hashes prevent duplicate records across ingestion runs.
- **Flexible ingestion** - Single files, file lists, directories (with glob), or raw bytes.
- **Extraction control** - Pass Kreuzberg's `ExtractionConfig` to set OCR behaviour, output format, and quality processing.
- **Batch tuning** - Adjust `insert_batch_size` to balance throughput against memory usage.

## Supported formats

Formats supported by Kreuzberg are as follows:

* Document formats: "pdf", "docx", "docm", "dotx", "dotm", "dot", "doc", "odt", "pptx", "ppsx", "pptm", "potx", "potm", "pot", "ppt", "xlsx", "xlsm", "xlsb", "xlam", "xla", "xltx", "xlt", "xls", "ods", "dbf", "hwp", "hwpx"
* Text formats: "txt", "md", "markdown", "commonmark", "html", "htm", "xml", "rtf", "rst", "org"
* Data formats: "json", "yaml", "yml", "toml", "csv", "tsv"
* Email formats: "eml", "msg"
* Archives: "zip", "tar", "gz", "tgz", "7z"
* Images (OCR supported): "bmp", "gif", "jpg", "jpeg", "png", "tiff", "tif", "webp", "jp2", "jpx", "jpm", "mj2", "j2k", "j2c", "jbig2", "jb2", "pnm", "pbm", "pgm", "ppm"
* Academic / publishing formats: "epub", "fb2", "bib", "ris", "nbib", "enw", "ipynb", "tex", "latex", "typst", "typ"
* Markup / structured formats: "opml", "dbk", "docbook", "jats"
* Other: "svg", "djot"

For more information on supported formats, see the [Kreuzberg docs](https://docs.kreuzberg.dev).

## Getting started

**Python**

To get started if using Python, visit [SurrealDB in the Kreuzberg Docs](https://kreuzberg.dev). For the complete API reference, embedding model options, chunking configuration, and database schema details, see the [Kreuzberg repository](https://github.com/Goldziher/kreuzberg).

**Rust**

As Kreuzberg is written in Rust and has its own [crate](https://crates.io/crates/kreuzberg), code can be written directly with much more boilerplate but also quite a bit of manual customisation. The following example shows a setup somewhat similar to the Python extension. It demonstrates a number of file types used to populate the same SurrealDB instance, in this case a JSON file `demo.json`, a Markdown file `demo.md`, and even an HWPX file `demo.hwpx`, which are assumed to be in a folder `/assets`. Most LLMs are able to generate sample files of these types such as the content below in JSON.

```json title="Sample data"
{
  "documents": [
    {
      "title": "English Quarterly Revenue",
      "language": "en",
      "content": "Quarterly revenue increased significantly this quarter."
    },
    {
      "title": "English Product",
      "language": "en",
      "content": "Product launch includes search and analytics."
    },
    {
      "title": "한국어 문서",
      "language": "ko",
      "content": "이 문서는 분기 매출과 검색 기능을 설명합니다."
    },
    {
      "title": "日本語 文書",
      "language": "ja",
      "content": "この文書は四半期売上と検索について説明します。"
    },
    {
      "title": "Mixed Doc",
      "language": "mixed",
      "content": "Quarterly revenue 데이터 日本語 検索 mixed language example."
    }
  ]
}
```

The code can be run with either `cargo run -- memory` or `cargo run -- local`, depending on if you prefer a one-time embedded instance or a local instance that can be connected to via SurrealDB Studio to manually query the data after the Rust code has run.

For more ideas on how to redo this example to suit your own needs, see the [Kreuzberg repository](https://github.com/Goldziher/kreuzberg).

```rust
// Required features to run:
// kreuzberg = { version = "4.9.4", default-features = true, features = ["hwp", "language-detection"] }
// surrealdb = { version = "4.0.0", default-features = true, features = ["protocol-ws", "kv-mem"] }
use anyhow::{Context, Result};
use kreuzberg::{extract_file, ExtractionConfig, LanguageDetectionConfig};
use sha2::{Digest, Sha256};
use std::{
    fs::read_to_string,
    path::{Path, PathBuf},
};
use surrealdb::{
    engine::any::connect,
    opt::auth::Root,
    types::{ToSql, Value},
};

use kreuzberg::types::ExtractionResult;
use serde::{Deserialize, Serialize};
use surrealdb::types::{RecordId, SurrealValue};

/// One logical document inside `assets/demo.json` (`documents` array).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonDocumentSpec {
    pub title: String,
    #[serde(default)]
    pub language: Option<String>,
    pub content: String,
}

#[derive(Debug, Deserialize)]
pub struct JsonDocumentsFile {
    pub documents: Vec<JsonDocumentSpec>,
}

/// Parse `demo.json`-style bundles to ingest records
pub fn parse_json_documents_file(path: &Path) -> anyhow::Result<JsonDocumentsFile> {
    let raw = read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    serde_json::from_str(&raw)
        .with_context(|| format!("parse JSON documents bundle {}", path.display()))
}

#[derive(Debug, Clone, SurrealValue)]
pub struct ExtractionMetadataNested {
    subject: Option<String>,
    language: Option<String>,
    modified_at: Option<String>,
    extraction_duration_ms: Option<u64>,
}

#[derive(Debug, Clone, SurrealValue)]
pub struct ConnectorDocument {
    id: RecordId,
    source: String,
    content: String,
    mime_type: String,
    title: Option<String>,
    authors: Option<Vec<String>>,
    created_at: Option<String>,
    metadata: ExtractionMetadataNested,
    quality_score: Option<f64>,
    content_hash: String,
    detected_languages: Option<Vec<String>>,
    keywords: Option<Vec<String>>,
}

/// Build the SurrealDB document payload for `INSERT IGNORE …`.
pub fn document_record_value(
    table: &str,
    extracted: &ExtractionResult,
    source_label: String,
    content_hash: &str,
) -> ConnectorDocument {
    let meta = &extracted.metadata;
    ConnectorDocument {
        id: RecordId::new(table, content_hash),
        source: source_label,
        content: extracted.content.clone(),
        mime_type: extracted.mime_type.as_ref().to_string(),
        title: meta.title.clone(),
        authors: meta.authors.clone(),
        created_at: meta.created_at.clone(),
        metadata: ExtractionMetadataNested {
            subject: meta.subject.clone(),
            language: meta.language.clone(),
            modified_at: meta.modified_at.clone(),
            extraction_duration_ms: meta.extraction_duration_ms,
        },
        quality_score: extracted.quality_score,
        content_hash: content_hash.to_string(),
        detected_languages: extracted.detected_languages.clone(),
        keywords: meta.keywords.clone(),
    }
}

/// Build a connector row from a JSON catalogue entry (no Kreuzberg pass - plain text is already known).
pub fn document_record_from_json_entry(
    table: &str,
    entry: &JsonDocumentSpec,
    source: String,
    content_hash: &str,
) -> ConnectorDocument {
    ConnectorDocument {
        id: RecordId::new(table, content_hash),
        source,
        content: entry.content.clone(),
        mime_type: "application/json".to_string(),
        title: Some(entry.title.clone()),
        authors: None,
        created_at: None,
        metadata: ExtractionMetadataNested {
            subject: None,
            language: entry.language.clone(),
            modified_at: None,
            extraction_duration_ms: None,
        },
        quality_score: None,
        content_hash: content_hash.to_string(),
        detected_languages: entry.language.as_ref().map(|l| vec![l.clone()]),
        keywords: None,
    }
}

const TABLE: &str = "documents";

fn sha256_hex(content: &str) -> String {
    let mut h = Sha256::new();
    h.update(content.as_bytes());
    format!("{:x}", h.finalize())
}

pub fn connector_schema(table: &str) -> String {
    format!(
        "DEFINE ANALYZER IF NOT EXISTS doc_analyzer TOKENIZERS class
            FILTERS lowercase,snowball(english);
        DEFINE TABLE IF NOT EXISTS {table} SCHEMAFULL;
        DEFINE FIELD IF NOT EXISTS source ON TABLE {table} TYPE string;
        DEFINE FIELD IF NOT EXISTS content ON TABLE {table} TYPE string;
        DEFINE FIELD IF NOT EXISTS mime_type ON TABLE {table} TYPE string;
        DEFINE FIELD IF NOT EXISTS title ON TABLE {table} TYPE option<string>;
        DEFINE FIELD IF NOT EXISTS authors ON TABLE {table} TYPE option<array<string>>;
        DEFINE FIELD IF NOT EXISTS created_at ON TABLE {table} TYPE option<string>;
        DEFINE FIELD IF NOT EXISTS ingested_at ON TABLE {table} TYPE datetime DEFAULT time::now();
        DEFINE FIELD IF NOT EXISTS metadata ON TABLE {table} TYPE object FLEXIBLE;
        DEFINE FIELD IF NOT EXISTS quality_score ON TABLE {table} TYPE option<float>;
        DEFINE FIELD IF NOT EXISTS content_hash ON TABLE {table} TYPE string;
        DEFINE FIELD IF NOT EXISTS detected_languages ON TABLE {table} TYPE option<array<string>>;
        DEFINE FIELD IF NOT EXISTS keywords ON TABLE {table} TYPE option<array<string>>;
        DEFINE INDEX IF NOT EXISTS idx_doc_source ON TABLE {table} FIELDS source UNIQUE;
        DEFINE INDEX IF NOT EXISTS idx_doc_hash ON TABLE {table} FIELDS content_hash UNIQUE;
        DEFINE INDEX IF NOT EXISTS idx_doc_content ON TABLE {table}
            FIELDS content FULLTEXT ANALYZER doc_analyzer BM25 HIGHLIGHTS;"
        )
}

// Add files such as demo.md, demo.hwpx, demo.json to /assets folder
fn default_asset_paths() -> Vec<PathBuf> {
    let assets = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");
    ["demo.md", "demo.hwpx", "demo.json"]
        .into_iter()
        .map(|name| assets.join(name))
        .collect()
}

fn json_entry_source_label(path: &Path, index: usize) -> String {
    format!("{}#{}", path.display(), index)
}

async fn ingest_path(
    path: &Path,
    table: &str,
    config: &ExtractionConfig,
) -> Result<Vec<ConnectorDocument>> {
    let path = path
        .canonicalize()
        .with_context(|| format!("resolve path {}", path.display()))?;
    if !path.is_file() {
        anyhow::bail!("not a file: {}", path.display());
    }

    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();

    if ext == "json" {
        let bundle = parse_json_documents_file(&path)?;
        if bundle.documents.is_empty() {
            anyhow::bail!("empty `documents` array in {}", path.display());
        }
        let mut records = Vec::with_capacity(bundle.documents.len());
        for (i, entry) in bundle.documents.iter().enumerate() {
            let hash = sha256_hex(&entry.content);
            let source = json_entry_source_label(&path, i);
            records.push(document_record_from_json_entry(table, entry, source, &hash));
        }
        Ok(records)
    } else {
        let extracted = extract_file(&path, None, config)
            .await
            .with_context(|| format!("Kreuzberg extract {}", path.display()))?;
        if !extracted.processing_warnings.is_empty() {
            eprintln!(
                "Kreuzberg warnings ({}): {:?}",
                path.display(),
                extracted.processing_warnings
            );
        }
        let hash = sha256_hex(extracted.content.as_str());
        Ok(vec![document_record_value(
            table,
            &extracted,
            path.display().to_string(),
            &hash,
        )])
    }
}

fn usage() -> &'static str {
    "usage: kreuzberg-surrealdb-example memory|local \n\
     \n\
       memory - SurrealDB in-memory (no server).\n\
       local - SurrealDB at ws://localhost:8000 (expects root/secret, ns/db main)."
}

#[tokio::main]
async fn main() -> Result<()> {
    let mut args = std::env::args_os().skip(1).collect::<Vec<_>>();
    if args.is_empty() {
        eprintln!("{}\n", usage());
        anyhow::bail!("missing mode: memory or local");
    }

    let mode = args.remove(0);
    let mode_str = mode
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("mode must be valid UTF-8"))?;
    let endpoint = match mode_str {
        "memory" => "memory",
        "local" => "ws://localhost:8000",
        _ => {
            eprintln!("{}\n", usage());
            anyhow::bail!(
                "first argument must be `memory` or `local`, got {:?}",
                mode_str
            );
        }
    };

    let paths: Vec<PathBuf> = if args.is_empty() {
        default_asset_paths()
    } else {
        args.into_iter().map(PathBuf::from).collect()
    };

    let config = ExtractionConfig {
        chunking: None,
        language_detection: Some(LanguageDetectionConfig {
            enabled: true,
            min_confidence: 0.55,
            detect_multiple: true,
        }),
        ..Default::default()
    };

    let mut all_docs = Vec::new();
    for p in &paths {
        let mut records = ingest_path(p, TABLE, &config).await?;
        all_docs.append(&mut records);
    }

    //eprintln!("Ingested {} record(s) from {} path(s).", all_docs.len(), paths.len());

    let client = connect(endpoint).await?;
    client.use_ns("main").use_db("main").await?;

    if mode_str == "local" {
        client
            .signin(Root {
                username: "root".into(),
                password: "secret".into(),
            })
            .await?;
    }

    client.query(connector_schema(TABLE)).await?.check()?;

    for doc in &all_docs {
        client
            .query(format!("INSERT IGNORE INTO {TABLE} $doc;"))
            .bind(("doc", doc.clone()))
            .await?
            .check()?;
    }

    let records: Value = client
        .query(
        "SELECT
            source,
            content,
            mime_type,
            title,
            metadata.language AS language,
            search::score(0) AS score
        FROM documents
        WHERE content @0@ 'product'
        ORDER BY score DESC
        LIMIT 10;",
        )
        .await?
        .check()?
        .take(0)?;

    println!("BM25 hits:\n{}", records.to_sql_pretty());

    Ok(())
}
```

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/langchain

# LangChain

Use SurrealDB native vector indexes as a drop-in vector store for LangChain.

[LangChain](https://python.langchain.com/docs/introduction/) is a framework for developing applications powered by large language models (LLMs). SurrealDB suits [LangChain](https://python.langchain.com/docs/introduction/) projects mainly because of its [multi-model capabilities](/docs/learn/data-models.md): a single database manages all of the application's data.

It handles structured and unstructured data, with vector search, [graph traversal](/docs/learn/data-models/graph/overview.md), [relational queries](/docs/learn/data-models.md), [full-text search](/docs/learn/data-models/full-text-search/overview.md), [document storage](/docs/learn/data-models/document/overview.md), and [time-series data](/docs/learn/data-models/time-series/overview.md) all within one ACID-compliant engine.

LangChain applications often work with several types of data for tasks such as context retrieval. Keeping all of them in one database simplifies the architecture, reduces latency, and keeps the data consistent.

This guide shows how to use SurrealDB as a vector store for LangChain.

> [!NOTE]
> This page uses the Python package, `langchain-surrealdb`. For TypeScript and JavaScript, the `@surrealdb/langgraph` package stores LangGraph.js checkpoints, long-term memory and node results in SurrealDB. See [LangGraph](/docs/integrate/integrations/ai-frameworks/langgraph.md).

<video style="width: 100%;" height="300" controls>
    <source src={VidMp4} type="video/mp4" />
    <source src={VidWebm} type="video/webm" />
</video>

## Setup

The examples on this page connect to a SurrealDB server at `ws://localhost:8000` and sign in as `root` with the password `secret`. To run one locally, [install SurrealDB](/docs/running/installation.md) and start it in memory with `surreal db start -u root -p secret`, or [run it with Docker](/docs/running/docker.md).

Then install the packages:

```bash
pip install -U langchain-surrealdb langchain_ollama surrealdb
```

* `surrealdb` → [SurrealDB Python SDK](/docs/reference/python.md)
* `langchain-surrealdb` → houses `SurrealDBVectorStore`
* `langchain_ollama`, `langchain-openai` (or HF, Cohere, etc.) → embeddings

## Create a vector store

`SurrealDBVectorStore` takes a LangChain embeddings model and a SurrealDB connection:

```python
from langchain_surrealdb.vectorstores import SurrealDBVectorStore
from langchain_ollama import OllamaEmbeddings
from surrealdb import Surreal

conn = Surreal("ws://localhost:8000/rpc")
conn.signin({"username": "root", "password": "secret"})
conn.use("langchain", "demo")
vector_store = SurrealDBVectorStore(OllamaEmbeddings(model="llama3.2"), conn)
```

Any LangChain embeddings class works in place of `OllamaEmbeddings`, such as `OpenAIEmbeddings` from `langchain-openai`. Internally, the vector store:

1. Creates the table **`documents`** if it does not exist.
2. Adds an **HNSW** index with the dimension of the embeddings model, using cosine distance and `F32` vectors.
3. Inserts each text with the embedding that the model generated for it.

## Add and search documents

The vector store implements the standard LangChain vector store methods:

| Method | Use |
| --- | --- |
| `add_documents(documents, ids)` | Embed and store LangChain `Document` objects. |
| `similarity_search(query, k, custom_filter)` | Return the `k` documents closest to the query text. `custom_filter` matches on document metadata. |
| `similarity_search_with_score(query, k, custom_filter)` | The same, with the distance score of each document. |
| `as_retriever(search_type, search_kwargs)` | Wrap the vector store as a retriever for use in a chain, for example with `search_type="mmr"`. |

The LangChain example in the tutorial [Build an AI agent with Python](/docs/learn/tutorials/walkthroughs/build-an-ai-agent.md#getting-started-with-langchain) uses each of these on two sample documents and shows the output.

## Next steps

The following resources cover more advanced use of SurrealDB with LangChain.

Several example implementations are available:

* A [basic example](https://github.com/surrealdb/langchain-surrealdb/tree/main/examples/basic) with a ready-to-use Dockerfile - perfect for your first steps
* A more advanced [graph example](https://github.com/surrealdb/langchain-surrealdb/tree/main/examples/graph) showcasing graph capabilities
* An interactive [Jupyter notebook](https://python.langchain.com/docs/integrations/vectorstores/surrealdb/) for hands-on learning

### Further reading and resources

For a deeper understanding of the technology stack:

* Explore the [SurrealDB vector-search reference](/docs/learn/data-models/vector-search/overview.md) for detailed technical information
* Check out the [LangChain API docs for `SurrealDBStore`](https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.surrealdb.SurrealDBStore.html) for the full API documentation
* Browse [Awesome SurrealDB](https://github.com/surrealdb/awesome-surreal) for a curated collection of resources, tools, and applications
That’s it - you now have a fully-featured LangChain vector store powered by SurrealDB, no boilerplate required. 🚀

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/langgraph

# LangGraph

Use SurrealDB as the checkpointer, long-term memory store and node cache for LangGraph.js agents and graphs with the @surrealdb/langgraph package.

[LangGraph.js](https://langchain-ai.github.io/langgraphjs/) is the TypeScript framework from LangChain for building stateful agents and multi-step graphs. The [`@surrealdb/langgraph`](https://www.npmjs.com/package/@surrealdb/langgraph) package stores the three kinds of state that LangGraph persists in a SurrealDB database that you run: conversation checkpoints, long-term memory, and cached node results.

This page is for TypeScript and JavaScript applications. The companion package `@surrealdb/langchain` provides LangChain.js components such as a vector store, retrievers and tools, and its [README](https://github.com/surrealdb/langchain.py#readme) documents them. For Python, see [LangChain](/docs/integrate/integrations/ai-frameworks/langchain.md).

| Class | LangGraph interface | What it stores |
| --- | --- | --- |
| `SurrealDBSaver` | `BaseCheckpointSaver` | Short-term state: the graph state of each thread after every step, so a conversation can continue, resume after an interrupt, or go back to an earlier step. |
| `SurrealDBStore` | `BaseStore` | Long-term memory: JSON items in namespaces that every thread can read, with optional semantic search. |
| `SurrealDBNodeCache` | `BaseCache` | Node results for nodes that declare a `cachePolicy`, so a repeated input does not run the node again. |

> [!NOTE]
> The same package also includes `AgentMemoryStore`, a read-only store that reads from the hosted [SurrealDB Agent Memory](/docs/agent-memory.md) service instead of your own database. It is documented on the [Agent Memory LangChain page](/docs/agent-memory/integrations/frameworks/langchain.md).

## Requirements

- [SurrealDB v3](/docs/running/installation.md), local or on [SurrealDB Cloud](/docs/operate/instances.md). The adapters check the server version when they connect and throw on v2.
- Node.js 22+ or Bun 1+
- `@langchain/core` 1.2.9+ and `@langchain/langgraph-checkpoint` 1.1.5+. LangChain v0.3 is not supported.

## Setup

Start SurrealDB locally, either [installed directly](/docs/running/installation.md):

```sh
surreal db start --user root --pass secret memory
```

or [with Docker](/docs/running/docker.md):

```sh
docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass secret
```

The `memory` storage engine keeps data only until the server stops. To keep checkpoints across restarts, start the server with a [persistent storage engine](/docs/running/file-backed.md).

## Install dependencies

```sh
bun add @surrealdb/langgraph @langchain/langgraph @langchain/core
```

The quick start below also uses the `langchain` package for `createAgent` and `@langchain/openai` for the model:

```sh
bun add langchain @langchain/openai
```

## Quick start

`createAgent` accepts a checkpointer and a store, so you can pass both adapters to it directly. The checkpointer saves the conversation under the `thread_id` in the run config, which makes the second call aware of the first:

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { SurrealDBSaver, SurrealDBStore } from "@surrealdb/langgraph";
import { createAgent } from "langchain";

const surreal = {
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
    namespace: "app",
    database: "agent",
};

const checkpointer = new SurrealDBSaver({ surreal });
const store = new SurrealDBStore({ surreal });
await store.start();

const agent = createAgent({
    model: new ChatOpenAI({ model: "gpt-4.1-mini" }),
    tools: [],
    checkpointer,
    store,
});

const config = { configurable: { thread_id: "demo-thread" } };

await agent.invoke(
    { messages: [{ role: "user", content: "My name is Ada." }] },
    config,
);

const result = await agent.invoke(
    { messages: [{ role: "user", content: "What is my name?" }] },
    config,
);

console.log(result.messages.at(-1)?.text);

await checkpointer.close();
await store.stop();
```

Each adapter creates its tables and indexes the first time it is used. You do not need to define a schema first.

## Connect to SurrealDB

Every adapter takes a `surreal` option. Pass it either a connection config or a `SurrealDBClient` that you created yourself.

A connection config signs in with a username and password, or authenticates with a token:

```typescript
// Username and password
const surreal = {
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
    namespace: "app",
    database: "agent",
};

// Token, for example a record user's JWT
const surrealWithToken = {
    url: "wss://<your-instance>.aws.surrealdb.cloud",
    token: process.env.SURREALDB_TOKEN!,
    namespace: "app",
    database: "agent",
};
```

| Field | Required | Notes |
| --- | --- | --- |
| `url` | Yes | WebSocket or HTTP endpoint of the SurrealDB server. |
| `username`, `password` | One of these or `token` | Credentials for `signin`. |
| `token` | One of these or `username` and `password` | An existing access token for `authenticate`. |
| `namespace` | No | Defaults to `langchain`. |
| `database` | No | Defaults to `langchain`. |

An adapter that receives a config opens its own connection and closes it in `close()` or `stop()`. To use one connection for several adapters, create a `SurrealDBClient` and pass it to each one. An adapter does not close a client that you passed in, so close it yourself when the application stops:

```typescript
import {
    SurrealDBClient,
    SurrealDBNodeCache,
    SurrealDBSaver,
    SurrealDBStore,
} from "@surrealdb/langgraph";

const client = new SurrealDBClient({
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
    namespace: "app",
    database: "agent",
});

const checkpointer = new SurrealDBSaver({ surreal: client });
const store = new SurrealDBStore({ surreal: client });
const cache = new SurrealDBNodeCache({ surreal: client });

// ...

await client.close();
```

## Checkpointer

`SurrealDBSaver` implements the full LangGraph `BaseCheckpointSaver` contract. Pass it as `checkpointer` to `createAgent`, or to `compile()` on a `StateGraph`:

```typescript
import { SurrealDBSaver } from "@surrealdb/langgraph";

const checkpointer = new SurrealDBSaver({ surreal });

const graph = builder.compile({ checkpointer });

await graph.invoke(input, { configurable: { thread_id: "user-42" } });
```

LangGraph writes a checkpoint after each step of a run. Checkpoint data is serialised with the LangGraph serialiser and stored as SurrealDB `bytes`, so message objects and other state values come back with their types intact.

### Read the history of a thread

`list()` returns checkpoints newest first. It supports the `before`, `limit` and `filter` options, and fills in `pendingWrites`, so `getStateHistory()` on a compiled graph also reports pending tasks:

```typescript
const config = { configurable: { thread_id: "user-42" } };

for await (const tuple of checkpointer.list(config, { limit: 5 })) {
    console.log(
        tuple.config.configurable?.checkpoint_id,
        tuple.metadata?.step,
        `${tuple.pendingWrites?.length ?? 0} pending writes`,
    );
}
```

Leave out `thread_id` to list checkpoints across all threads, and leave out `checkpoint_ns` to list across all namespaces. `filter` matches fields in the checkpoint metadata and takes the same operators as the store filter described in [Filter items](#filter-items).

### Delete a thread

`deleteThread()` removes every checkpoint and pending write for a thread in one transaction:

```typescript
await checkpointer.deleteThread("user-42");
```

### Options

| Option | Default | Notes |
| --- | --- | --- |
| `surreal` | Required | A connection config or a `SurrealDBClient`. |
| `checkpointsTable` | `langgraph_checkpoints` | Table for checkpoints. |
| `writesTable` | `langgraph_checkpoint_writes` | Table for pending writes. |
| `serde` | `JsonPlusSerializer` | A LangGraph `SerializerProtocol`. |
| `skipInitSchema` | `false` | Do not create tables and indexes. See [Manage the schema yourself](#manage-the-schema-yourself). |
| `skipVersionCheck` | `false` | Do not check that the server is v3 or later. |

> [!NOTE]
> The checkpointer reads checkpoint format v4 and later, which is the format that current LangGraph versions write. It refuses to load an older checkpoint rather than return state in a format the graph cannot use.

## Long-term memory store

`SurrealDBStore` implements the LangGraph `BaseStore`. A store holds JSON items that stay available across threads, such as user preferences or facts that an agent learnt in an earlier conversation. Each item has a namespace, which is an array of strings, and a key that is unique within that namespace.

Call `start()` once before the first use. It connects, and creates the table and indexes:

```typescript
import { SurrealDBStore } from "@surrealdb/langgraph";

const store = new SurrealDBStore({ surreal });
await store.start();

await store.put(["users", "alice", "preferences"], "theme", { value: "dark" });
await store.put(["users", "alice", "preferences"], "language", { value: "en" });
await store.put(["users", "bob", "preferences"], "theme", { value: "light" });

const theme = await store.get(["users", "alice", "preferences"], "theme");
console.log(theme?.value);
```

```text title="Output"
{ value: 'dark' }
```

`put()` on an existing namespace and key replaces the item and updates its `updatedAt` time. `delete(namespace, key)` removes an item.

`search()` takes a namespace prefix and returns the items under it, newest first. `listNamespaces()` returns the distinct namespaces under a prefix, and `maxDepth` shortens each one:

```typescript
const items = await store.search(["users", "alice"]);
console.log(items.length);

const namespaces = await store.listNamespaces({ prefix: ["users"], maxDepth: 2 });
console.log(namespaces);
```

```text title="Output"
2
[ [ 'users', 'alice' ], [ 'users', 'bob' ] ]
```

Inside a graph node or an agent tool, LangGraph passes the store in the runtime config, so the node reads and writes the same SurrealDB table without a reference of its own.

### Filter items

`filter` matches fields inside the item value. A bare value means equality, several keys must all match, and these operators are supported: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin` and `$exists`.

```typescript
await store.search(["users"], {
    filter: { value: { $in: ["dark", "high-contrast"] } },
    limit: 20,
});
```

### Semantic search

To search items by meaning, give the store an `index` with an embeddings model and the number of dimensions it produces. The store then embeds each item when it is saved and defines an [HNSW vector index](/docs/learn/data-models/vector-search/overview.md) on the table:

```typescript
import { OpenAIEmbeddings } from "@langchain/openai";
import { SurrealDBStore } from "@surrealdb/langgraph";

const store = new SurrealDBStore({
    surreal,
    index: {
        dims: 1536,
        embeddings: new OpenAIEmbeddings({ model: "text-embedding-3-small" }),
        fields: ["text"],
    },
});
await store.start();

await store.put(["users", "alice"], "pref-ui", { text: "Prefers dark mode" });
await store.put(["users", "alice"], "pref-food", { text: "Is vegetarian" });

const hits = await store.search(["users", "alice"], {
    query: "user interface settings",
    limit: 1,
});

console.log(hits[0]?.key, hits[0]?.score);
```

`fields` names the paths in the value to embed. Without it, the store embeds the whole value as JSON. To skip embedding for one item, pass `false` as the fourth argument to `put()`. With the default cosine distance, `score` is the cosine similarity, so a higher score is a closer match.

If `search()` gets a `query` but the store has no `index`, it logs a warning once and returns recent items without ranking. Set `strictSearch: true` to throw an error instead.

> [!IMPORTANT]
> The vector index is created with the `dims` value from the first `start()`. If you change the embeddings model to one with a different number of dimensions, remove the index or use a new `tableName`.

### Options

| Option | Default | Notes |
| --- | --- | --- |
| `surreal` | Required | A connection config or a `SurrealDBClient`. |
| `tableName` | `langgraph_store` | Table for items. |
| `index` | None | `{ dims, embeddings, fields?, distanceStrategy? }`. Enables semantic search. |
| `index.distanceStrategy` | `cosine` | `cosine`, `euclidean`, `manhattan` or `hamming`. |
| `indexType` | `hnsw` | `hnsw`, `diskann` (SurrealDB 3.1+), or `none` for a brute-force search. |
| `ef` | `40` | Search breadth for the vector index. A higher value is more accurate and slower. |
| `strictSearch` | `false` | Throw when `search()` gets a `query` and no `index` is configured. |
| `skipInitSchema` | `false` | Do not create the table and indexes. |
| `skipVersionCheck` | `false` | Do not check that the server is v3 or later. |

The store runs the operations in a batch one after another, not in a single transaction. A `put()` with an `index` calls the embeddings provider, and a transaction would keep a write lock open during that network call.

## Node cache

LangGraph v1 lets a node declare a `cachePolicy`. When the same node runs again with the same input before the time to live (TTL) ends, LangGraph returns the cached result and does not run the node. `SurrealDBNodeCache` keeps those results in SurrealDB, so the cache is shared between processes and stays after a restart. Pass it as `cache` to `compile()`:

```typescript
import { Annotation, END, START, StateGraph } from "@langchain/langgraph";
import { SurrealDBNodeCache } from "@surrealdb/langgraph";

const cache = new SurrealDBNodeCache({ surreal });

const State = Annotation.Root({
    input: Annotation<string>(),
    output: Annotation<string>(),
});

let calls = 0;

const graph = new StateGraph(State)
    .addNode(
        "summarise",
        async (state) => {
            calls++;
            return { output: state.input.toUpperCase() };
        },
        { cachePolicy: { ttl: 120 } },
    )
    .addEdge(START, "summarise")
    .addEdge("summarise", END)
    .compile({ cache });

await graph.invoke({ input: "hello" });
await graph.invoke({ input: "hello" });

console.log(`node ran ${calls} time(s)`);

await cache.close();
```

```text title="Output"
node ran 1 time(s)
```

`ttl` is in seconds. A cached result without a TTL does not expire.

LangGraph does not wait for a cache write to finish, so a write that fails cannot stop the graph. The cache catches the error and passes it to `onError`, which logs a console warning by default:

```typescript
const cache = new SurrealDBNodeCache({
    surreal,
    onError: (err) => logger.error({ err }, "node cache write failed"),
});
```

| Option | Default | Notes |
| --- | --- | --- |
| `surreal` | Required | A connection config or a `SurrealDBClient`. |
| `tableName` | `langgraph_cache` | Table for cached results. |
| `serde` | `JsonPlusSerializer` | A LangGraph `SerializerProtocol`. |
| `onError` | Console warning | Called when a cache write fails. |
| `skipInitSchema` | `false` | Do not create the table. |
| `skipVersionCheck` | `false` | Do not check that the server is v3 or later. |

## Manage the schema yourself

By default, each adapter runs `DEFINE TABLE IF NOT EXISTS`, `DEFINE FIELD` and `DEFINE INDEX` statements the first time it connects. This needs a user that can define tables, such as a namespace or database [system user](/docs/reference/query-language/statements/define/user.md) with the `EDITOR` or `OWNER` role.

To run the application as a user with fewer permissions, create the schema once with a separate user or a migration, then set `skipInitSchema: true` on each adapter. The tables are:

| Adapter | Default tables |
| --- | --- |
| `SurrealDBSaver` | `langgraph_checkpoints`, `langgraph_checkpoint_writes` |
| `SurrealDBStore` | `langgraph_store` |
| `SurrealDBNodeCache` | `langgraph_cache` |

The quickest way to get the exact definitions is to let the adapters create the tables in a development database, then run [`INFO FOR TABLE`](/docs/reference/query-language/statements/info.md) on each one or use [`surreal db export`](/docs/reference/cli/db/commands/export.md).

## Close connections

An adapter that created its own connection closes it in `checkpointer.close()`, `store.stop()` or `cache.close()`. Call these when the process shuts down. If you passed a shared `SurrealDBClient`, these methods leave it open, and you close the client instead.

## Examples and source

- The [adapter repository](https://github.com/surrealdb/langchain.py) contains the source and runnable examples for an agent with a checkpointer, long-term memory, and node caching.
- [LangChain](/docs/integrate/integrations/ai-frameworks/langchain.md) covers SurrealDB as a vector store for LangChain in Python.
- [Vector search](/docs/learn/data-models/vector-search/overview.md) explains the HNSW and DiskANN indexes that semantic search uses.
- [Agent Memory LangChain integration](/docs/agent-memory/integrations/frameworks/langchain.md) covers retrievers, tools and `AgentMemoryStore` for the hosted memory service.

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/llamaindex

# LlamaIndex

Use SurrealDB’s native HNSW vector index as the backing store for a Llama Index `VectorStoreIndex`.

Llama Index is a framework for building RAG pipelines. It provides a flexible and powerful way to build and deploy RAG systems.

> [!NOTE]
> Llama Index doesn’t (yet!) ship an off-the-shelf SurrealDB adapter, so in this guide we’ll implement a **20-line `SurrealVectorStore`** that satisfies Llama Index’s minimal vector-store interface. You can drop it into any RAG pipeline just like you would with Pinecone, Qdrant, Chroma, etc.

## TL;DR

1. **Install** `surrealdb` + `llama-index`.
2. **Create** a table with an `HNSW` index.
3. **Drop-in** the 20-line `SurrealVectorStore`.
4. Use `VectorStoreIndex.from_documents()` and you’re done.

## Install the libraries

```bash
pip install surrealdb llama-index numpy
```

## Connect to SurrealDB

```python
from surrealdb import Surreal
import asyncio, os

# - connection details -
DB_URL   = os.getenv("SDB_URL", "http://localhost:8000/rpc")
DB_USER  = os.getenv("SDB_USER", "root")
DB_PASS  = os.getenv("SDB_PASS", "secret")
NS, DB   = "demo", "demo"
TABLE    = "llama_chunks"

sdb = Surreal(DB_URL)

async def init():
    await sdb.signin({"user": DB_USER, "pass": DB_PASS})
    await sdb.use(NS, DB)

asyncio.run(init())
```

## Create the table and HNSW index

```python
# SurrealDB ≥ v1.5 exposes an in-memory HNSW ANN index
schema = """
DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
DEFINE FIELD text      ON $tb TYPE string;
DEFINE FIELD embedding ON $tb TYPE array;

DEFINE INDEX idx_hnsw ON $tb
  FIELDS embedding
  HNSW DIMENSION 768
  DIST   COSINE;
"""
asyncio.run(sdb.query(schema, {"tb": TABLE}))
```

SurrealQL’s `DEFINE INDEX … HNSW` activates a high-speed, cosine-distance ANN index.

## A tiny SurrealDB adapter for Llama Index

```python
import numpy as np
from typing import Any, List, Sequence
from llama_index.core.vector_stores.types import (
    BasePydanticVectorStore,
    VectorStoreQuery,
    VectorStoreQueryResult,
)
from llama_index.core.schema import NodeWithEmbedding

class SurrealVectorStore(BasePydanticVectorStore):
    """Minimal Llama Index adapter using SurrealDB’s <|K,EF|> operator."""

    def __init__(self, table: str, conn: Surreal):
        self.table, self.conn = table, conn

    # ---- required APIs ----------------------------------------------------
    def add(self, nodes: Sequence[NodeWithEmbedding], **_) -> List[str]:
        rows = [
            {
                "id": f"{self.table}:{i}",
                "text": n.get_content(metadata_mode="all"),
                "embedding": n.embedding,
            }
            for i, n in enumerate(nodes)
        ]
        asyncio.run(self.conn.query(f"INSERT INTO {self.table} $data", {"data": rows}))
        return [r["id"] for r in rows]

    def delete(self, doc_id: str, **_) -> None:  # optional but easy
        asyncio.run(self.conn.delete(doc_id))

    def query(
        self, query: VectorStoreQuery, **_
    ) -> VectorStoreQueryResult:  # semantic search
        q_vec = query.query_embedding
        surql = """
        LET $q := $vec;
        SELECT id, text, vector::distance::knn() AS score
        FROM {self.table}
        WHERE embedding <|{query.similarity_top_k},64|> $q
        ORDER BY score;
        """
        res = asyncio.run(self.conn.query(surql, {"vec": q_vec}))[0].result
        return VectorStoreQueryResult(
            nodes=[],  # Llama Index will fetch raw docs separately
            ids=[r["id"] for r in res],
            similarities=[r["score"] for r in res],
        )
```

The `SurrealVectorStore` class is a minimal adapter cribbed from the official [build a vector store from scratch](https://docs.llamaindex.ai/en/stable/examples/low_level/vector_store/) example.

## Index documents with Llama Index

```python
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# 5-1  load + chunk a handful of docs (replace with your own)
docs = SimpleDirectoryReader("./my_pdfs").load_data()

# 5-2  build the index - Llama Index will call SurrealVectorStore.add()
surreal_store = SurrealVectorStore(table=TABLE, conn=sdb)
index = VectorStoreIndex.from_documents(
    docs,
    vector_store=surreal_store,
    show_progress=True,
)
```

## Query

```python
qe   = index.as_query_engine(similarity_top_k=4)
resp = qe.query("Which document talks about vector search in SurrealDB?")
print(resp)
```

The query flow is:

```text
User → Llama Index → SurrealVectorStore.query()
          ↘︎ top-K doc IDs & scores
                  ↘︎ fetch full text → synthesize answer
```

## What about metadata filters, deletes, hybrid search?

SurrealDB supports **metadata-rich JSON payloads**, additional **filter clauses**, and full-text search; extend `SurrealVectorStore.query()` to:

* add `WHERE` predicates before the `<|K,EF|>` operator,
* combine with `vector::distance::knn()` for re-ranking,
* or fall back to `vector::similarity::cosine()` for exact search.

All other Llama Index abstractions (retrievers, query engines, agents) work unchanged, because they talk to the vector store through the same tiny interface you just implemented.

Enjoy Llama Index + SurrealDB!

## References

- [DEFINE INDEX statement](/docs/reference/query-language/statements/define/indexes.md)
- [Building a RAG with Astro, FastAPI, SurrealDB and Llama 3.1](https://fireworks.ai/blog/rag-with-astro-fastapi-surrealdb-tailwind)
- [Building a (Very Simple) Vector Store from Scratch - LlamaIndex](https://docs.llamaindex.ai/en/stable/examples/low_level/vector_store/)

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/mastra

# Mastra

Use SurrealDB as the storage backend for Mastra agents, covering conversation memory, workflow snapshots, scores, observability spans, and native vector search.

[Mastra](https://mastra.ai) is a TypeScript framework for building AI agents, workflows, and RAG pipelines. [`@surrealdb/mastra-ai`](https://github.com/surrealdb/mastra-ai) provides `SurrealDBStore`, a storage adapter that backs Mastra with a single SurrealDB instance: conversation memory (threads, messages, and working memory), workflow suspend/resume snapshots, scores, observability spans, and [HNSW vector indexes](/docs/learn/data-models/vector-search/overview.md) for RAG.

Because SurrealDB is [multi-model](/docs/learn/data-models.md), one database covers everything a Mastra application persists. Message history, workflow state, and vector embeddings live in the same ACID-compliant engine, so there is no separate vector database to deploy or keep in sync.

> [!NOTE]
> This page covers the storage adapter, which runs against a SurrealDB instance you manage. The same package also integrates with [SurrealDB Agent Memory](/docs/agent-memory/integrations/frameworks/mastra.md), a hosted memory provider for fact extraction and semantic recall.

## Requirements

- [SurrealDB v3](/docs/running/installation.md), local or on [SurrealDB Cloud](/docs/operate/instances.md)
- Bun 1+ or Node.js 22+
- `@mastra/core` 1.31.0+

## Setup

Start SurrealDB locally, either [installed directly](/docs/running/installation.md):

```sh
surreal db start --user root --pass secret memory
```

or [with Docker](/docs/running/docker.md):

```sh
docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass secret
```

Alternatively, create a managed instance on [SurrealDB Cloud](/docs/operate/instances.md) and connect with its `wss://` URL.

## Install dependencies

```sh
bun add @surrealdb/mastra-ai
```

## Quick start

Create a store, pass it to `Mastra` as `storage`, and call `store.init()` to connect and apply the table schemas. The agent's conversation history then persists in SurrealDB, keyed by `resourceId` and `threadId`:

```typescript
import { Mastra } from "@mastra/core/mastra";
import { Agent } from "@mastra/core/agent";
import { anthropic } from "@ai-sdk/anthropic";
import { SurrealDBStore } from "@surrealdb/mastra-ai";

const store = new SurrealDBStore({
    id: "my-store",
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
    namespace: "mastra",
    database: "my_app",
});

const agent = new Agent({
    name: "assistant",
    instructions: "You are a helpful assistant.",
    model: anthropic("claude-sonnet-4-6"),
});

const mastra = new Mastra({
    agents: { assistant: agent },
    storage: store,
});

await store.init();

const response = await mastra.getAgent("assistant").generate("Hello!", {
    resourceId: "user-001",
    threadId: "thread-001",
});

console.log(response.text);
await store.close();
```

## Configuration

`SurrealDBStore` accepts three configuration shapes. `namespace` and `database` are optional in the first two and both default to `mastra`.

Username and password:

```typescript
new SurrealDBStore({
    id: "my-store",
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
    namespace: "mastra",
    database: "my_app",
});
```

Token authentication, for example against a SurrealDB Cloud instance:

```typescript
new SurrealDBStore({
    id: "my-store",
    url: "wss://cloud.surrealdb.com",
    token: "<your-jwt-token>",
    namespace: "mastra",
    database: "my_app",
});
```

A pre-connected `Surreal` instance from the [JavaScript SDK](/docs/reference/javascript.md), when your application already manages its own connection:

```typescript
import { Surreal } from "surrealdb";

const db = new Surreal();
await db.connect("ws://localhost:8000");

new SurrealDBStore({ id: "my-store", db });
```

## Workflow suspend and resume

Mastra workflows can suspend mid-run and resume later, for example to wait for human approval. With `SurrealDBStore` as storage, each snapshot is written atomically, so a run survives a process restart and resumes from the suspended step:

```typescript
import { Mastra } from "@mastra/core/mastra";
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { SurrealDBStore } from "@surrealdb/mastra-ai";
import { z } from "zod";

const store = new SurrealDBStore({
    id: "store",
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
});
const mastra = new Mastra({ storage: store });

const approveStep = createStep({
    id: "approve",
    inputSchema: z.object({ value: z.number() }),
    resumeSchema: z.object({ approved: z.boolean() }),
    outputSchema: z.object({ approved: z.boolean() }),
    execute: async ({ inputData, resumeData, suspend }) => {
        if (!resumeData) {
            await suspend({});
        }
        return { approved: resumeData!.approved };
    },
});

const workflow = createWorkflow({
    id: "approval",
    mastra,
    inputSchema: z.object({ value: z.number() }),
    outputSchema: z.object({ approved: z.boolean() }),
    steps: [approveStep],
}).then(approveStep).commit();

await store.init();

const run = workflow.createRun();
await run.start({ inputData: { value: 42 } });

await run.resume({
    step: approveStep,
    resumeData: { approved: true },
});

await store.close();
```

## Observational Memory

`SurrealDBStore` is a supported backend for Mastra's [Observational Memory](https://mastra.ai/docs/memory/observational-memory), the observer/reflector system in `@mastra/memory` that compresses long message histories into observations. [Memory extractors](https://mastra.ai/blog/introducing-memory-extractors) also work, pulling structured facts out of conversations during observation cycles, and extracted values persist through the same SurrealDB tables. Observational Memory requires `@mastra/memory` 1.1.0+, and extractors require 1.22.0+:

```typescript
import { Extractor, Memory } from "@mastra/memory";
import { SurrealDBStore } from "@surrealdb/mastra-ai";
import { z } from "zod";

const store = new SurrealDBStore({
    id: "om-store",
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
});
await store.init();

const memory = new Memory({
    storage: store,
    options: {
        observationalMemory: {
            model: "anthropic/claude-haiku-4-5",
            observation: {
                extract: [
                    new Extractor({
                        name: "User profile",
                        instructions: "Extract stable user profile facts.",
                        schema: z.object({
                            preferredName: z.string().optional(),
                            timezone: z.string().optional(),
                        }),
                    }),
                ],
            },
        },
    },
});
```

## Vector search

SurrealDB v3 includes native [HNSW vector indexes](/docs/learn/data-models/vector-search/overview.md), so the same database that stores agent memory also serves RAG queries. The package exposes `SurrealDBClient` for raw SurrealQL, letting you define a schema, upsert documents with embeddings, and run a k-nearest-neighbour search:

```typescript
import { SurrealDBClient } from "@surrealdb/mastra-ai";

const SCHEMA = `
DEFINE TABLE IF NOT EXISTS documents SCHEMAFULL;
DEFINE FIELD IF NOT EXISTS content   ON documents TYPE string;
DEFINE FIELD IF NOT EXISTS embedding ON documents TYPE array<float>;
DEFINE INDEX IF NOT EXISTS idx_hnsw
  ON documents FIELDS embedding HNSW DIMENSION 1536 DIST COSINE;
`;

const client = new SurrealDBClient({
    id: "rag",
    url: "ws://localhost:8000",
    username: "root",
    password: "secret",
});
await client.connect();
await client.execute(SCHEMA);

await client.execute(
    `UPSERT type::record('documents', $id) CONTENT $data`,
    { id: "doc-1", data: { content: "SurrealDB supports vector search.", embedding: [] } },
);

const results = await client.queryAll(
    `SELECT content, vector::distance::cosine(embedding, $qe) AS dist
     FROM documents WHERE embedding <|5,40|> $qe ORDER BY dist ASC`,
    { qe: [] },
);
```

## API

### `SurrealDBStore`

| Member | Description |
| ------ | ----------- |
| `init()` | Connect and apply all table schemas |
| `close()` | Disconnect |
| `client` | The underlying `SurrealDBClient` for raw queries |
| `stores` | Individual domain stores (`memory`, `workflows`, `scores`, `observability`) |

### `SurrealDBClient`

| Method | Description |
| ------ | ----------- |
| `connect(config?)` | Open the WebSocket connection |
| `close()` | Disconnect |
| `queryAll<T>(surql, bindings?)` | Run a query and return all rows |
| `queryOne<T>(surql, bindings?)` | Run a query and return the first row or `null` |
| `execute(surql, bindings?)` | Run a statement with no return value |
| `txBatch(statements, bindings?)` | Run statements in a single `BEGIN`/`COMMIT TRANSACTION` request |

## Next steps

The [repository](https://github.com/surrealdb/mastra-ai) includes runnable examples for each area:

- [basic-agent](https://github.com/surrealdb/mastra-ai/tree/main/examples/basic-agent): multi-turn agent conversation with SurrealDB memory
- [workflow-persistence](https://github.com/surrealdb/mastra-ai/tree/main/examples/workflow-persistence): suspend/resume workflow with snapshot storage
- [rag-pipeline](https://github.com/surrealdb/mastra-ai/tree/main/examples/rag-pipeline): vector similarity search with SurrealDB HNSW indexes
- [observational-memory](https://github.com/surrealdb/mastra-ai/tree/main/examples/observational-memory): Observational Memory and extractors on SurrealDB

For hosted memory with fact extraction and semantic recall, see the [SurrealDB Agent Memory integration for Mastra](/docs/agent-memory/integrations/frameworks/mastra.md).

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/overview

# AI framework integrations

This section contains information about the different frameworks that can be used to integrate with SurrealDB.

SurrealDB integrates with popular AI and data frameworks, so you can use features such as vector search, graph relationships, and structured data storage from within them. These integrations help you build applications that combine LLMs, agents, data pipelines and more, using tools and frameworks you already know.

<table style={{ width: '100%' }}>
    <thead>
        <tr>
            <th>Integration</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/agno.md">Agno</a></td>
            <td>Agno is a python framework for building multi-agent systems with shared memory, knowledge and reasoning.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/vercel/ai-sdk.md">AI SDK</a></td>
            <td>Vercel's TypeScript library for language and embedding models, with SurrealDB for vector search tools, graph tools and chat history.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/camel.md">Camel</a></td>
            <td>A Python framework for building multi-agent LLM systems with SurrealDB vector storage capabilities.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/cocoindex.md">CocoIndex</a></td>
            <td>An incremental indexing framework for AI agents with declarative SurrealDB table, relation, and vector targets.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/crewai.md">CrewAI</a></td>
            <td>A framework for orchestrating role-playing AI agents with SurrealDB for entity and short-term memory.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/dagster.md">Dagster</a></td>
            <td>A data orchestration framework with SurrealDB vector search integration for ML pipelines.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/vercel/eve.md">Eve</a></td>
            <td>Vercel's agent framework, with SurrealDB tools for your data and a SurrealDB memory provider.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/google-agent.md">Google Agent</a></td>
            <td>A framework for building and deploying intelligent agents in Google Cloud with SurrealDB vector storage for RAG.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/hermes.md">Hermes</a></td>
            <td>Nous Research's terminal agent, given a persistent filesystem in SurrealDB as a toolset and as a memory provider.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/kreuzberg.md">Kreuzberg</a></td>
            <td>A polyglot document intelligence framework to extract text, metadata, images, and structured information from documents (PDFs,images, etc.).</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/langchain.md">LangChain</a></td>
            <td>A framework for building LLM based applications.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/langgraph.md">LangGraph</a></td>
            <td>A TypeScript framework for stateful agents and graphs, with SurrealDB as the checkpointer, long-term memory store and node cache.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/llamaindex.md">Llama Index</a></td>
            <td>A framework for building RAG pipelines with SurrealDB's native HNSW vector index as the backing store.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/mastra.md">Mastra</a></td>
            <td>A TypeScript agent framework with SurrealDB as a storage backend for conversation memory, workflow snapshots, and vector search.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/pydantic-ai.md">Pydantic AI</a></td>
            <td>A Python framework designed to help you quickly, confidently, and painlessly build production grade applications and workflows with Generative AI.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/ai-frameworks/smolagents.md">Smol Agents</a></td>
            <td>A complete walkthrough for building a code-generating AI agent that recommends grocery items by querying SurrealDB's HNSW vector index.</td>
        </tr>
    </tbody>
</table>

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/pydantic-ai

# Pydantic AI

This section contains information about the Pydantic AI framework and how to integrate it with SurrealDB.

[Pydantic AI](https://ai.pydantic.dev) is a Python agent framework for building production-grade applications and workflows with Generative AI.

A Pydantic AI agent uses SurrealDB as its knowledge store through a tool: a function that the agent's model can call. The tool takes the model's search text, embeds it with the same model that embedded the stored records, runs a SurrealDB vector search, and returns the nearest records as text. This page shows those parts. The tutorial [Build an AI agent with Python](/docs/learn/tutorials/walkthroughs/build-an-ai-agent.md#getting-started-with-pydantic-ai) has the complete retrieval-augmented generation (RAG) program, which builds a search database from the Logfire documentation, and the commands that run it.

## Install

The example uses the Pydantic AI and SurrealDB Python packages, and an OpenAI API key for the embedding and chat models:

```bash
pip install pydantic-ai surrealdb
```

**Bash**

```bash
export OPENAI_API_KEY=your-api-key
```

**PowerShell**

```powershell
$env:OPENAI_API_KEY = "your-api-key"
```

## Models and the retrieval tool

An `Embedder` turns text into vectors and an `Agent` holds the chat model. The `@agent.tool_plain` decorator registers `retrieve()` as a tool, and its docstring tells the model what the tool does and what its argument means. This is the tool from the tutorial's program without its Logfire tracing.

```python
from pydantic_ai import Agent, Embedder

embedder = Embedder('openai:text-embedding-3-small')
agent = Agent('openai:gpt-5.2')


@agent.tool_plain
async def retrieve(search_query: str) -> str:
    """Retrieve documentation sections based on a search query.

    Args:
        search_query: The search query.
    """
    result = await embedder.embed_query(search_query)
    embedding_vector = result.embeddings[0]

    # SurrealDB vector search using the HNSW index
    async with database_connect(False) as db:
        rows = await query(
            db,
            """
            SELECT url, title, content, vector::distance::knn() AS dist
            FROM doc_sections
            WHERE embedding <|8, 40|> $vector
            ORDER BY dist ASC
            """,
            {'vector': list(embedding_vector)},
            RetrievalQueryResult,
        )

    return '\n\n'.join(
        f'# {row.title}\nDocumentation URL:{row.url}\n\n{row.content}' for row in rows
    )
```

`database_connect()` opens a connection to SurrealDB, embedded in a local file or to a server at a URL, and `query()` validates the records it returns as `RetrievalQueryResult` models. Both are defined in the full program in the tutorial.

The `<|8, 40|>` operator asks the HNSW index for the 8 nearest records, with 40 as the size of the candidate list it searches. `vector::distance::knn()` returns the distance that the operator already computed for each record.

## Schema

The vector index must have the dimension of the embedding model, which is 1536 for `text-embedding-3-small`:

```surql
DEFINE TABLE doc_sections SCHEMALESS;
DEFINE FIELD embedding ON doc_sections TYPE array<float>;
DEFINE INDEX hnsw_idx_doc_sections ON doc_sections
    FIELDS embedding HNSW DIMENSION 1536 DIST COSINE;
```

To use another embedding model, change the `Embedder` model string and the `DIMENSION` together. The records already stored must also be embedded again, because vectors from two different models cannot be compared.

## Run the agent

`agent.run_sync()` sends a question to the model, which calls `retrieve()` as often as it needs before it writes its answer. In async code, `await agent.run()` does the same. `agent.to_web()` returns a web chat application for the same agent.

```python
answer = agent.run_sync('How do I register a function as a custom tool for my agent?')
print(answer.output)
```

---

Source: https://surrealdb.com/docs/integrate/integrations/ai-frameworks/smolagents

# SmolAgents

A complete walkthrough for building a code-generating AI agent that recommends grocery items by querying SurrealDB's HNSW vector index.

In this guide you will build an agent that, given a natural-language shopping request, finds the most relevant grocery items in your database and returns them in a single reply.

## Install the dependencies

```bash
pip install smolagents surrealdb fastembed datasets
```

| Library        | Purpose                                |
| -------------- | -------------------------------------- |
| **surrealdb**  | Async Python SDK for SurrealDB         |
| **smolagents** | Code-generating agent framework        |
| **fastembed**  | Local Jina v2 embedding model (768-D)  |
| **datasets**   | Pulls the public *GroceryList* dataset |

## Create a SurrealDB "grocery search" tool

```python
from fastembed import TextEmbedding
from surrealdb import AsyncSurreal
from smolagents import Tool
from datasets import load_dataset
import asyncio, os
from typing import List, Dict, Any

class GroceryQueryTool(Tool):
    name = "surreal_grocery_search"
    description = "Semantic search over grocery items stored in SurrealDB."
    inputs = {
        "query": {
            "type": "string",
            "description": "A natural-language description of a grocery need.",
        }
    }
    output_type = "string"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Connection details
        self.uri = "ws://localhost:8000/rpc"
        self.ns = "demo"
        self.dbname = "demo"
        self.table = "groceries"
        self.user = os.getenv("SURREAL_USER", "root")
        self.pw = os.getenv("SURREAL_PASS", "secret")

        self.emb = TextEmbedding(model_name="jinaai/jina-embeddings-v2-base-en")

        # one-time async bootstrap
        asyncio.run(self._setup())

    async def _setup(self):
        """Connect, create schema, and ingest groceries if empty."""
        async with AsyncSurreal(self.uri) as db:
            await db.signin({"username": self.user, "password": self.pw})
            await db.use(self.ns, self.dbname)

            schema = """
            DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
            DEFINE FIELD item_name   ON $tb TYPE string;
            DEFINE FIELD category    ON $tb TYPE string;
            DEFINE FIELD description ON $tb TYPE string;
            DEFINE FIELD embedding   ON $tb TYPE array;

            DEFINE INDEX idx_hnsw ON $tb
              FIELDS embedding
              HNSW DIMENSION 768
              DIST   COSINE;
            """
            await db.query(schema, {"tb": self.table})

            # skip ingest if we already have rows
            existing = await db.query(f"SELECT count() FROM {self.table};")
            if existing[0]["result"][0]["count"] > 0:
                return

            print("🛒 Ingesting GroceryList dataset …")
            ds = load_dataset("AmirMohseni/GroceryList")["train"]  # 225 rows

            BATCH = 64
            items = ds["item"]
            cats = ds["category"]
            descs = [f"{it.capitalize()} is in the {cat} aisle." for it, cat in zip(items, cats)]

            for i in range(0, len(descs), BATCH):
                vecs = self.emb.query_embed(descs[i:i+BATCH])
                rows = [
                    {
                        "id": f"{self.table}:{i+j}",
                        "item_name": items[i+j],
                        "category": cats[i+j],
                        "description": descs[i+j],
                        "embedding": list(vec),
                    }
                    for j, vec in enumerate(vecs)
                ]
                await db.create(self.table, rows)

    async def _lookup(self, query_vec: List[float]) -> List[Dict[str, Any]]:
        """Perform vector search with proper connection management."""
        async with AsyncSurreal(self.uri) as db:
            await db.signin({"username": self.user, "password": self.pw})
            await db.use(self.ns, self.dbname)

            surql = """
            LET $q := $vec;
            SELECT item_name, category, description,
                   vector::distance::knn() AS dist
            FROM $tb
            WHERE embedding <|$k,$ef|> $q      -- top-k, efSearch
            ORDER BY dist;
            """
            result = await db.query(
                surql,
                {
                    "vec": query_vec,
                    "tb": self.table,
                    "k": 5,
                    "ef": 64
                }
            )
            return result[0]["result"]

    def forward(self, query: str) -> str:
        """Return the five closest grocery items."""
        q_vec = next(self.emb.query_embed(query))
        hits = asyncio.run(self._lookup(q_vec))

        return "Retrieved items:\n" + "".join(
            f"== {hit['item_name'].title()} ==\n"
            f"Category: {hit['category']}\n"
            f"{hit['description']}\n\n"
            for hit in hits
        )
```

---

Source: https://surrealdb.com/docs/integrate/integrations/authentication/better-auth/getting-started

# Getting started

Install the @surrealdb/better-auth adapter, connect to SurrealDB, configure the adapter, and generate your Better Auth schema.

This guide walks through installing the `@surrealdb/better-auth` adapter, connecting it to SurrealDB, and generating the schema Better Auth needs.

## Installation

Install the adapter alongside `better-auth` and the [SurrealDB JavaScript SDK](/docs/reference/javascript.md):

**Bun**

```bash
bun add @surrealdb/better-auth better-auth surrealdb
```

**npm**

```bash
npm install @surrealdb/better-auth better-auth surrealdb
```

**pnpm**

```bash
pnpm add @surrealdb/better-auth better-auth surrealdb
```

## Quick start

Connect a `Surreal` client, then pass it to `surrealAdapter` as the `database` option in your Better Auth configuration. Better Auth manages all table operations through the adapter.

```typescript
import { betterAuth } from 'better-auth';
import { Surreal } from 'surrealdb';
import { surrealAdapter } from '@surrealdb/better-auth';

const db = new Surreal();
await db.connect('ws://localhost:8000/rpc');
await db.use({ namespace: 'namespace', database: 'database' });

export const auth = betterAuth({
    database: surrealAdapter({ db }),
    emailAndPassword: { enabled: true },
});
```

## Connecting to SurrealDB

The adapter accepts any connected `Surreal` instance. Connect it before passing it to `surrealAdapter`. Use WebSocket for long-running servers and HTTP for stateless environments such as serverless functions.

```typescript
import { Surreal } from 'surrealdb';

const db = new Surreal();

// WebSocket (recommended for persistent servers)
await db.connect('ws://localhost:8000/rpc', {
    namespace: 'myapp',
    database: 'production',
    authentication: {
        username: 'root',
        password: 'secret',
    },
});

// HTTP (for stateless environments)
await db.connect('http://localhost:8000', {
    namespace: 'myapp',
    database: 'production',
});
```

For a full reference of connection options, see [Connecting to SurrealDB](/docs/reference/javascript/concepts/connecting-to-surrealdb.md) in the JavaScript SDK documentation.

## Configuration options

`surrealAdapter` accepts the following options:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `db` | `Surreal` | required | A connected SurrealDB client instance. |
| `usePlural` | `boolean` | `false` | Use plural table names (`users` instead of `user`). |
| `schemaMode` | `'schemafull' \| 'schemaless'` | `'schemafull'` | Table mode used by the generated schema. `schemaless` keeps known fields typed and indexed while still accepting writes to undeclared fields. |

```typescript
surrealAdapter({
    db,
    usePlural: true, // use plural table names
});
```

## Schema generation

The adapter includes a `createSchema` implementation that generates SurrealQL DDL statements for all Better Auth tables. Use the Better Auth CLI to produce a `schema.surql` file:

```bash
bunx @better-auth/cli generate --output schema.surql
```

Then apply it to your SurrealDB instance:

```bash
surreal db import --endpoint http://localhost:8000 \
    --ns myapp --db production \
    --user root --pass secret \
    schema.surql
```

The generated schema uses `SCHEMAFULL` tables by default. Each field is typed from the Better Auth schema:

- Required fields take a concrete type (`string`, `datetime`, `bool`, and so on).
- Optional fields use `option<T | null>`, so they accept a typed value, a stored `NULL`, or a missing value.
- Object fields use `TYPE object FLEXIBLE` so nested objects can hold arbitrary keys.
- `DEFINE INDEX` statements are emitted for unique fields and for fields Better Auth marks as indexed.

Every statement uses `IF NOT EXISTS`, so the file is safe to reapply.

> [!NOTE]
> If your app adds many dynamic plugin fields and you would rather not regenerate the schema each time, set `schemaMode: 'schemaless'`. Known fields stay typed and indexed, and writes to undeclared fields are accepted.

## Table names

By default the adapter uses singular table names: `user`, `session`, `verification`, and `account`. Set `usePlural: true` to use plural names instead.

Better Auth also lets you override model names per-table via the `modelName` option in your configuration, and the adapter respects those overrides automatically.

## Next steps

- [Overview](/docs/integrate/integrations/authentication/better-auth/overview.md): adapter capabilities and prerequisites
- [Plugins](/docs/integrate/integrations/authentication/better-auth/plugins.md): use any Better Auth plugin and the SurrealQL helper functions generated for the organisation plugin.
- [Transactions & limitations](/docs/integrate/integrations/authentication/better-auth/transactions-and-limitations.md): how transactions behave and what to be aware of.

---

Source: https://surrealdb.com/docs/integrate/integrations/authentication/better-auth/overview

# Better Auth

Use SurrealDB as the database behind Better Auth with the @surrealdb/better-auth adapter, including schema generation, transactions, and support for all Better Auth plugins.

[Better Auth](https://better-auth.com) is a comprehensive, framework-agnostic authentication and authorisation library for TypeScript. The `@surrealdb/better-auth` adapter lets you use SurrealDB as the database behind Better Auth: you pass it a single connected [`Surreal`](/docs/reference/javascript.md) client and Better Auth manages all of its table operations through the adapter.

The adapter supports schema generation, transactions, the full set of Better Auth WHERE operators, and every Better Auth plugin.

> [!NOTE]
> This section covers the **Better Auth** integration only. For SurrealDB's own sign-in, tokens, and permissions model, see [Security](/docs/learn/security.md).

> [!NOTE]
> The `@surrealdb/better-auth` adapter works with SurrealDB versions `v3.1.0` and later.

## Prerequisites

- SurrealDB 3.1 or later
- Better Auth 1.6.x
- Node.js 18+ or Bun 1.x

## Feature support

The adapter advertises the following capabilities to Better Auth:

| Capability | Supported |
|------------|-----------|
| JSON / object fields | Yes |
| Dates | Yes |
| Booleans | Yes |
| Arrays | Yes |

## Identifiers

By default, Better Auth generates string identifiers in JavaScript. The adapter stores them as SurrealDB [record IDs](/docs/reference/query-language/language-primitives/data-types/record-ids.md) and deserialises them back to strings when reading, so a record round-trips to your application as the plain string `id`.

UUIDs are also supported. Enable them in your Better Auth configuration:

```typescript
betterAuth({
    database: surrealAdapter({ db }),
    advanced: { database: { generateId: 'uuid' } },
});
```

Better Auth generates the UUID in JavaScript and passes it to the adapter, which stores and reads it transparently (it round-trips as the plain UUID string). SurrealDB does not mint the UUID natively, which is why the adapter reports `supportsUUIDs: false` to Better Auth: that flag means "the database generates UUIDs itself", not "UUIDs are unsupported".

Numeric (auto-increment) identifiers are not supported.

## In this section

- [Getting started](/docs/integrate/integrations/authentication/better-auth/getting-started.md) - Install the adapter, connect to SurrealDB, configure options, and generate your schema.

- [Plugins](/docs/integrate/integrations/authentication/better-auth/plugins.md) - Use any Better Auth plugin and call the SurrealQL helper functions generated for the organisation plugin.

- [Transactions & limitations](/docs/integrate/integrations/authentication/better-auth/transactions-and-limitations.md) - How transactions behave and the current limitations to be aware of.

## Sources

- [GitHub repository](https://github.com/surrealdb/better-auth)
- [npm package](https://www.npmjs.com/package/@surrealdb/better-auth)
- [Better Auth documentation](https://better-auth.com)

---

Source: https://surrealdb.com/docs/integrate/integrations/authentication/better-auth/plugins

# Plugins

Use any Better Auth plugin with the SurrealDB adapter and call the SurrealQL helper functions generated for the organisation plugin.

The `@surrealdb/better-auth` adapter works with all Better Auth plugins. Pass them in the `plugins` array of your Better Auth configuration:

```typescript
import { betterAuth } from 'better-auth';
import { organization } from 'better-auth/plugins/organization';
import { twoFactor } from 'better-auth/plugins/two-factor';
import { admin } from 'better-auth/plugins/admin';
import { Surreal } from 'surrealdb';
import { surrealAdapter } from '@surrealdb/better-auth';

const db = new Surreal();
await db.connect('ws://localhost:8000/rpc');
await db.use({ namespace: 'myapp', database: 'production' });

export const auth = betterAuth({
    database: surrealAdapter({ db }),
    plugins: [
        organization(),
        twoFactor(),
        admin(),
    ],
});
```

A wider example combining several plugins:

```typescript
import { betterAuth } from 'better-auth';
import { admin } from 'better-auth/plugins/admin';
import { anonymous } from 'better-auth/plugins/anonymous';
import { bearer } from 'better-auth/plugins/bearer';
import { magicLink } from 'better-auth/plugins/magic-link';
import { multiSession } from 'better-auth/plugins/multi-session';
import { organization } from 'better-auth/plugins/organization';
import { twoFactor } from 'better-auth/plugins/two-factor';
import { username } from 'better-auth/plugins/username';
import { Surreal } from 'surrealdb';
import { surrealAdapter } from '@surrealdb/better-auth';

const db = new Surreal();
await db.connect('ws://localhost:8000/rpc');
await db.use({ namespace: 'myapp', database: 'production' });

export const auth = betterAuth({
    secret: process.env.BETTER_AUTH_SECRET!,
    baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:3000',
    emailAndPassword: { enabled: true },
    database: surrealAdapter({ db }),
    plugins: [
        organization({
            teams: { enabled: true },
            dynamicAccessControl: { enabled: true },
        }),
        twoFactor(),
        admin(),
        bearer(),
        username(),
        magicLink({
            sendMagicLink: async ({ email, url }) => {
                // send an email containing the magic link url
            },
        }),
        anonymous(),
        multiSession(),
    ],
});
```

> [!IMPORTANT]
> Each plugin may add new tables. Re-run [schema generation](/docs/integrate/integrations/authentication/better-auth/getting-started.md#schema-generation) after adding plugins to produce the updated DDL, or use `schemaMode: 'schemaless'` to accept the new fields without regenerating.

## SurrealDB helper functions

When you use the `organization` plugin (with or without the `teams` option), schema generation also emits a set of `fn::*` SurrealQL functions you can call directly in your own queries, [rules, and permissions](/docs/reference/query-language/statements/define/table.md#defining-permissions). These functions are defined with `IF NOT EXISTS`, so re-running the generated schema is safe.

### `fn::auth::organization::*`

These functions are emitted when the `organization` plugin is active.

| Function | Signature | Returns | Description |
|---|---|---|---|
| `fn::auth::organization::member_of` | `(userId: string, organizationId: string)` | `bool` | True if the user is a member of the organisation. |
| `fn::auth::organization::get_role` | `(userId: string, organizationId: string)` | `option<string>` | The member's role (`"owner"`, `"admin"`, `"member"`), or `NONE` if not a member. |
| `fn::auth::organization::has_role` | `(userId: string, organizationId: string, minRole: string)` | `bool` | True if the user's role is equal to or senior to `minRole` (owner > admin > member). |
| `fn::auth::organization::members` | `(organizationId: string)` | `array` | All `members` records for the organisation. |
| `fn::auth::organization::teams` | `(organizationId: string)` | `array` | All `teams` records for the organisation (requires `teams: { enabled: true }`). |
| `fn::auth::organization::has_permission` | `(userId: string, organizationId: string, resource: string, action: string)` | `bool` | True if the user's role has a custom permission for the given resource and action (requires `dynamicAccessControl`). |

```surql
-- Check if a user belongs to an organisation
IF fn::auth::organization::member_of($userId, $organizationId) {
    -- allow access
};

-- Require at least admin-level access
IF fn::auth::organization::has_role($userId, $organizationId, "admin") {
    -- perform a privileged operation
};

-- Get a user's role string
LET $role = fn::auth::organization::get_role($userId, $organizationId);

-- List all members
LET $members = fn::auth::organization::members($organizationId);
```

### `fn::auth::team::*`

These functions are emitted when `teams: { enabled: true }` is set on the `organization` plugin.

| Function | Signature | Returns | Description |
|---|---|---|---|
| `fn::auth::team::member_of` | `(userId: string, teamId: string)` | `bool` | True if the user is a member of the team. |
| `fn::auth::team::members` | `(teamId: string)` | `array` | All `teamMembers` records for the team. |

```surql
-- Check team membership
IF fn::auth::team::member_of($userId, $teamId) {
    -- allow team-scoped access
};

-- List all team members
LET $members = fn::auth::team::members($teamId);
```

---

Source: https://surrealdb.com/docs/integrate/integrations/authentication/better-auth/transactions-and-limitations

# Transactions & limitations

How the @surrealdb/better-auth adapter handles transactions, and the current limitations to be aware of.

The `@surrealdb/better-auth` adapter uses transactions internally, and exposes them for operations you want to group yourself. This page covers that behaviour and the limitations that come with it.

## Transactions

Transaction support is built in. Better Auth uses transactions internally for operations that need atomicity (for example, creating a session alongside a new user record), so most applications never call the transaction API directly.

If you need manual transaction access, call `transaction` on the adapter. Operations run inside the callback are committed together when it resolves, or discarded if it throws.

```typescript
const adapter = surrealAdapter({ db })(options);

await adapter.transaction(async (trx) => {
    await trx.create({ model: 'user', data: { /* ... */ } });
    await trx.create({ model: 'session', data: { /* ... */ } });
});
```

Transactions are backed by [`SurrealDB.beginTransaction()`](/docs/reference/query-language/statements/begin.md). If any operation inside the callback throws, the transaction is cancelled and changes are discarded.

`beginTransaction()` needs a WebSocket connection, so connect the `db` that you give the adapter with a `ws://` or `wss://` URL. Over HTTP, `beginTransaction()` throws `UnsupportedFeatureError`, and every Better Auth operation that uses a transaction fails, such as signing up a user. On Cloudflare Workers, open the connection inside each request. See [Cloudflare Workers](/docs/learn/querying/concepts-and-guides/connecting-from-serverless-and-edge.md#cloudflare-workers).

## Limitations

Keep the following in mind when adopting the adapter.

### Version coupling

The adapter targets **Better Auth 1.6.x** and **SurrealDB 3.1+**. Other major versions of either dependency are not supported.

### Numeric identifiers are not supported

By default Better Auth uses string identifiers, and [UUIDs](/docs/integrate/integrations/authentication/better-auth/overview.md#identifiers) can be enabled in your Better Auth configuration. Numeric (auto-increment) identifier strategies are **not** supported, because SurrealDB does not generate them natively and the adapter has no JavaScript fallback for them.

### `SCHEMAFULL` schemas require regeneration

With the default `schemaMode: 'schemafull'`, writes to fields that are not in the generated schema are rejected. Whenever you add a plugin or otherwise introduce new fields, [regenerate and reapply the schema](/docs/integrate/integrations/authentication/better-auth/getting-started.md#schema-generation). If you would rather not regenerate each time, set `schemaMode: 'schemaless'`; known fields stay typed and indexed, and writes to undeclared fields are accepted.

### Transaction rollback is best-effort

SurrealDB's `cancel()` is not honoured in every setup (for example, the in-memory engine). To keep rollback reliable, the adapter compensates by deleting records it created inside a failed transaction. This covers records created during the transaction; it does not restore prior values for records that were updated or deleted within it.

### Value deserialisation

When reading records, the adapter converts SurrealDB types back to JavaScript values: a `datetime` becomes a JavaScript `Date`, and a `RecordId` becomes its string `id`. Bear this in mind if you query the underlying tables directly rather than through Better Auth.

---

Source: https://surrealdb.com/docs/integrate/integrations/backend-platforms/encore

# Encore

Build and verify an AI agent memory service with Encore APIs, Pub/Sub and scheduled jobs around SurrealDB vector and graph queries.

[Encore](https://encore.dev/) is a platform that lets engineers and their agents build and verify complete backends using type-safe APIs and infrastructure primitives defined in application code, backed by local infrastructure during development and managed services in their AWS or GCP account when deployed. In this guide, those primitives define and connect the APIs, Pub/Sub ingestion, and scheduled retention workflow around SurrealDB's vector and graph capabilities.

The example application stores durable memory for AI agents. Each memory contains text and a vector embedding, with graph relationships connecting it to the entities it mentions. Memories are written asynchronously through Pub/Sub, recalled through vector similarity or graph traversal, and removed by a scheduled retention job.

## Run the example

You need the [Encore CLI](https://encore.dev/docs/install), Docker and Node.js 22 or later.

> [!TIP]
> Using a coding agent? Copy the prompt below to skip the manual setup.

```text
Set up and run the Encore and SurrealDB agent memory example. First check whether the Encore CLI is installed and, if needed, follow https://encore.dev/docs/install. Then run `encore app create agent-memory --example=ts/surrealdb-agent-memory`, follow the example README to start SurrealDB and the Encore application locally, verify that storing and recalling a memory works, and run `encore check` and `encore test`.
```

Start a local SurrealDB 3.3 instance:

```bash
docker run --rm --name encore-surrealdb-memory \
  -p 8000:8000 \
  surrealdb/surrealdb:v3.3.0 \
  start --user root --pass secret memory
```

This starts a temporary SurrealDB instance at `http://localhost:8000`. Its data is discarded when the container stops.

In another terminal, create and run the example application:

```bash
encore app create agent-memory --example=ts/surrealdb-agent-memory
cd agent-memory
npm install
encore run
```

Encore starts the APIs and local Pub/Sub and cron infrastructure. The application connects to the SurrealDB container as `root` with the password `secret`.

## How the integration works

The `remember` API accepts memory text, its embedding, extracted entity names and an optional expiry time. It publishes the request to an at-least-once Encore Pub/Sub topic, whose subscriber writes the memory and its `mentions` relationships to SurrealDB.

The API, topic and subscriber are defined together in the application code, allowing Encore to connect the ingestion flow locally and provision it using the corresponding managed services when deployed:

```typescript
import { randomUUID } from "node:crypto";
import { api } from "encore.dev/api";
import { CronJob } from "encore.dev/cron";
import { Subscription, Topic } from "encore.dev/pubsub";

const memoriesToStore = new Topic<MemoryEvent>("memories-to-store", {
    deliveryGuarantee: "at-least-once",
});

export const remember = api(
    { expose: true, method: "POST", path: "/agents/:agentID/memories" },
    async (params: RememberParams): Promise<{ memoryID: string; status: string }> => {
        const memoryID = `m_${randomUUID().replaceAll("-", "")}`;
        await memoriesToStore.publish({
            ...params,
            memoryID,
            entities: normalizeEntities(params.entities ?? []),
        });
        return { memoryID, status: "queued" };
    },
);

new Subscription(memoriesToStore, "store-memory-in-surrealdb", {
    handler: async (event) => storeMemory(await getSurreal(), event),
});
```

Stable record and relationship IDs make this write safe to repeat if Pub/Sub retries an event. Recall can then combine an HNSW vector search with graph traversal in one SurrealQL query:

```surql notest
SELECT id, text, created_at, expires_at,
       vector::distance::knn() AS distance,
       ->mentions->entity.name AS entities
FROM memory
WHERE embedding <|10, 100|> $embedding
  AND agent_id = $agent_id
  AND (expires_at = NONE OR expires_at > time::now())
ORDER BY distance
LIMIT $limit;
```

An Encore cron job calls the retention API every 24 hours to delete expired memories:

```typescript
export const pruneExpired = api(
    { expose: true, method: "POST", path: "/memories/prune" },
    async (): Promise<{ deleted: number }> => ({
        deleted: await pruneExpiredMemories(await getSurreal()),
    }),
);

new CronJob("prune-agent-memory", {
    title: "Remove expired agent memories",
    every: "24h",
    endpoint: pruneExpired,
});
```

The [complete example](https://github.com/encoredev/examples/tree/main/ts/surrealdb-agent-memory) contains the remaining API definitions, retry-safe transaction, schema and tests.

## Store and recall a memory

Store a memory for an agent:

```bash
curl -X POST http://localhost:4000/agents/research-agent/memories \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "SurrealDB stores vector and graph context for the agent.",
    "embedding": [0.94, 0.06, 0, 0, 0, 0, 0, 0],
    "entities": ["SurrealDB", "Encore"]
  }'
```

The API returns a generated `memoryID` and the status `queued`. Once the subscriber has written the event, recall the nearest memories:

```bash
curl -X POST http://localhost:4000/agents/research-agent/recall \
  -H 'Content-Type: application/json' \
  -d '{
    "embedding": [0.95, 0.05, 0, 0, 0, 0, 0, 0],
    "limit": 5
  }'
```

The example uses eight-dimensional vectors to keep requests readable. Change both `EMBEDDING_DIMENSIONS` and the HNSW index dimension before connecting a production embedding model.

Run the checks and tests with:

```bash
encore check
encore test
```

## Connect to SurrealDB Cloud

Set the SurrealDB endpoint and database token as Encore secrets before deploying the application:

```bash
encore secret set --type dev,prod SurrealDBURL
encore secret set --type dev,prod SurrealDBToken
```

`SurrealDBToken` must be a database token with access to the `encore` namespace and `agent_memory` database. A personal access token beginning with `sdbp_` authenticates the SurrealDB Cloud control plane and cannot be used as the application's database token.

## Resources

- [Complete Encore and SurrealDB example](https://github.com/encoredev/examples/tree/main/ts/surrealdb-agent-memory)
- [SurrealDB JavaScript SDK](/docs/reference/javascript.md)
- [Vector indexes](/docs/learn/data-models/vector-search/vector-indexes.md)
- [Encore infrastructure primitives](https://encore.dev/docs/ts/primitives)

---

Source: https://surrealdb.com/docs/integrate/integrations/data-management/airbyte

# Airbyte

The Airbyte connector allows you to sync data to SurrealDB from hundreds of sources.

This guide helps you configure SurrealDB as a destination in [Airbyte](https://airbyte.com) using the [official connector](https://github.com/surrealdb/airbyte-connector).

## Prerequisites
To connect SurrealDB to Airbyte, you need the following:

- An Airbyte deployment with access to the SurrealDB destination connector.
- SurrealDB `v2.2.0` or later.
- A SurrealDB instance (self-hosted or [SurrealDB Cloud](https://studio.surrealdb.com/cloud)) reachable by Airbyte.
- Ensure your SurrealDB database can be accessed by Airbyte. If your database is within a VPC, you may need to allow access from the IP you're using to expose Airbyte.
- A token or user credentials with [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md), [`DEFINE INDEX`](/docs/reference/query-language/statements/define/indexes.md), [`UPSERT`](/docs/reference/query-language/statements/upsert.md), [`SELECT`](/docs/reference/query-language/statements/select.md), and [`REMOVE`](/docs/reference/query-language/statements/remove.md) permissions.

## Setup instructions

Follow these steps to configure SurrealDB as a destination. You can use either a self-hosted instance or SurrealDB Cloud .

Before proceeding, ensure you have the endpoint URL and credentials for your SurrealDB instance and that Airbyte can reach it over the network.

### Option 1: Self-hosted SurrealDB

1. Ensure your SurrealDB instance is reachable from Airbyte. This might involve opening network access or configuring an SSH tunnel.
2. Create a dedicated user or token in SurrealDB, for example:

```surql
DEFINE USER airbyte ON ROOT PASSWORD "YourPassword" ROLES OWNER;
```

Use the generated credentials when setting up the destination.

### Option 2: SurrealDB Cloud

1. Visit the [Instances page](https://studio.surrealdb.com/cloud/instances) and select your instance.
2. Click **Connect with Surreal CLI** to obtain a connection command containing the `--endpoint` and authentication details.
3. Verify you can connect using `surreal db sql` with those parameters.

## Finish Airbyte configuration

1. Open the Airbyte dashboard and add a new **Destination**.
2. Select **SurrealDB** from the list of destination types.
3. Provide the host, port, namespace, database, and either the username/password or token you created earlier.
4. Click **Set up destination** and run the connection test.

Upon a successful test, you can start syncing data from your sources into SurrealDB tables. Each stream will be output into its own table in SurrealDB. Each table will contain 3 fields:

- `_airbyte_raw_id`: a uuid assigned by Airbyte to each event that is processed. The field type in SurrealDB is string. The connector uses this as the ID of each record in the destination SurrealDB table.
- `_airbyte_extracted_at`: a timestamp representing when the event was pulled from the data source. The field type in SurrealDB is datetime.
- `_airbyte_data`: a JSON blob holding the event data. The field type in SurrealDB is object.

## Known limitations
SurrealDB destination forces all identifier (table, schema and columns) names to be lowercase.

## Related links

- [Airbyte destination documentation](https://github.com/surrealdb/airbyte-connector)
- [Connect to airbyte via a dev container](https://github.com/surrealdb/airbyte-connector/blob/main/devcontainer.md)

---

Source: https://surrealdb.com/docs/integrate/integrations/data-management/fivetran

# Fivetran

The Fivetran integration for SurrealDB allows you to sync data from Fivetran to SurrealDB.

This guide will help you connect SurrealDB to Fivetran. The Fivetran integration is available through their [partner-built program](https://fivetran.com/docs/partner-built-program). For support with self-hosted SurrealDB destinations, please contact [SurrealDB Support](/contact). For SurrealDB Cloud related questions, reach out to [SurrealDB Cloud Support](/docs/operate/organisations/support.md).

## Prerequisites
To connect SurrealDB to Fivetran, you need the following:

- A Fivetran role with the [Create Destinations or Manage Destinations](https://fivetran.com/docs/using-fivetran/fivetran-dashboard/account-settings/role-based-access-control#rbacpermissions) permissions.
- A SurrealDB token.
- A SurrealDB instance (self-hosted or Cloud) that is accessible by Fivetran.

## Setup instructions

Follow these steps to set up SurrealDB as a destination in Fivetran. You have two options: self-hosted SurrealDB or SurrealDB Cloud .

Before proceeding with either option, ensure you have:

- Access to your SurrealDB instance with appropriate permissions
- The necessary connection details (endpoint URL, credentials)
- Network connectivity between Fivetran and your SurrealDB instance

### Option 1: Self-hosted SurrealDB

1. For self-hosted SurrealDB, ensure your SurrealDB instance is accessible by Fivetran according to your Fivetran deployment:
   - For [Fivetran SaaS Deployment](https://fivetran.com/docs/deployment-models/saas-deployment), ensure your SurrealDB is accessible via Internet.
   - For [Fivetran Hybrid Deployment](https://fivetran.com/docs/deployment-models/hybrid-deployment), ensure your SurrealDB is accessible by the Fivetran Hybrid Deployment Agent.
   - For [Fivetran Self-Hosted Deployment](https://fivetran.com/docs/deployment-models/self-hosted-deployment), ensure your SurrealDB is accessible by the Fivetran HVR Agent.
2. Set up the token and use it following [SurrealDB's Authentication documentation](/docs/learn/security/authentication/users.md#token).

### Option 2: SurrealDB Cloud

1. Ensure your SurrealDB instance is up and running and accessible via Internet.
2. Browse the [Instances page](https://studio.surrealdb.com/cloud/instances) and select your chosen instance.
3. Click **Connect with Surreal CLI** and locate the `surreal db sql --endpoint wss://YOUR_INSTANCE_HOSTNAME --token YOUR_TOKEN` command.
4. Run the command, and set up your own [`ACCESS`](/docs/reference/query-language/statements/define/access.md) or [`USER`](/docs/reference/query-language/statements/define/user.md). The example below works for testing purposes:

    ```surql
    USE NS your_ns;
    USE DB your_db;
    DEFINE USER your_user ON DATABASE PASSWORD "YourPassword" ROLES OWNER;
    ```

5. Ensure the user/pass is working by running:

    ```bash
    surreal db sql --endpoint wss://YOUR_INSTANCE_HOSTNAME --user your_user --pass YourPassword --ns your_ns --db your_db
    ```

6. Make a note of the `endpoint`, `user`, and `pass` parameters. You will need them to configure Fivetran.

7. (Optional) If you prefer using `token`, we recommend `DEFINE ACCESS ... TYPE JWT`. Refer to the [`DEFINE ACCESS > JWT` documentation](/docs/reference/query-language/statements/define/access/jwt.md) to set up JWT access.

    - Verify if the token is working before proceeding to the next section, by running:
    ```bash
    surreal db sql --endpoint wss://YOUR_INSTANCE_HOSTNAME --token your_token --ns your_ns --db your_db
    ```

## Finish Fivetran configuration

1. Log in to your [Fivetran account](https://fivetran.com/login).
2. Go to the **Destinations** page and click **Add destination**.
3. Enter a **Destination name** of your choice.
4. Click **Add**.
5. Select **SurrealDB** as the destination type.
6. Enter the `url`, `user` and `pass` (or `token`) you verified in the previous step.

> [!NOTE]
> The `url` setting corresponds to the `endpoint` parameter you verified in the previous step.

7. Click **Save & Test**.

Fivetran [tests and validates](https://fivetran.com/docs/destinations/surrealdb#setup-tests) the SurrealDB connection. Upon successfully completing the setup tests, you can sync your data using Fivetran connectors to the SurrealDB destination.

In addition, Fivetran automatically configures a [Fivetran Platform Connector](https://fivetran.com/docs/logs/fivetran-platform) to transfer the connector logs and account metadata to a schema in this destination. The Fivetran Platform Connector enables you to monitor your connectors, track your usage, and audit changes. The connector sends all these details at the destination level.

> [!IMPORTANT]
> If you are an Account Administrator, you can manually add the Fivetran Platform Connector on an account level so that it syncs all the metadata and logs for all the destinations in your account to a single destination. If an account-level Fivetran Platform Connector is already configured in a destination in your Fivetran account, then we don't add destination-level Fivetran Platform Connectors to the new destinations you create.

## Setup tests

Fivetran performs the following SurrealDB connection tests:

- The Database Connection test checks if we can connect to your SurrealDB database using the provided URL and token.

The test should complete in a few seconds if your Fivetran deployment can access the target SurrealDB instance.

## Related articles

- [Destination Overview](https://fivetran.com/docs/destinations/surrealdb)

- [API Destination Configuration](https://fivetran.com/docs/rest-api/api-reference/destinations/create-destination?service=surrealdb_destination)

- [Documentation Home](/docs)

---

Source: https://surrealdb.com/docs/integrate/integrations/data-management/n8n

# n8n

The official n8n node for SurrealDB. It provides both action and tool nodes to interact with a SurrealDB database, allowing you to create, read, update, and delete records, as well as execute custom SurrealQL queries.

This guide shows how to integrate SurrealDB with [n8n](https://n8n.io/), a [fair-code licensed](https://docs.n8n.io/reference/license/) workflow automation platform.

The SurrealDB node is the official n8n node for SurrealDB. It provides both action and tool nodes to interact with a SurrealDB database, allowing you to create, read, update, and delete records, as well as execute custom SurrealQL queries. It is available in the [n8n Community Nodes](https://docs.n8n.io/integrations/community-nodes/) repository.

> [!IMPORTANT]
> As with all community nodes, this node works only with self-hosted n8n instances, not with n8n Cloud. This node has been tested with SurrealDB `v2.x`

## Features

- **Dual Node Types**: Functions as both an action node and a tool node for AI workflows
- **Complete CRUD Operations**: Create, read, update, and delete SurrealDB records
- **Custom Queries**: Execute any SurrealQL query with full parameter support
- **Enhanced query builder**: Visual interface for building `SELECT` queries with `WHERE`, `ORDER BY`, `GROUP BY`, and other clauses
- **Table Operations**: List fields and explore table structure
- **Relationship Support**: Query and manage record relationships
- **Native Data Format**: Works with SurrealDB's native data formats
- **Connection Pooling**: Configurable connection pooling for improved performance and resource management
- **Enhanced error handling**: Comprehensive error classification, automatic retry logic, and connection recovery
    - **Intelligent Recovery**: Different error handling strategies for different operation types
    - **Detailed Error Reporting**: Rich error context with categorization and severity levels
- **Pool Monitoring**: Built-in pool statistics and performance monitoring

## Prerequisites

1. You need a self-hosted n8n instance (`v0.214.0` or later recommended).
2. You need access to a SurrealDB instance (`2.0.0` or later recommended).

## Installation steps

1. Open your n8n instance
2. Go to **Settings** > **Community Nodes**
3. Click **Install**
4. Enter `@surrealdb/n8n-nodes-surrealdb` and click **Install**
5. Restart your n8n instance if prompted

> [!NOTE]
> To use this node as a tool in AI workflows, you must set the environment variable `N8N_COMMUNITY_PACKAGES_ALLOW_TOOL_USAGE=true`.

## Configuration

In order to use SurrealDB in n8n, you need to configure the SurrealDB node.

### Credentials

To use the SurrealDB node, you need to create credentials with the following properties:

<table>
  <thead>
    <tr>
      <th>Property</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Connection String</strong></td>
      <td>The connection string to your SurrealDB instance (must start with <code>http://</code> or <code>https://</code>). WebSocket connections (<code>ws://</code> or <code>wss://</code>) are not supported.</td>
    </tr>
    <tr>
      <td><strong>Authentication</strong></td>
      <td>Choose the authentication scope:</td>
    </tr>
    <tr>
      <td><strong>Root</strong></td>
      <td>Full access to all namespaces and databases</td>
    </tr>
    <tr>
      <td><strong>Namespace</strong></td>
      <td>Access limited to a specific namespace</td>
    </tr>
    <tr>
      <td><strong>Database</strong></td>
      <td>Access limited to a specific database within a namespace</td>
    </tr>
    <tr>
      <td><strong>Username</strong></td>
      <td>Username for authentication</td>
    </tr>
    <tr>
      <td><strong>Password</strong></td>
      <td>Password for authentication</td>
    </tr>
    <tr>
      <td><strong>Namespace</strong></td>
      <td>Target namespace (required for Namespace and Database authentication)</td>
    </tr>
    <tr>
      <td><strong>Database</strong></td>
      <td>Target database (required for Database authentication)</td>
    </tr>
  </tbody>
</table>

The authentication type you choose affects how namespace and database information is handled. Depending on the authentication type, you will need to provide different information. See the table below for more details.

<table>
  <thead>
    <tr>
      <th>Authentication Type</th>
      <th>Access Scope</th>
      <th>Required Fields</th>
      <th>Optional Fields</th>
      <th>Override Capability</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Root Authentication</strong></td>
      <td>All namespaces and databases</td>
      <td>None</td>
      <td>Namespace, Database</td>
      <td>Can override namespace/database at node level</td>
    </tr>
    <tr>
      <td><strong>Namespace Authentication</strong></td>
      <td>All databases within a specific namespace</td>
      <td>Namespace</td>
      <td>Database</td>
      <td>Can override database at node level</td>
    </tr>
    <tr>
      <td><strong>Database Authentication</strong></td>
      <td>Specific database within a specific namespace</td>
      <td>Namespace, Database</td>
      <td>None</td>
      <td>Can override both at node level for specific operations</td>
    </tr>
  </tbody>
</table>

### Node-level namespace and database overrides

For most operations, you can override the namespace and database settings from your credentials:

1. In the node configuration, expand the **Options** section
2. Enter values in the **Namespace** and/or **Database** fields
3. These values will take precedence over the credential settings for that specific operation
4. You will be required to provide a namespace when using Namespace authentication
5. You will be required to provide both a namespace and database when using Database authentication

## Operations

The SurrealDB node provides operations organised by resource type. For anything not covered, you can use the **Execute Query** operation.

<table>
  <thead>
    <tr>
      <th>Category</th>
      <th>Operation</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="5"><strong>Record Operations</strong></td>
      <td><strong>Create Record</strong></td>
      <td>Create a single record in a table</td>
    </tr>
    <tr>
      <td><strong>Get Record</strong></td>
      <td>Retrieve a specific record by ID</td>
    </tr>
    <tr>
      <td><strong>Update Record</strong></td>
      <td>Update a specific record by ID</td>
    </tr>
    <tr>
      <td><strong>Upsert Record</strong></td>
      <td>Create or update a record (insert if not exists, update if exists)</td>
    </tr>
    <tr>
      <td><strong>Delete Record</strong></td>
      <td>Delete a specific record by ID</td>
    </tr>
    <tr>
      <td rowspan="9"><strong>Table Operations</strong></td>
      <td><strong>Get All Records</strong></td>
      <td>Retrieve all records from a table</td>
    </tr>
    <tr>
      <td><strong>Create Many</strong></td>
      <td>Create multiple records in a table</td>
    </tr>
    <tr>
      <td><strong>Get Many</strong></td>
      <td>Retrieve multiple records by IDs</td>
    </tr>
    <tr>
      <td><strong>Update All Records</strong></td>
      <td>Update all records in a table</td>
    </tr>
    <tr>
      <td><strong>Delete All Records</strong></td>
      <td>Delete all records from a table</td>
    </tr>
    <tr>
      <td><strong>Merge All Records</strong></td>
      <td>Merge the same data into all records in a table</td>
    </tr>
    <tr>
      <td><strong>Create Table</strong></td>
      <td>Define a new table with optional schema</td>
    </tr>
    <tr>
      <td><strong>Delete Table</strong></td>
      <td>Remove a table from the database</td>
    </tr>
    <tr>
      <td><strong>Get Table</strong></td>
      <td>Retrieve information about a table</td>
    </tr>
    <tr>
      <td rowspan="3"><strong>Field Operations</strong></td>
      <td><strong>List Fields</strong></td>
      <td>List all fields defined on a table</td>
    </tr>
    <tr>
      <td><strong>Create Field</strong></td>
      <td>Create a new field on a table</td>
    </tr>
    <tr>
      <td><strong>Delete Field</strong></td>
      <td>Delete a field from a table</td>
    </tr>
    <tr>
      <td rowspan="2"><strong>Index Operations</strong></td>
      <td><strong>Create Index</strong></td>
      <td>Create a new index on a table</td>
    </tr>
    <tr>
      <td><strong>Delete Index</strong></td>
      <td>Delete an index from a table</td>
    </tr>
    <tr>
      <td rowspan="3"><strong>Relationship Operations</strong></td>
      <td><strong>Create Relationship</strong></td>
      <td>Create a relationship between two records</td>
    </tr>
    <tr>
      <td><strong>Delete Relationship</strong></td>
      <td>Delete a relationship between records</td>
    </tr>
    <tr>
      <td><strong>Query Relationships</strong></td>
      <td>Query relationships between records</td>
    </tr>
    <tr>
      <td rowspan="2"><strong>Query Operations</strong></td>
      <td><strong>Execute Query</strong></td>
      <td>Execute a raw SurrealQL query with parameters</td>
    </tr>
    <tr>
      <td><strong>Build Select Query</strong></td>
      <td>Build SELECT queries using a visual interface with WHERE, ORDER BY, GROUP BY, and other clauses</td>
    </tr>
    <tr>
      <td rowspan="3"><strong>System Operations</strong></td>
      <td><strong>Health Check</strong></td>
      <td>Check if the database instance is responsive</td>
    </tr>
    <tr>
      <td><strong>Version</strong></td>
      <td>Get the version of the SurrealDB instance</td>
    </tr>
    <tr>
      <td><strong>Get Pool Statistics</strong></td>
      <td>Monitor connection pool performance and statistics</td>
    </tr>
  </tbody>
</table>

## Understanding SurrealDB and n8n integration

### Connection protocol

> [!IMPORTANT]
> Due to n8n's architecture, this node only supports HTTP/HTTPS connections to SurrealDB. WebSocket connections (WS/WSS) are not supported.

Your connection string must start with `http://` or `https://` (not `ws://` or `wss://`). This means that when configuring your SurrealDB instance, ensure it's accessible via `HTTP/HTTPS`.

If you're using SurrealDB Cloud or another instance that only offers WebSocket connections, you'll need to set up a [self-hosted SurrealDB instance](/pricing) with HTTP enabled. This limitation is due to how n8n handles connections and executes node operations. You can read more about this in the [n8n documentation](https://www.npmjs.com/package/n8n-nodes-surrealdb).

This node uses the HTTP/HTTPS protocol exclusively, which means that each operation creates a new connection to SurrealDB, the connection is closed after the operation completes, and no persistent connection is maintained between operations.

### Connection pooling

The SurrealDB node includes connection pooling to improve performance and resource management. Connection pooling allows the node to reuse database connections across multiple operations, reducing connection overhead and improving response times.

#### Pool configuration options

You can configure the connection pool through the "Connection Pooling" options in any node operation:

- **Max Connections** (default: 10): Maximum number of connections in the pool
- **Min Connections** (default: 2): Minimum number of connections to keep in the pool
- **Acquire Timeout** (default: 30000ms): Maximum time to wait for a connection from the pool
- **Health Check Interval** (default: 60000ms): Interval between health checks for pool connections
- **Max Idle Time** (default: 300000ms): Maximum time a connection can remain idle before being closed
- **Retry Attempts** (default: 3): Number of retry attempts for failed connection acquisitions
- **Retry Delay** (default: 1000ms): Delay between retry attempts

#### Pool monitoring

Use the **System > Get Pool Statistics** operation to monitor pool performance:

```json
{
  "poolStatistics": {
    "totalConnections": 5,
    "activeConnections": 2,
    "idleConnections": 3,
    "waitingRequests": 0,
    "totalRequests": 150,
    "failedRequests": 2,
    "averageResponseTime": 45,
    "successRate": 99
  },
  "performance": {
    "averageResponseTimeMs": 45,
    "requestsPerSecond": 2,
    "errorRate": 1
  },
  "poolHealth": {
    "utilizationRate": 40,
    "availableConnections": 3,
    "waitingRequests": 0
  }
}
```

### SurrealDB result handling

SurrealDB operations often return empty results rather than errors when no matching data is found. This behaviour differs from many other databases and can be important to understand when building workflows:

- **Empty Results vs. Errors**: A query for a non-existent record returns an empty result, not an error
- **Always Output Data**: The "Always Output Data" option is particularly useful with SurrealDB to ensure your workflow continues even when no results are found

### Working with SurrealDB data types

SurrealDB supports rich data types that map well to n8n's JSON handling:

- **Records and IDs**: SurrealDB record IDs use the format `table:id`
- **Relationships**: Relationships are first-class citizens in SurrealDB
- **Arrays and Objects**: Nested data structures are fully supported

## Error handling

The SurrealDB node includes an error handling and recovery system that automatically manages common database issues:

### Automatic error classification

The system automatically categorizes errors into different types:
<table>
  <thead>
    <tr>
      <th>Error Type</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Connection Errors</strong></td>
      <td>Network issues, timeouts, connection refused</td>
    </tr>
    <tr>
      <td><strong>Authentication Errors</strong></td>
      <td>Invalid credentials, unauthorised access</td>
    </tr>
    <tr>
      <td><strong>Query Errors</strong></td>
      <td>Syntax errors, malformed queries</td>
    </tr>
    <tr>
      <td><strong>Validation Errors</strong></td>
      <td>Invalid data, missing required fields</td>
    </tr>
    <tr>
      <td><strong>System Errors</strong></td>
      <td>Database server issues, internal errors</td>
    </tr>
  </tbody>
</table>

### Intelligent retry logic

- **Exponential Backoff**: Automatic retry with increasing delays
- **Operation-Specific Retries**: Different retry strategies for read vs write operations
- **Configurable Limits**: Adjustable retry counts and delays
- **Smart Error Filtering**: Only retry on recoverable errors

### Connection recovery

- **Automatic Reconnection**: Reconnects to SurrealDB on connection failures
- **Re-authentication**: Automatically re-authenticates after reconnection
- **Connection Validation**: Verifies connection health before retrying operations

### Enhanced error reporting

When `Continue on Fail` is enabled, errors include detailed information:
```json
{
  "error": {
    "message": "Connection timeout",
    "category": "TIMEOUT_ERROR",
    "severity": "MEDIUM",
    "retryable": true,
    "context": {
      "operation": "executeQuery",
      "itemIndex": 0,
      "timestamp": "2024-01-15T10:30:00Z",
      "recoveryStrategy": "CONNECTION_RECOVERY"
    }
  }
}
```

### Error handling strategies

Different operation types use different error handling strategies:

- **Read Operations**: Faster retries, continue on low/medium errors
- **Write Operations**: More retries, stop on medium+ errors
- **Critical Operations**: Minimal retries, stop on any error
- **Bulk Operations**: Moderate retries, handle rate limiting

For detailed information about the error handling system, see [Error Handling Documentation](https://github.com/surrealdb/n8n-nodes-surrealdb/blob/main/docs/ERROR_HANDLING.md).

## Resources

- [n8n Community Nodes Documentation](https://docs.n8n.io/integrations/community-nodes/)
- [SurrealDB Documentation](/docs)
- [SurrealQL Reference](/docs/reference/query-language.md)

---

Source: https://surrealdb.com/docs/integrate/integrations/data-management/overview

# Data management integrations

This section contains information about the different data management features of SurrealDB.

SurrealDB integrates with data platforms that help you store, organise, and transform your data. With the integrations below, you can build ETL pipelines, ingest data from different sources, and maintain data quality at scale, all on SurrealDB's multi-model architecture.

<table>
    <thead>
        <tr>
            <th>Integration</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="/docs/integrate/integrations/data-management/airbyte.md">Airbyte</a></td>
            <td>Data integration platform specialising in ELT pipelines.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/data-management/fivetran.md">Fivetran</a></td>
            <td>Data integration platform to manage data transfer between different sources and destination systems.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/data-management/n8n.md">n8n</a></td>
            <td>Workflow automation platform that lets you build custom event-driven automations.</td>
        </tr>
        <tr>
            <td><a href="/docs/integrate/integrations/data-management/qyrus.md">Qyrus</a></td>
            <td>Data quality assurance platform for cross-source comparisons and single-source validations.</td>
        </tr>
    </tbody>
</table>

---

Source: https://surrealdb.com/docs/integrate/integrations/data-management/qyrus

# Qyrus

Qyrus Data Testing integrates with SurrealDB for data quality assurance. Use Compare Jobs for cross-source validation (migrations, sync) and Evaluate Jobs for single-source checks (schema, profiling). Configure with Host URL, Port, Namespace, Database, and SurrealQL queries.

**Qyrus Data Testing** is a data quality assurance platform that integrates with SurrealDB. Use it to validate data, compare datasets across sources, and run quality checks on SurrealDB tables using SurrealQL queries.

## Overview

- **Integration type**: SurrealDB multi-model database connector for Qyrus Data Testing
- **Primary use**: Data quality assurance, cross-source comparison, and single-source validation
- **Query language**: SurrealQL for fetching and validating data
- **Documentation**: [Qyrus Data Testing](https://docs.qyrus.com/data-testing)

## Use cases

Qyrus supports two job types when using SurrealDB as a data source:

| Job Type | Description | Example Scenarios |
|----------|-------------|-------------------|
| **Compare Job** | Validates differences between two data sources | Data migrations, synchronization checks, production vs. staging comparison, source vs. target validation |
| **Evaluate Job** | Validates a single SurrealDB data source | Schema checks, constraint validation, data profiling, quality rules, custom business logic |

## Configuration parameters

When configuring SurrealDB as a data source in Qyrus, use the following parameters:

<table>
  <thead>
    <tr>
      <th>Parameter</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Host URL</strong></td>
      <td>SurrealDB server URL (HTTP / HTTPS / WebSocket)</td>
    </tr>
    <tr>
      <td><strong>Port</strong></td>
      <td>Port on which the SurrealDB service is running</td>
    </tr>
    <tr>
      <td><strong>Namespace</strong></td>
      <td>SurrealDB namespace to connect to</td>
    </tr>
    <tr>
      <td><strong>Database Name</strong></td>
      <td>Target database inside the namespace</td>
    </tr>
    <tr>
      <td><strong>Username</strong></td>
      <td>Login username (if authentication is enabled)</td>
    </tr>
    <tr>
      <td><strong>Password</strong></td>
      <td>Login password (if authentication is enabled)</td>
    </tr>
    <tr>
      <td><strong>Query</strong></td>
      <td>SurrealQL query that fetches data from the selected table</td>
    </tr>
    <tr>
      <td><strong>Enable Limit &amp; Offset</strong> (Optional)</td>
      <td>Enables pagination controls for query execution</td>
    </tr>
  </tbody>
</table>

## Getting started

To set up SurrealDB with Qyrus Data Testing:

1. Visit the [Qyrus Data Testing documentation](https://docs.qyrus.com/data-testing) for an overview of the platform
2. Configure SurrealDB as a data source using the [SurrealDB connector guide](https://docs.qyrus.com)
3. Create and run [Compare](https://docs.qyrus.com) or [Evaluate](https://docs.qyrus.com) jobs as needed
4. View validation results in [Job History](https://docs.qyrus.com/data-testing) and detailed reports for completed jobs

## Frequently Asked Questions

### What is Qyrus data testing?

Qyrus Data Testing is a data quality assurance tool that enables cross-source comparisons (Compare Jobs) and internal validations (Evaluate Jobs) to maintain reliable and accurate data across databases and systems.

### How does SurrealDB integrate with Qyrus?

SurrealDB is available as a connector in Qyrus. You configure the connection using Host URL, Port, Namespace, Database Name, and optionally Username and Password. Data is fetched from SurrealDB using SurrealQL queries that you define in Qyrus.

### When should I use a Compare Job vs. an Evaluate Job?

- **Compare Job**: Use when you need to validate that two data sources match (e.g., after a migration, during sync checks, or when comparing production and staging).
- **Evaluate Job**: Use when you need to validate a single SurrealDB data source (e.g., schema checks, data profiling, quality rules, or custom logic).

### What SurrealQL queries can I use in Qyrus?

You can use any valid SurrealQL query that fetches data from your SurrealDB tables. The query runs against the configured Namespace and Database. Examples: `SELECT * FROM table`, `SELECT * FROM table LIMIT 100`, or more complex queries with filters and joins.

### Does Qyrus support SurrealDB authentication?

Yes. If your SurrealDB instance has authentication enabled, provide the **Username** and **Password** in the Qyrus connector configuration.

### Where can I find more help?

- [Qyrus Data Testing - SurrealDB Connector](https://docs.qyrus.com)
- [Manage Jobs](https://docs.qyrus.com)
- [Data Testing Overview](https://docs.qyrus.com/data-testing)

---

Source: https://surrealdb.com/docs/integrate/integrations/database-clients/beekeeper-studio

# Beekeeper Studio

Connect Beekeeper Studio to SurrealDB to browse a namespace and database, inspect field types and run SurrealQL from a desktop editor.

[Beekeeper Studio](https://www.beekeeperstudio.io/) is a cross-platform desktop SQL editor and database manager. It has a SurrealDB connection type of its own, so a namespace and database can be browsed and queried without anything in between.

> [!NOTE]
> Beekeeper Studio describes its SurrealDB support as alpha, and repeats that in the connection dialog with a link to the features it currently covers. Read that list before depending on it for more than browsing and querying.

## Before you start

- A running SurrealDB instance. See [installation](/docs/running/installation.md) if you do not have one yet.
- [Beekeeper Studio](https://www.beekeeperstudio.io/db/surrealdb-client/) installed.

## Connect

1. Open Beekeeper Studio and select **New Connection**.
2. Set **Connection Type** to **SurrealDB**.
3. Fill in the connection. The address is three separate fields rather than one URL:
   - **Protocol**, such as `http`
   - **Host**, such as `localhost`
   - **Port**, `8000` by default
4. Choose an **Authentication Method** for the level the account belongs to, such as **Root**, then give the **User** and **Password**.
5. Enter the **Namespace** and **Database** to open.
6. Select **Test** to check the details, then **Connect**.

![The Beekeeper Studio connection dialog with SurrealDB chosen as the connection type, showing separate protocol, host and port fields above the authentication method, user, password, namespace and database.](~/assets/img/integrations/beekeeper_studio_connection.png)

A connection can be saved into a folder and given a colour, which helps where several instances are open at once.

## Browse and query

Connecting opens a query tab and lists the database's entities in the sidebar. Expanding a table shows its fields with the types SurrealDB holds them as, so a `record<person>` link or an `array<string>` reads as itself rather than as a foreign key.

Queries are written in SurrealQL and run with **Run All**, and results appear in a sortable grid below the editor:

```surql
-- Setup
CREATE cart:1 SET product_name = 'Ceramic mug', quantity = 2, price = 12.5;
CREATE cart:2 SET product_name = 'Canvas tote bag', quantity = 1, price = 18;

SELECT product_name, quantity, price FROM cart LIMIT 10;
```

![Beekeeper Studio connected to SurrealDB, with the entity sidebar showing a cart table and its field types, a SurrealQL query in the editor, and ten result rows in the grid below.](~/assets/img/integrations/beekeeper_studio_query.png)

The screenshots here use the [Surreal Deal Store](/docs/learn/tutorials/demos/surreal-deal-store.md) sample dataset.

---

Source: https://surrealdb.com/docs/integrate/integrations/editors

# SurrealQL editor support

SurrealQL syntax highlighting, completion and diagnostics in VS Code and JetBrains IDEs, plus the SurrealQL language server for other editors and CI.

SurrealDB publishes extensions that add SurrealQL to VS Code and to the JetBrains IDEs, and a language server that provides diagnostics, completion and hover to any editor that speaks the Language Server Protocol (LSP). To embed a SurrealQL editor in a web page, see [SurrealQL in CodeMirror](/docs/integrate/integrations/editors/codemirror.md).

Files with the `.surql` and `.surrealql` extensions are treated as SurrealQL.

## Choose a tool

| Tool | Gives you | Install from |
| --- | --- | --- |
| [VS Code extension](#vs-code) | Highlighting, snippets, comment toggling, language server features, a **Run** code lens and a results panel | VS Code Marketplace, Open VSX |
| [JetBrains plugin](#jetbrains-ides) | Highlighting, language server features, a **Run** code lens and a grammar version picker | JetBrains Marketplace |
| [Language server](#language-server) | Diagnostics, completion, hover, go-to-definition, references, rename, code actions and a headless `check` command | `surreal install lsp`, GitHub releases, npm, crates.io |
| [CodeMirror addon](/docs/integrate/integrations/editors/codemirror.md) | Highlighting, folding, indentation and a version linter for editors in a web page | npm |

## Language server

The language server reads SurrealQL files and reports what it finds in them. The editor extensions start it for you. It provides:

- Diagnostics for syntax errors, and for queries that disagree with the schema in your files, such as an unknown field or a field of the wrong type.
- Completion for field names, `record<table>` types, built-in functions and statement keywords.
- Hover with type information, function signatures and the permissions on a table.
- Go-to-definition and references for tables, fields, functions and parameters.
- Rename for functions defined in your files, and code actions for missing `PERMISSIONS` clauses.
- Signature help, call hierarchy and a document outline of tables, fields, events, indexes and functions.

The server builds its picture of the schema from `DEFINE` statements in your workspace, from the connected database, or from both. A workspace scan skips files over 2 MB and indexes at most 5,000 `.surql` files.

### Install the language server

With the [`surreal` launcher](/docs/reference/cli/launcher.md), install it as the `lsp` component:

```bash
surreal install lsp
```

The server is also attached to each [GitHub release](https://github.com/surrealdb/surrealql-language-server/releases) as a binary for macOS (arm64), Linux (amd64 and arm64) and Windows (amd64). Rust projects can depend on the `surrealql-language-server` crate, and the WebAssembly build for browsers is the `@surrealdb/surrealql-language-server` npm package.

### Use it in another editor

An editor starts the server over standard input and output, and the server writes nothing else to that channel:

```bash
surreal lsp stdio
```

Point any LSP client at that command for files with the `.surql` extension. The binary from a GitHub release does the same with `surrealql-language-server stdio`.

### Check files from the command line

The same analysis runs without an editor, which suits CI jobs, pre-commit hooks and coding agents:

```bash
surreal lsp check queries/
```

Pass a directory or files. To check a file against the schema in another folder, add `--workspace schema/`. For a file that exists only in memory, use `--stdin --stdin-filename <path>`. A file that creates a record in a table that has no `PERMISSIONS` clause gives output like this:

```text title="Example output"
queries/create.surql:1:8 warning[permission-unknown]: No explicit permission rule found for CREATE on `person`.
0 errors, 1 warning in 1 file
```

`--json` prints the diagnostics as one JSON document, each with a stable `code` such as `permission-unknown`, and `--fail-on warning` makes warnings fail the run too. The exit code says what happened:

| Exit code | Meaning |
| --- | --- |
| 0 | The check completed and nothing reached the `--fail-on` level, which is `error` by default. |
| 1 | The check completed and found diagnostics at or above that level. |
| 2 | The command was misused, or an input file could not be read. |

### Settings

Editors pass settings under a `surrealql` key, either as initialisation options or as workspace configuration. A table declared `SCHEMALESS` accepts fields that are not defined, so by default the server stays quiet about unknown fields and field types on it. The `analysis.schemalessDiagnostics` setting changes that:

| Value | Behaviour |
| --- | --- |
| `quiet` | Reports none of the schema-based diagnostics on a `SCHEMALESS` table. This is the default. |
| `errors` | Reports only the two faults SurrealDB itself raises: a value of the wrong type and an unknown type name. |
| `strict` | Checks a `SCHEMALESS` table in the same way as a `SCHEMAFULL` one. |

```json title="Settings"
{ "surrealql": { "analysis": { "schemalessDiagnostics": "errors" } } }
```

Use `analysis.externalParams` to list parameters that your application binds at run time, so that the server does not report them as undefined.

> [!NOTE]
> The server reads function signatures from a catalogue built for a fixed SurrealDB release, and it does not recognise every type added in SurrealDB 4.0. In version 0.6.4, the `i8` and `f16` field types are reported as `unknown-type` errors although SurrealDB 4.0 accepts them. Treat that diagnostic as advice when you target a newer type, and check the statement against your server.

## VS Code

The [SurrealQL extension](https://marketplace.visualstudio.com/items?itemName=surrealdb.surrealql) adds SurrealQL to VS Code. Open the Extensions view, search for **SurrealQL** by SurrealDB, and select **Install**. From a terminal:

```bash
code --install-extension surrealdb.surrealql
```

Editors based on VS Code that use [Open VSX](https://open-vsx.org/extension/surrealdb/surrealql), such as VSCodium, install it from there under the same name.

The extension provides:

- **Highlighting** with a TextMate grammar, including SurrealQL inside Markdown code fences and JavaScript or TypeScript template literals.
- **Snippets** for common statements.
- **Comment toggling** that understands all three line comment markers, `--`, `//` and `#`.
- **Language server features**. The extension downloads the server from GitHub on first use and caches it.
- **Run** above each top-level statement in a `.surql` or `.surrealql` file, which runs that statement against the configured endpoint.
- A **SurrealQL Results** panel with the last 50 executed queries, as a table or as JSON.
- A status bar item showing the connection in use, which opens the settings when selected.

Settings live under the `surrealql` key:

| Setting | Default | Description |
| --- | --- | --- |
| `surrealql.lsp.enable` | `true` | Turns the language server on or off. |
| `surrealql.lsp.version` | `"latest"` | Pins a language server release tag. |
| `surrealql.lsp.binaryPath` | `""` | Uses a local binary instead of the downloaded one. |
| `surrealql.connection.endpoint` | `"http://localhost:8000"` | HTTP endpoint that **Run** sends queries to. |
| `surrealql.connection.namespace` | `""` | Default namespace. |
| `surrealql.connection.database` | `""` | Default database. |
| `surrealql.connection.username` | `"root"` | User name for HTTP basic authentication. |
| `surrealql.connection.password` | | Password for that user. |
| `surrealql.connection.authContext` | `"root"` | The level the user belongs to: `root`, `namespace`, `database` or `record`. |
| `surrealql.inference.mode` | `"both"` | Where the schema comes from: `workspace`, `db` or `both`. |

A `USE NS` or `USE DB` statement in a file overrides the namespace and database settings for the statements that follow it.

To connect a coding agent in VS Code to SurrealDB, see [Visual Studio Code](/docs/agents/vscode.md) in the agent setup pages.

## JetBrains IDEs

The SurrealQL plugin works in IntelliJ IDEA, PyCharm, WebStorm, GoLand, RustRover, DataGrip and other IntelliJ-based IDEs from build 243 (2024.3) onwards. Open **Settings**, select **Plugins**, search the **Marketplace** tab for **SurrealQL**, and install the plugin by SurrealDB.

The plugin provides:

- Highlighting from the same TextMate grammar as the VS Code extension.
- Language server features through the LSP4IJ plugin, on which it depends.
- A file icon for `.surql` and `.surrealql` files.
- A **Run** code lens and a tool window for results, and a status bar widget that shows the connection.

The plugin downloads the newest published grammar when the IDE starts, and falls back to a copy bundled with the plugin when it is offline. To use an older grammar, for example after a highlighting regression, open **Settings**, **Tools**, **SurrealQL**, choose a version from the **Version** list and select **Apply**. The change takes effect without restarting the IDE.

## Other editors

Syntax grammars and editor integrations for Zed, Neovim, Helix and Emacs are in development in the [SurrealDB GitHub organisation](https://github.com/surrealdb). They are not yet published as releases, so they are not covered here. Any of these editors can use the language server described above. For connecting a coding agent in Zed, see [Zed](/docs/agents/zed.md).

SurrealDB Studio has its own SurrealQL editors, described in [SurrealQL editors](/docs/reference/studio/surrealql-editors.md).

---

Source: https://surrealdb.com/docs/integrate/integrations/editors/codemirror

# SurrealQL in CodeMirror

Add SurrealQL highlighting, folding, indentation and version linting to a CodeMirror 6 editor with the @surrealdb/codemirror package.

The `@surrealdb/codemirror` package adds SurrealQL to a [CodeMirror 6](https://codemirror.net) editor, for pages that let people write queries.

The package provides:

- SurrealQL highlighting, including embedded JavaScript in `function() { ... }` bodies.
- Folding for blocks, objects and arrays.
- Automatic indentation and comment toggling.
- A linter that reports syntax which a given SurrealDB version does not support.

## Before you start

- A project that already uses CodeMirror 6, with `@codemirror/state` and `@codemirror/view` installed.
- A package manager such as npm, pnpm or yarn.

## Install

```bash
npm install @surrealdb/codemirror
```

The package ships ES module and CommonJS builds and its own TypeScript types.

## Add SurrealQL to an editor

Pass the `surrealql()` extension to the editor state:

```ts
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { surrealql } from "@surrealdb/codemirror";

const state = EditorState.create({
    doc: "SELECT * FROM person WHERE age > 18;",
    extensions: [surrealql()],
});

new EditorView({
    parent: document.getElementById("editor")!,
    state,
});
```

The `surrealql()` extension is a standard CodeMirror `LanguageSupport`, so it combines with other CodeMirror extensions such as themes, key maps and line numbers.

## Lint for a SurrealDB version

`surrealqlVersionLinter()` takes the SurrealDB version your users run, and reports syntax in the document that this version does not support. Add it beside `surrealql()`:

```ts
import { surrealql, surrealqlVersionLinter } from "@surrealdb/codemirror";

const extensions = [surrealql(), surrealqlVersionLinter("2.0.0")];
```

The linter reports through `@codemirror/lint`, so diagnostics appear with the lint styling you have configured.

## Edit part of a statement

Pass a scope to `surrealql()` when the editor holds a fragment instead of a full script. The scope sets what the editor expects to parse:

| Scope | Expected content |
| --- | --- |
| `permission` | The contents of a `PERMISSIONS` clause, such as `FOR select WHERE published = true`. |
| `index` | The clauses of an index definition, such as `FIELDS name UNIQUE`. |

```ts
const extensions = [surrealql("permission")];
```

## Use the grammar directly

`@surrealdb/codemirror` builds on `@surrealdb/lezer`, which holds the [Lezer](https://lezer.codemirror.net) grammar. Use the CodeMirror package for an editor. Install the Lezer package on its own to parse SurrealQL into a syntax tree outside an editor.

## See also

- [SurrealQL editor support](/docs/integrate/integrations/editors.md) for the VS Code extension, the JetBrains plugin and the language server.

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/fastembed

# Fastembed

This section contains information about using Fastembed to retrieve embeddings to store in SurrealDB

Fastembed is a library that allows you to generate vector embeddings locally, without needing an API key or calling into an external service.

Fastembed uses the included ONNX runtime to run its embedding models, downloading each model once, the first time it is used.

Fastembed libraries are available for the following languages:

* [Python](https://github.com/qdrant/fastembed)
* [Rust](https://crates.io/crates/fastembed)
* [Go](https://github.com/Anush008/fastembed-go)
* [JavaScript](https://github.com/Anush008/fastembed-js)

## Overview of available models

The following is an overview of most of the models available for Fastembed. General use cases are:

* Prototyping, development speed, cost savings: models with small vector embedding sizes tend to take up a relatively small amount of disk size as well (generally a few hundred MB) and can be quickly downloaded and run locally.
* Small or edge devices: devices with no internet access can still take advantage of vector embeddings.
* Particular use cases: some models are specialised for certain use cases such as images, certain languages, and contexts.

### MiniLM series

Fast general-purpose embeddings. Choose L6 for speed, L12 for quality. Ideal for semantic search, clustering, and similarity tasks.

A "quantized" model means that it is optimised for faster inference and lower memory usage, often with minimal quality loss.

| Model name      | Embedding size | Description                                         |
| --------------- | -------------- | --------------------------------------------------- |
| AllMiniLML6V2   | 384            | Sentence Transformer model, MiniLM-L6-v2            |
| AllMiniLML6V2Q  | 384            | Quantized Sentence Transformer model, MiniLM-L6-v2  |
| AllMiniLML12V2  | 384            | Sentence Transformer model, MiniLM-L12-v2           |
| AllMiniLML12V2Q | 384            | Quantized Sentence Transformer model, MiniLM-L12-v2 |

### BGE series

Used for dense retrieval and semantic similarity. BGESmallENV15 is optimised for speed and tends to be the default choice for many applications.

| Model name     | Embedding size | Description                                                  |
| -------------- | -------------- | ------------------------------------------------------------ |
| BGEBaseENV15   | 768            | v1.5 release of the base English model                       |
| BGEBaseENV15Q  | 768            | Quantized v1.5 release of the base English model             |
| BGELargeENV15  | 1024           | v1.5 release of the large English model                      |
| BGELargeENV15Q | 1024           | Quantized v1.5 release of the large English model            |
| BGESmallENV15  | 384            | v1.5 release of the fast and default English model           |
| BGESmallENV15Q | 384            | Quantized v1.5 release of the fast and default English model |

### Nomic embed text

Used for large context window embeddings.

Optimised for long-context English text (8K tokens). v1.5 improves quality over v1.

| Model name         | Embedding size | Description                                                     |
| ------------------ | -------------- | --------------------------------------------------------------- |
| NomicEmbedTextV1   | 768            | 8192 context length english model                               |
| NomicEmbedTextV15  | 768            | v1.5 release of the 8192 context length english model           |
| NomicEmbedTextV15Q | 768            | Quantized v1.5 release of the 8192 context length english model |

### Paraphrase models

Used for paraphrase detection and multilingual similarity. Ideal for sentence equivalence and semantic matching tasks.

| Model name               | Embedding size | Description                                                              |
| ------------------------ | -------------- | ------------------------------------------------------------------------ |
| ParaphraseMLMiniLML12V2  | 384            | Multi-lingual model                                                      |
| ParaphraseMLMiniLML12V2Q | 384            | Quantized Multi-lingual model                                            |
| ParaphraseMLMpnetBaseV2  | 768            | Sentence-transformers model for tasks like clustering or semantic search, based on the MPNet architecture. |

### Chinese BGE models

| Model name    | Embedding size | Description                             |
| ------------- | -------------- | --------------------------------------- |
| BGESmallZHV15 | 512            | v1.5 release of the small Chinese model |
| BGELargeZHV15 | 1024           | v1.5 release of the large Chinese model |

### Modernbert and multilingual e5

Used for context-rich multilingual embeddings. Great for cross-language retrieval and nuanced contextual understanding.

| Model name           | Embedding size | Description                                    |
| -------------------- | -------------- | ---------------------------------------------- |
| ModernBertEmbedLarge | 1024           | Large model of ModernBert Text Embeddings      |
| MultilingualE5Small  | 384            | Small model of multilingual E5 Text Embeddings |
| MultilingualE5Base   | 768            | Base model of multilingual E5 Text Embeddings  |
| MultilingualE5Large  | 1024           | Large model of multilingual E5 Text Embeddings |

### Mxbai and GTE

Used for high-quality English/multilingual embeddings.

| Model name         | Embedding size | Description                                                |
| ------------------ | -------------- | ---------------------------------------------------------- |
| MxbaiEmbedLargeV1  | 1024           | Large English embedding model from MixedBreed.ai           |
| MxbaiEmbedLargeV1Q | 1024           | Quantized Large English embedding model from MixedBreed.ai |
| GTEBaseENV15       | 768            | Base multilingual embedding model from Alibaba            |
| GTEBaseENV15Q      | 768            | Quantized base multilingual embedding model from Alibaba  |
| GTELargeENV15      | 1024           | Large multilingual embedding model from Alibaba            |
| GTELargeENV15Q     | 1024           | Quantized large multilingual embedding model from Alibaba  |

### CLIP and code models

Use CLIP for image-text matching, Jina for code search and retrieval. JinaEmbeddingsV2BaseCode is optimised for embedding code snippets.

| Model name               | Embedding size | Description                         |
| ------------------------ | -------------- | ----------------------------------- |
| ClipVitB32               | 512            | CLIP text encoder based on ViT-B/32 |
| JinaEmbeddingsV2BaseCode | 768            | Jina embeddings v2 base code        |

## Language-specific example

The following example in Rust demonstrates how SurrealDB can be used to store the embeddings from the default language model for a number of phrases, after which it can be prompted to return the three closest results to a certain prompt.

First add a few crates to Cargo.toml with the following command:

```bash
cargo add anyhow fastembed serde tokio surrealdb --features surrealdb/kv-mem
```

Then use the following code.

```rust
use anyhow::Error;
use fastembed::{EmbeddingModel, InitOptions, TextEmbedding};
use serde::Serialize;
use surrealdb::{
    Surreal, Value,
    engine::any::{Any, connect},
};

const SCHEMA: &str = "DEFINE TABLE document;
        DEFINE FIELD text ON document TYPE string;
        DEFINE FIELD embedding ON document TYPE array<float>;
        // Uncomment this to use HNSW index, ensure that number after
        // DIMENSION matches size of embedding
        // DEFINE INDEX hnsw_embed ON document FIELDS embedding
        //     HNSW DIMENSION 384 DIST COSINE";

const INSERT_QUERY: &str = "INSERT INTO document $docs";

const VECTOR_QUERY: &str = "SELECT 
        text, 
        vector::distance::knn() AS distance 
        FROM document
        WHERE embedding <|3,COSINE|> $embeds
        ORDER BY distance";

#[derive(Serialize)]
struct DocumentInput {
    text: String,
    embedding: Vec<f32>,
}

async fn store_docs(
    input: Vec<&str>,
    db: &Surreal<Any>,
    model: &mut TextEmbedding,
) -> Result<(), Error> {
    let docs = model
        .embed(input.clone(), None)?
        .into_iter()
        .zip(input.into_iter())
        .map(|(embedding, text)| DocumentInput {
            text: text.to_string(),
            embedding,
        })
        .collect::<Vec<DocumentInput>>();

    db.query(INSERT_QUERY).bind(("docs", docs)).await?;
    Ok(())
}

async fn test_embed(
    input: &str,
    db: &Surreal<Any>,
    model: &mut TextEmbedding,
) -> Result<(), Error> {
    let Some(embeds) = model.embed(vec![input], None)?.into_iter().next() else {
        return Err(anyhow::anyhow!("Nothing found at index 0"));
    };

    let val = db
        .query(VECTOR_QUERY)
        .bind(("embeds", embeds.clone()))
        .await?
        .take::<Value>(0)?;
    println!("{val}\n");
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Default model
    let mut model = TextEmbedding::try_new(InitOptions::new(EmbeddingModel::BGESmallENV15))?;

    let db = connect("memory").await?;

    db.use_ns("ns").use_db("db").await?;

    db.query(SCHEMA).await?;

    let input = vec![
        // Cities
        "Calgary is a city in the Canadian province of Alberta.",
        "Ljubljana is the capital and largest city of Slovenia.",
        // Historical / mythological figures
        "Xenophon of Athens was a Greek military leader, philosopher, and historian.",
        "King Arthur was a mythical king in the mythology of Great Britain.",
        // Planets
        "Venus is the second planet from the Sun.",
        "Ceres is a dwarf planet in the middle main asteroid belt between the orbits of Mars and Jupiter.",
        // Languages
        "Manx is a Gaelic language of the insular Celtic branch of the Celtic language family",
        "Interlingue, originally Occidental, is an international auxiliary language created in 1922.",
        // Sea animals
        "Octopuses have a complex nervous system and are among the most intelligent and behaviourally diverse invertebrates.",
        "Clams have no central nervous system at all and are near to plants in intelligence.",
    ];
    store_docs(input, &db, &mut model).await?;

    println!("Edmonton is closest to:");
    test_embed("Edmonton", &db, &mut model).await?;

    println!("Merlin is closest to:");
    test_embed("Merlin", &db, &mut model).await?;

    println!("Earth is closest to:");
    test_embed("Earth", &db, &mut model).await?;

    println!("Irish is closest to:");
    test_embed("Irish language", &db, &mut model).await?;

    println!("Squid are closest to:");
    test_embed("Squid", &db, &mut model).await?;

    Ok(())
}
```

Output of the example with the default model:

```text
Edmonton is closest to:
[
    { distance: 0.2596421358215669f, text: 'Calgary is a city in the Canadian province of Alberta.' },
    { distance: 0.5010449624435647f, text: 'Ljubljana is the capital and largest city of Slovenia.' },
    { distance: 0.5242241576926254f, text: 'Interlingue, originally Occidental, is an international auxiliary language created in 1922.' }
]

Merlin is closest to:
[
    { distance: 0.3653307924860497f, text: 'King Arthur was a mythical king in the mythology of Great Britain.' },
    { distance: 0.4515194174120666f, text: 'Manx is a Gaelic language of the insular Celtic branch of the Celtic language family' },
    { distance: 0.5317039966149415f, text: 'Calgary is a city in the Canadian province of Alberta.' }
]

Earth is closest to:
[
    { distance: 0.3380429615054925f, text: 'Venus is the second planet from the Sun.' },
    { distance: 0.3764237673020161f, text: 'Ceres is a dwarf planet in the middle main asteroid belt between the orbits of Mars and Jupiter.' },
    { distance: 0.444087039462282f, text: 'Calgary is a city in the Canadian province of Alberta.' }
]

Irish is closest to:
[
    { distance: 0.27517683002655635f, text: 'Manx is a Gaelic language of the insular Celtic branch of the Celtic language family' },
    { distance: 0.34080671701374754f, text: 'Interlingue, originally Occidental, is an international auxiliary language created in 1922.' },
    { distance: 0.5113325799682362f, text: 'King Arthur was a mythical king in the mythology of Great Britain.' }
]

Squid are closest to:
[
    { distance: 0.3439891425642231f, text: 'Octopuses have a complex nervous system and are among the most intelligent and behaviourally diverse invertebrates.' },
    { distance: 0.4707156750207915f, text: 'Manx is a Gaelic language of the insular Celtic branch of the Celtic language family' },
    { distance: 0.517311424260043f, text: 'Clams have no central nervous system at all and are near to plants in intelligence.' }
]
```

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/mistral

# Mistral

End-to-end guide for building a fast semantic-search stack with Mistral-Embed vectors stored in SurrealDB’s native HNSW index.

**Python**

Modern open-source RAG pipelines need two things:

1. **High-quality embeddings** - *Mistral-Embed* (`mistral-embed`) returns 1 024-dimensional float vectors that rival OpenAI + Cohere.
2. **Fast vector storage** - **SurrealDB** (≥ v1.5) ships an in-memory HNSW index, queried with the `<|K,EF|>` operator in SurrealQL.

The sections below connect the two, from installation through ingestion and search to a complete script.

## Prerequisites

```bash
pip install mistralai surrealdb
````

Set two environment variables (or hard-code them if you must):

```bash
export SDB_URL="http://localhost:8000/rpc"   # ← SurrealDB RPC endpoint
export MISTRAL_API_KEY="sk-…"                # ← your Mistral key
```

## Connect and create the schema

```python
from mistralai.client import MistralClient
from surrealdb import Surreal
import os, asyncio

# ----- 1.1 · Config -----------------------------------------------------------------
SDB_URL  = os.getenv("SDB_URL", "http://localhost:8000/rpc")
SDB_USER = os.getenv("SDB_USER", "root")
SDB_PASS = os.getenv("SDB_PASS", "secret")
NS, DB   = "demo", "demo"
TABLE    = "mistral_docs"
MODEL    = "mistral-embed"

# ----- 1.2 · Clients ----------------------------------------------------------------
sdb   = Surreal(SDB_URL)
mistr = MistralClient(api_key=os.environ["MISTRAL_API_KEY"])

async def init_db():
    await sdb.signin({"user": SDB_USER, "pass": SDB_PASS})
    await sdb.use(NS, DB)

    # one quick embedding → get true vector dimension
    dim = len(mistr.embeddings(model=MODEL, input=["ping"]).data[0].embedding)

    schema = """
    DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
    DEFINE FIELD text      ON $tb TYPE string;
    DEFINE FIELD embedding ON $tb TYPE array;

    DEFINE INDEX hnsw_idx ON $tb
      FIELDS embedding
      HNSW DIMENSION {dim}
      DIST   COSINE;
    """
    await sdb.query(schema, {"tb": TABLE})

asyncio.run(init_db())
```

### Why detect the dimension dynamically?

*Future-proofing:* if Mistral introduces a **small** or **large** Embed model with a different dimension, the code auto-adapts.

## Embed and bulk-insert documents

```python
DOCS = [
    "SurrealDB offers an in-memory HNSW vector index for low-latency search.",
    "Mistral-Embed produces 1 024-dimensional embeddings.",
    "You can build a completely open-source RAG stack with these two tools.",
]

async def insert_docs(docs, batch=64):
    rows = []
    for i in range(0, len(docs), batch):
        chunk = docs[i : i + batch]
        vecs  = mistr.embeddings(model=MODEL, input=chunk).data
        rows += [
            {
                "id":        f"{TABLE}:{i+j}",
                "text":      chunk[j],
                "embedding": vec.embedding,
            }
            for j, vec in enumerate(vecs)
        ]
    await sdb.query(f"INSERT INTO {TABLE} $data", {"data": rows})

asyncio.run(insert_docs(DOCS))
```

Bulk-inserting sends every document in one SurrealQL call and one network round trip, which is **much faster** than inserting records one at a time.

## Search with a natural-language query

```python
async def search(query: str, k: int = 3, ef: int = 64):
    q_vec = mistr.embeddings(model=MODEL, input=[query]).data[0].embedding
    surql = """
    LET $q := $vec;
    SELECT id, text, vector::distance::knn() AS score
    FROM $tb
    WHERE embedding <|{k},{ef}|> $q
    ORDER BY score;
    """
    res = await sdb.query(surql, {"vec": q_vec, "tb": TABLE})
    return res[0].result

hits = asyncio.run(search("Which database supports native vector search?"))
for h in hits:
    print(f"⭐ {h['text']}  (score={h['score']:.4f})")
```

`<|K,EF|>` activates the HNSW **K-nearest-neighbour** operator (`K=3`, `efSearch=64`).
`vector::distance::knn()` exposes the cosine distance already computed inside the index, no post-processing needed.

## Full script (ready to run)

```python
# mistral_surreal_demo.py
from __future__ import annotations
import os, asyncio
from mistralai.client import MistralClient
from surrealdb import Surreal

SDB_URL  = os.getenv("SDB_URL", "http://localhost:8000/rpc")
SDB_USER = os.getenv("SDB_USER", "root")
SDB_PASS = os.getenv("SDB_PASS", "secret")
NS, DB, TABLE = "demo", "demo", "mistral_docs"
MODEL   = "mistral-embed"
KEY     = os.environ["MISTRAL_API_KEY"]  # export first!

sdb, mistr = Surreal(SDB_URL), MistralClient(api_key=KEY)

DOCS = [
    "SurrealDB's vector index is built on HNSW.",
    "Mistral-Embed vectors offer strong semantic quality.",
    "Together they form a fast, open-source search stack.",
]

async def main():
    await sdb.signin({"user": SDB_USER, "pass": SDB_PASS})
    await sdb.use(NS, DB)

    dim = len(mistr.embeddings(model=MODEL, input=["x"]).data[0].embedding)
    await sdb.query("""
        DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
        DEFINE FIELD text ON $tb TYPE string;
        DEFINE FIELD embedding ON $tb TYPE array;
        DEFINE INDEX hnsw_idx ON $tb FIELDS embedding
               HNSW DIMENSION {dim} DIST COSINE;
    """, {"tb": TABLE})

    # ingest if empty
    if (await sdb.query(f"SELECT count() FROM {TABLE};"))[0].result[0]["count"] == 0:
        rows = []
        vecs = mistr.embeddings(model=MODEL, input=DOCS).data
        rows = [
            {"id": f"{TABLE}:{i}", "text": DOCS[i], "embedding": v.embedding}
            for i, v in enumerate(vecs)
        ]
        await sdb.query(f"INSERT INTO {TABLE} $data", {"data": rows})

    # search
    q_vec = mistr.embeddings(model=MODEL,
                             input=["open-source vector database"] ).data[0].embedding
    res = await sdb.query("""
        LET $q := $vec;
        SELECT text, vector::distance::knn() AS score
        FROM {TABLE}
        WHERE embedding <|3,64|> $q
        ORDER BY score;
    """, {"vec": q_vec})
    print(res[0].result)

if __name__ == "__main__":
    asyncio.run(main())
```

## About quantisation

SurrealDB currently stores vectors as `float32` / `float64` arrays and does **not** ship built-in binary or int8 quantisation.
If memory is critical you can:

1. Quantise offline to int8 (e.g. with *faiss* or *sentence-transformers*).
2. Store the int8 arrays in **another field** (SurrealQL’s array type is agnostic).
3. Execute a **two-stage search**: coarse K-NN on the int8 field, then rescore on the full-precision field.

### You’re done 🚀

You now have a clean, fully-async SurrealDB setup that stores **Mistral-Embed** vectors, supports **fast HNSW search**, and can be dropped into any RAG or semantic-search workflow.

**Rust**

In Rust, the [mistralai-client](https://crates.io/crates/mistralai-client) crate generates the embeddings and the SurrealDB Rust SDK stores and searches them. This section covers the parts that are specific to Mistral AI. The tutorial [Implement semantic search in Rust](/docs/learn/tutorials/walkthroughs/semantic-search-in-rust.md#using-mistral) builds the complete program around them: the `document` table and its index, a function that stores a batch of texts with their embeddings, and a KNN query that answers questions against them.

## Setup

Create a new Cargo project with `cargo new project_name`, go into the project folder, and add the dependencies:

```bash
cargo add anyhow mistralai-client tokio surrealdb --features surrealdb/kv-mem,tokio/macros,tokio/rt-multi-thread
```
<br />

You need an [API key](https://console.mistral.ai/api-keys) from Mistral AI's platform. Set it in the `MISTRAL_API_KEY` environment variable rather than in the code, and run the program like this:

```bash
MISTRAL_API_KEY=whateverthekeyis cargo run
```
<br />

Or like this if you are using PowerShell on Windows:

```powershell
$env:MISTRAL_API_KEY = "whateverthekeyis"
cargo run
```
<br />

## Generate an embedding

The program below reads the key once through a `LazyLock`, [creates a client](https://docs.rs/mistralai-client/0.14.0/mistralai_client/v1/client/struct.Client.html#method.new) and asks the `mistral-embed` model for the embedding of one sentence. SurrealDB uses the tokio runtime, so the program calls the async `.embeddings_async()` method, which takes a `Vec<String>` and returns one embedding for each string.

```rust
use std::sync::LazyLock;

use anyhow::Error;
use mistralai_client::v1::{client::Client, constants::EmbedModel};

static KEY: LazyLock<String> = LazyLock::new(|| std::env::var("MISTRAL_API_KEY").unwrap());

const MODEL: EmbedModel = EmbedModel::MistralEmbed;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let client = Client::new(Some(KEY.to_string()), None, None, None)?;

    let input = vec!["Joram is the main character in the Darksword Trilogy.".to_string()];
    let mut result = client.embeddings_async(MODEL, input, None).await?;

    let embedding: Vec<f32> = result.data.remove(0).embedding;
    println!("{}", embedding.len());
    Ok(())
}
```

```text title="Output"
1024
```

`Client::new()` looks for the `MISTRAL_API_KEY` variable by default. To read the key from a variable with another name, pass the name as the second argument:

```rust
let client = Client::new(Some(KEY.to_string()), Some("OTHER_ENV_VAR".to_string()), None, None)?;
```
<br />

The [response](https://docs.rs/mistralai-client/0.14.0/mistralai_client/v1/embedding/struct.EmbeddingResponse.html) holds one `EmbeddingResponseDataItem` for each input string, in the same order, and each item's `embedding` field is a `Vec<f32>`. That type can be stored in SurrealDB as it is, as an `array<float>` field.

## Match the index to the model

The `mistral-embed` model returns vectors of [1024 dimensions](https://docs.mistral.ai/getting-started/models/models_overview/#premier-models), so a vector index on the field that stores them must use `DIMENSION 1024`. The tutorial defines the table, the field and an HNSW index with that dimension, then stores 16 short facts and asks four questions against them.

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/openai

# OpenAI

This section contains information about the OpenAI embeddings feature of SurrealDB.

**Python**

SurrealDB provides a number of different embeddings features that can be used to manage your data. This walkthrough shows how to embed your text with OpenAI, store the vectors in SurrealDB, and run fast k‑nearest‑neighbour (KNN) searches, all from Python. It follows the same flow you might have seen for Qdrant, but swaps in SurrealDB’s native vector‑search features so you can keep documents, graphs, and embeddings in one place.

## Install the two clients

OpenAI calls the API that turns text into a 1 536‑dimensional vector, while SurrealDB lets your Python code connect over WebSocket or HTTP to any SurrealDB server.

SurrealDB must be running somewhere. If you do not have SurrealDB running already you can spin up an in‑memory node in one line:

```bash
pip install openai surrealdb   
```

For local testing you can spin it up quickly:

```bash
docker run -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass secret
```

## Set up the OpenAI and SurrealDB clients

```python
import asyncio
import openai
from surrealdb import Surreal

openai_client = openai.Client(api_key="YOUR_OPENAI_KEY")

TEXTS = [
    "SurrealDB is a multi-model database you can embed anywhere!",
    "Loved by devs who need graphs, documents **and** vector search in one box.",
]

async def init_db() -> Surreal:
    db = Surreal("ws://localhost:8000/rpc")          # change URL if remote
    await db.signin({"username": "root", "password": "secret"})
    await db.use("demo_ns", "demo_db")
    return db
```

## Create the embeddings with OpenAI

`text‑embedding‑3‑small` is compact, cheap, and surprisingly accurate for semantic search. If you need more nuance (or plan to quantise heavily) you can upgrade to `text‑embedding‑3‑large` (3 072 dimensions) at roughly twice the cost.

```python
EMBED_MODEL = "text-embedding-3-small"

emb_resp = openai_client.embeddings.create(
    input=TEXTS,
    model=EMBED_MODEL
)
emb_vectors = [row.embedding for row in emb_resp.data]   # list[list[float]]
```

## Insert the documents into SurrealDB

SurrealDB is schemaless by default, so you can drop JSON directly into a table named article:

*(table `article` with a vector field called `embedding`)*

```python
async def load_documents(db: Surreal):
    docs = [
        {"text": txt, "embedding": vec}
        for txt, vec in zip(TEXTS, emb_vectors)
    ]
    await db.create("article", docs)

asyncio.run(load_documents(asyncio.run(init_db())))
```

## Add a vector index (HNSW)

The Hierarchical Navigable Small World (HNSW) index trades a tiny bit of accuracy for dramatic speed‑ups compared with brute-force scanning; ideal once your table grows beyond a few thousand records. Because HNSW lives in RAM today, index creation is instant but counts against your memory budget.

SurrealQL lets you add the index once; after that inserts are indexed automatically.

```python
async def add_index(db: Surreal):
    await db.query("""
        DEFINE INDEX article_embedding_hnsw 
        ON article
        FIELDS embedding
        HNSW DIMENSION 1536;
    """)

asyncio.run(add_index(asyncio.run(init_db())))
```

The `DIMENSION` must match the length of the OpenAI vectors (1536 in this model).

## Search for the most relevant documents

```python
async def semantic_search(question: str, k: int = 3):
    query_vec = openai_client.embeddings.create(
        input=[question],
        model=EMBED_MODEL
    ).data[0].embedding

    db = await init_db()

    # KNN search: <|k, ef|> - ef is “search breadth”. 100 is a decent default.
    result = await db.query(f"""
        LET $q := {query_vec};

        SELECT id, text,
               vector::distance::knn() AS distance
        FROM article
        WHERE embedding <|{k},100|> $q
        ORDER BY distance;
    """)
    return result[0]['result']

hits = asyncio.run(semantic_search("What’s the best database for unified search?"))
for hit in hits:
    print(hit["distance"], hit["text"])
```

The `vector::distance::knn()` helper returns the exact distance that the KNN operator just computed, so SurrealDB can immediately sort or filter without recalculating.

Two knobs to remember:

- `k` - the number of neighbours you want back.
- `ef` (the second number) - search breadth. Higher values spend more CPU for slightly better accuracy; 100-200 is a safe default.

## (Optional) Binary-quantise the vectors

SurrealDB stores vectors as arrays of floats (`F32` by default) and doesn’t yet expose built-in binary quantisation the way Qdrant does.
If you need ultra-compact storage you can:

1. **Quantise offline** (e.g. convert to `int32` with `numpy`).
2. Store the compressed list in a separate field (`embedding_q32`) and build an index on that instead:

```sql
DEFINE INDEX article_embedding_q32_mt
ON article
FIELDS embedding_q8
HNSW DIMENSION 1536 TYPE I32;
```

This keeps the SurrealDB side simple while you experiment with different quantisers. For more information about vector search in SurrealDB, see the [Vector Search Reference guides](/docs/learn/data-models/vector-search/overview.md).

**Rust**

In Rust, the [async-openai](https://crates.io/crates/async-openai) crate generates the embeddings and the SurrealDB Rust SDK stores and searches them. This section covers the parts that are specific to OpenAI. The tutorial [Implement semantic search in Rust](/docs/learn/tutorials/walkthroughs/semantic-search-in-rust.md#using-openai) builds the complete program around them: the `document` table and its index, a function that stores each text with its embedding, and a KNN query that finds the closest documents to a search term.

## Setup

Create a new Cargo project with `cargo new project_name`, go into the project folder, and add the dependencies. The `embedding` feature of `async-openai` enables the embeddings API:

```bash
cargo add anyhow async-openai tokio surrealdb --features async-openai/embedding,surrealdb/kv-mem,tokio/macros,tokio/rt-multi-thread
```
<br />

You need an [OpenAI API key](https://platform.openai.com/api-keys). Set it in the `OPENAI_API_KEY` environment variable rather than in the code, and run the program like this:

```bash
OPENAI_API_KEY=whateverthekeyis cargo run
```
<br />

Or like this if you are using PowerShell on Windows:

```powershell
$env:OPENAI_API_KEY = "whateverthekeyis"
cargo run
```
<br />

## Generate an embedding

The program below reads the key once through a `LazyLock`, creates a client that holds it, and asks the [`text-embedding-3-small`](https://platform.openai.com/docs/guides/embeddings/embedding-models) model for the embedding of one sentence.

```rust
use std::sync::LazyLock;

use anyhow::Error;
use async_openai::{Client, config::OpenAIConfig, types::embeddings::CreateEmbeddingRequestArgs};

static KEY: LazyLock<String> = LazyLock::new(|| std::env::var("OPENAI_API_KEY").unwrap());

#[tokio::main]
async fn main() -> Result<(), Error> {
    let config = OpenAIConfig::new().with_api_key(&*KEY);
    let client = Client::with_config(config);

    let request = CreateEmbeddingRequestArgs::default()
        .model("text-embedding-3-small")
        .input("Octopuses solve puzzles and escape enclosures, showing advanced intelligence.")
        .dimensions(1536u32)
        .build()?;
    let mut result = client.embeddings().create(request).await?;

    let embedding: Vec<f32> = result.data.remove(0).embedding;
    println!("{}", embedding.len());
    Ok(())
}
```

```text title="Output"
1536
```

The response holds one `Embedding` for each input, and each one's `embedding` field is a `Vec<f32>`. That type can be stored in SurrealDB as it is, as an `array<float>` field.

## Match the index to the model

`text-embedding-3-small` returns vectors of [1536 dimensions](https://platform.openai.com/docs/guides/embeddings) by default. The `.dimensions()` setting asks the model for shorter vectors, and whatever length you choose, a vector index on the field that stores them must use the same `DIMENSION`. The tutorial uses 1536 for both.

Compared with the Mistral AI client in the [Mistral](/docs/integrate/integrations/embeddings-providers/mistral.md) Rust example, three things change: the model is a string rather than an enum, the request is built with `CreateEmbeddingRequestArgs`, and the index uses `DIMENSION 1536` instead of `DIMENSION 1024`. The table, the structs and the KNN query work unchanged.

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/overview

# Embeddings provider integrations

This section contains information about different LLM models you can use with SurrealDB.

SurrealDB supports vector embeddings for semantic search and machine learning across your data. With integrations for the main embedding providers, you can store, index and query high-dimensional vectors alongside your regular data.

- [Quick start with Python](/docs/integrate/integrations/embeddings-providers/python-quickstart.md) - LangChain, Ollama, Mistral, and more

- [Quick start with Rust](/docs/integrate/integrations/embeddings-providers/rust-quickstart.md) - Mistral, Ollama, and more

## Full examples

<table>
  <tbody>
    <tr>
      <td><a href="/docs/integrate/integrations/embeddings-providers/mistral.md">Mistral</a></td>
      <td>Mistral AI's embedding model and SurrealDB vector search (Python and Rust)</td>
    </tr>
    <tr>
      <td><a href="/docs/integrate/integrations/embeddings-providers/openai.md">OpenAI</a></td>
      <td>OpenAI's embedding service and SurrealDB vector search (Python and Rust)</td>
    </tr>
  </tbody>
</table>

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/python-quickstart

# Python quickstart

This section contains information about different embedding models you can use with SurrealDB.

SurrealDB supports vector embeddings for semantic search and machine learning across your data. With integrations for the main embedding providers, you can store, index and query high-dimensional vectors alongside your regular data.

**LangChain**

More details and providers in [LangChain Embedding models](https://python.langchain.com/docs/integrations/text_embedding/) documentation.

**Ollama**

## Ollama

```python
from langchain_ollama import OllamaEmbeddings

vector_store = SurrealDBVectorStore(
    OllamaEmbeddings(model="all-minilm:22m"),
    conn
)
```

More [Ollama embedding models](https://ollama.com/search?c=embedding) in their documentation.

**OpenAI**

## OpenAI

Requires `OPENAI_API_KEY` environment variable.

```python
from langchain_openai import OpenAIEmbeddings

vector_store = SurrealDBVectorStore(
    OpenAIEmbeddings(model="text-embedding-3-large"),
    conn
)
```

**Mistral**

## Mistral

Requires `MISTRALAI_API_KEY` environment variable.

```python
from langchain_mistralai import MistralAIEmbeddings

vector_store = SurrealDBVectorStore(
    MistralAIEmbeddings(model="mistral-embed"),
    conn
)
```

**SentenceTransformer**

## SentenceTransformer

```python
from langchain_huggingface import HuggingFaceEmbeddings

vector_store = SurrealDBVectorStore(
    HuggingFaceEmbeddings(
        model_name="sentence-transformers/all-MiniLM-L6-v2"
    ),
    conn
)
```

More [SentenceTransformer models](https://www.sbert.net/docs/sentence_transformer/pretrained_models.html) in their documentation.

**AWS Bedrock**

## AWS Bedrock

```python
from langchain_aws import BedrockEmbeddings

vector_store = SurrealDBVectorStore(
    BedrockEmbeddings(model_id="amazon.titan-embed-text-v2:0"),
    conn
)
```

**Gemini**

## Gemini

Requires `GOOGLE_API_KEY` environment variable.

```python
from langchain_google_genai import GoogleGenerativeAIEmbeddings

vector_store = SurrealDBVectorStore(
    GoogleGenerativeAIEmbeddings(model="models/embedding-001"),
    conn
)
```

<br />

Then, to query the vector store using similarity search:

```python
doc1 = Document(
    page_content="SurrealDB is the ultimate multi-model database for AI applications",
    metadata={"key": "sdb"},
)
doc2 = Document(
    page_content="Surrealism is an artistic and cultural movement that emerged in the early 20th century",
    metadata={"key": "surrealism"},
)
vector_store.add_documents(documents=[doc1, doc2], ids=["1", "2"])

results = vector_store.similarity_search_with_score(query=q, k=2)
for doc, score in results:
    print(f"• [{score:.0%}]: {doc.page_content}")
top_match = results[0][0]
```

Find an example in [Minimal LangChain chatbot example with vector and graph](/blog/minimal-langchain-chatbot-example-with-vector-and-graph).

**Vanilla**

**Ollama**

## Ollama

```python
import ollama

embedding = ollama.embed(model="all-minilm:22m", input=text)
conn.create("documents", { "content": text, "embedding": embedding })
```

More [Ollama embedding models](https://ollama.com/search?c=embedding) in their documentation.

**OpenAI**

## OpenAI

```python
from openai import OpenAI
client = OpenAI()

text = "Your text string"
response = client.embeddings.create(
    input=text,
    model="text-embedding-3-small"
)

conn.create("documents", { "content": text, "embedding": response.data[0].embedding })
```

More info in [OpenAI embeddings](https://platform.openai.com/docs/guides/embeddings?lang=python) documentation.

**Sentence Transformers**

## Sentence Transformers

```python
from sentence_transformers import SentenceTransformer

st = SentenceTransformer("all-MiniLM-L6-v2")
embedding = st.encode(text).tolist()
conn.create("documents", { "content": text, "embedding": embedding })
```

More [SentenceTransformer models](https://www.sbert.net/docs/sentence_transformer/pretrained_models.html) in their documentation.

To query the vector store using similarity search:

```python
k = 5
query_embedding = st.encode("this is your query text")
res = conn.query(
    f"""
    SELECT
        *,
        vector::distance::knn() AS dist
    FROM documents
    WHERE embedding <|{k}|> $vector;
    """,
    {
        "vector": query_embedding.tolist(),
    },
)
```

This requires an index to be created beforehand. Refer to the [vector search cheat sheet](/docs/learn/data-models/vector-search/vector-indexes.md#vector-search-cheat-sheet).

<br />

Examples above assume you have a DB connection like this:

```python
conn = Surreal("localhost")
conn.signin({"username": "root", "password": "secret"})
conn.use("test_ns", "test_db")
```

---

Source: https://surrealdb.com/docs/integrate/integrations/embeddings-providers/rust-quickstart

# Rust quickstart

This section contains information about different embedding models you can use with SurrealDB.

SurrealDB supports vector embeddings for semantic search and machine learning across your data. With integrations for the main embedding providers, you can store, index and query high-dimensional vectors alongside your regular data.

**Mistral**

## Mistral

```rust
use mistralai_client::v1::{client::Client, constants::EmbedModel};

static KEY = std::env::var("MISTRAL_API_KEY").unwrap();

// ...

let client = Client::new(Some(KEY.to_string()), None, None, None)?;
let input = vec!["Joram is the main character in the Darksword Trilogy.".to_string()];

let result = client.embeddings_async(MODEL, input, None).await?;
println!("{:?}", result);
```

Find a full example in [Semantic search in Rust with SurrealDB and Mistral AI](/blog/semantic-search-in-rust-with-surrealdb-and-mistral-ai#generate-mistral-ai-embeddings).

**Ollama**

## Ollama

```rust
use ollama_rs::{Ollama, generation::embeddings::GenerateEmbeddingsRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let ollama = Ollama::default();

    let model = "all-minilm:22m".to_string()
    let prompt = "this is your input text".to_string();

    let request = GenerateEmbeddingsRequest::new(model, prompt);
    let response = ollama.generate_embeddings(request).await?;

    println!("Generated embeddings (first 5): {:?}", &response.embeddings[..5]);
    println!("Embedding vector length: {}", response.embeddings.len());

    Ok(())
}
```

**SentenceTransformer**

## SentenceTransformer

```rust
use rust_bert::sentence_embeddings::{
    SentenceEmbeddingsBuilder, SentenceEmbeddingsModelType,
};

fn main() -> anyhow::Result<()> {
    // Set up the model builder, specifying the model type
    let model = SentenceEmbeddingsBuilder::remote(
        SentenceEmbeddingsModelType::AllMiniLmL6V2
    ).create_model()?;

    // Define the sentences to embed
    let sentences = [
        "this is your text",
        "you can encode more than one in batch"
    ];

    // Generate the embeddings
    let embeddings = model.encode(&sentences)?;

    // Print the results
    for (i, embedding) in embeddings.iter().enumerate() {
        // Truncate for display purposes
        let truncated_embedding: Vec<_> = embedding.iter().take(5).cloned().collect();

        println!("\nSentence: '{}'", sentences[i]);
        println!("Embedding (first 5 values): {:?}", truncated_embedding);
        println!("Embedding dimensions: {}", embedding.len());
    }

    Ok(())
}
```

---

Source: https://surrealdb.com/docs/integrate/integrations/frontend-frameworks/tanstack-db

# TanStack DB

Use the pre-release @surrealdb/tanstack-db package to back TanStack DB collections with SurrealDB tables, with local-first writes and live query updates.

[TanStack DB](https://tanstack.com/db) is a client-side store that keeps collections of records in memory, applies writes to them immediately and queries them reactively. The `@surrealdb/tanstack-db` package connects a TanStack DB collection to a SurrealDB table, so that local writes are saved to the database and changes made elsewhere reach the collection through a [live query](/docs/reference/query-language/statements/live-select.md).

> [!WARNING]
> `@surrealdb/tanstack-db` is a pre-release. The only version published to npm is `1.0.0-alpha.1`, and it depends on the release candidate of `@tanstack/db`. Behaviour and options can change before a stable release, and the limitations at the end of this page apply to it.

## Before you start

- A running SurrealDB instance, with the namespace and database you connect to already defined. See [installation](/docs/running/installation.md) if you do not have one yet.
- A project that uses the [JavaScript SDK](/docs/reference/javascript.md), version 2.2.2 or later in the 2.x line.

## Install

Install the adapter next to the packages it lists as peer dependencies:

```bash
npm install @surrealdb/tanstack-db@alpha surrealdb @tanstack/db @tanstack/query-core @tanstack/query-db-collection @standard-schema/spec
```

## Create a collection

A collection takes an open `Surreal` connection, the name of a table and a TanStack Query client. The `queryKey` identifies the collection and, together with the table name, gives it a stable id.

```ts
import { createCollection } from '@tanstack/db';
import { QueryClient } from '@tanstack/query-core';
import { Surreal } from 'surrealdb';
import { surrealCollectionOptions } from '@surrealdb/tanstack-db';

const db = new Surreal();
await db.connect('ws://127.0.0.1:8000/rpc', {
	namespace: 'test',
	database: 'test',
	authentication: { username: 'root', password: 'secret' },
});

type Product = { id: string; name: string; price: number };

export const products = createCollection(
	surrealCollectionOptions<Product>({
		db,
		table: { name: 'product' },
		queryClient: new QueryClient(),
		queryKey: ['product'],
		syncMode: 'eager',
	}),
);
```

The `syncMode` option takes `'eager'`, `'on-demand'` or `'progressive'`. The examples on this page use `'eager'`, which delivers both the initial reads and live updates. See [Limitations](#limitations).

## Write records

A write updates the collection at once and returns a transaction. Wait for the `settled` state to know that SurrealDB has accepted the change:

```ts
await products.insert({ id: 'p1', name: 'Keyboard', price: 40 }).when('settled');

await products.update('product:p1', (draft) => {
	draft.price = 45;
}).when('settled');

await products.delete('product:p1').when('settled');
```

> [!WARNING]
> In this pre-release, a `delete` can raise `DeleteOperationItemNotFoundError` after it settles, which ends a Node.js process unless the error is caught.

A record written as `p1` into the `product` table is stored as `product:p1`, and the collection keys it by the full record ID, `'product:p1'`. Use that key for `update` and `delete`. To pass record IDs as values instead of strings, see the `RecordId` model example in the package README.

## Read records with a live query

A collection loads the records that a query asks for. Build the query with `createLiveQueryCollection`, and preload it:

```ts
import { createLiveQueryCollection, gt } from '@tanstack/db';

const pricey = createLiveQueryCollection((q) =>
	q
		.from({ products })
		.where(({ products }) => gt(products.price, 5))
		.select(({ products }) => products),
);

await pricey.preload();
console.log(pricey.toArray.map((product) => product.name));
```

The `where` condition is passed to SurrealDB as part of the query, so the collection holds only the matching records. In a framework, bind the same query to your components with the matching TanStack DB package, such as `@tanstack/react-db`.

## Receive changes from other clients

Once a collection is syncing, a change made by another client, a script or a SurrealQL statement is delivered through a live query and appears in the collection with `$origin` set to `'remote'`. Call `startSyncImmediate()` to start the collection without waiting for a subscriber:

```ts
products.startSyncImmediate();
```

## Other features

The package README documents further options:

- **Persistence:** `persistedSurrealCollectionOptions` stores a collection in a local SQLite database so that it survives a restart.
- **End-to-end encryption:** the `e2ee` option stores records as encrypted envelopes, using a crypto provider such as the included `WebCryptoAESGCM`.
- **CRDTs:** the `crdt` option keeps documents as [Loro](https://loro.dev) updates. Merging happens in the client. SurrealDB stores the encoded updates as ordinary records and passes them to other clients, and it does not merge or understand them.

## Permissions and schema

The adapter does not define tables or permissions. Define each table, with `DEFINE TABLE` and `DEFINE FIELD`, and its access rules in SurrealDB before the collection uses it. See [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md) for the options.

## Limitations

These limitations apply to `@surrealdb/tanstack-db` `1.0.0-alpha.1` with `@tanstack/db` `1.0.0-rc.1.5`.

- **Existing records load only through a query.** Calling `preload()` on the collection itself does nothing, even with `syncMode: 'eager'`, and logs a warning that names `'on-demand'`. Records already in the table appear once a live query collection, as shown above, reads them.
- **`'on-demand'` mode misses new records.** With `syncMode: 'on-demand'`, a record created by another client after the query loaded did not reach the live query collection. `'eager'` and `'progressive'` delivered it.
- **The table must exist.** Reading a table that has not been defined fails with a `table does not exist` error.
- **A local delete can raise an unhandled error.** After `delete(...)` settles, the live query reports the same deletion, and the collection can throw `DeleteOperationItemNotFoundError` because the record is already gone. In Node.js this ends the process unless the error is caught.
- **The peer dependency on `surrealdb` is `^2.2.2`.** The package works with the 2.x SDK only.

---

Source: https://surrealdb.com/docs/integrate/integrations/vercel

# Vercel

Use SurrealDB with Vercel - Next.js apps, the AI SDK, eve agents and Vercel Sandbox - with connection, credential and runtime guidance that applies to all four.

These pages show how to use SurrealDB with Vercel's frameworks and compute: Next.js applications, the AI SDK, agents built with eve, and Vercel Sandbox. Each page uses the [`surrealdb`](/docs/reference/javascript.md) JavaScript SDK directly, so no adapter package is needed.

> [!NOTE]
> This section is about running your own SurrealDB database. For managed long-term memory for agents, see [SurrealDB Agent Memory](/docs/agent-memory.md), which has its own [AI SDK](/docs/agent-memory/integrations/ai-sdks/vercel-ai-sdk.md) and [eve](/docs/agent-memory/integrations/frameworks/eve.md) integrations.

## Choose a page

| Page | Use it to |
| --- | --- |
| [Next.js](/docs/integrate/integrations/vercel/nextjs.md) | Read and write data from Server Components, Server Actions and Route Handlers, and stream live updates to the browser. |
| [AI SDK](/docs/integrate/integrations/vercel/ai-sdk.md) | Store embeddings, give a model search and graph tools, and keep chat history in SurrealDB. |
| [Eve](/docs/integrate/integrations/vercel/eve.md) | Give an eve agent tools that query your data, and back an eve memory slot with SurrealDB. |
| [Vercel Sandbox](/docs/integrate/integrations/vercel/vercel-sandbox.md) | Start a temporary SurrealDB server inside a sandbox, or let sandboxed code query your database with limited access. |

## Where the database runs

Vercel Functions and sandboxes run your code, but they do not keep data between invocations. Run SurrealDB as a separate server, either on [SurrealDB Cloud](/docs/running/cloud.md) or on infrastructure that you manage, and connect to it from Vercel. Place the database in or near the region where your functions run, because every query is a network round trip.

A sandbox can run a SurrealDB server for a short time, which is useful for tests and for scratch data that an agent creates. The [Vercel Sandbox](/docs/integrate/integrations/vercel/vercel-sandbox.md) page describes when that is appropriate.

## Store credentials as environment variables

The examples in this section read the connection details from these environment variables:

| Variable | Example value |
| --- | --- |
| `SURREALDB_URL` | `https://<your-instance>.aws.surrealdb.cloud` |
| `SURREALDB_NAMESPACE` | `app` |
| `SURREALDB_DATABASE` | `main` |
| `SURREALDB_USER` | `app_server` |
| `SURREALDB_PASS` | The password of that user |

Add them to the Vercel project under **Settings** > **Environment Variables**, or with the Vercel CLI:

```sh
vercel env add SURREALDB_PASS
```

To use the same values on your computer, link the project and pull the variables into `.env.local`:

```sh
vercel link
vercel env pull
```

Give the application its own [database-level user](/docs/learn/security/authentication/users.md#system-users) rather than the root user. A user defined `ON DATABASE` can only reach that one database. The `EDITOR` role lets it read and write data in that database, but not manage users or access methods:

```surql
DEFINE USER app_server ON DATABASE PASSWORD 'strongPassword' ROLES EDITOR;
```

A user defined on the database signs in with the namespace and database as well as the username and password. The connection examples in this section pass both.

## Choose HTTP or WebSocket

The JavaScript SDK connects over HTTP when the URL starts with `http://` or `https://`, and over WebSocket when it starts with `ws://` or `wss://`.

- **HTTP** sends each query as its own request. Nothing has to stay open between invocations, which suits functions that can be paused or stopped at any time. Use it for server-side code on Vercel.
- **WebSocket** keeps one connection open and is required for [live queries](/docs/reference/javascript/concepts/live-queries.md). Use it in the browser, where the page stays open, or in a long-running process.

[Connecting from serverless and edge](/docs/learn/querying/concepts-and-guides/connecting-from-serverless-and-edge.md) explains the trade-offs in more detail, including token authentication and batching.

## Create the namespace and database

SurrealDB returns an error such as `The namespace 'app' does not exist` when a client selects a namespace or database that has not been defined. Start a schema file with the definitions, so the file works on an empty server:

```surql title="schema.surql"
DEFINE NAMESPACE IF NOT EXISTS app;
USE NS app;
DEFINE DATABASE IF NOT EXISTS main;
USE DB main;

-- Tables, fields and indexes follow
```

Send the file to the `/sql` endpoint of the server. The pages in this section use this command to apply their schemas:

```sh
curl -X POST -u "root:secret" -H "Accept: application/json" \
  --data-binary @schema.surql http://localhost:8000/sql
```

## See also

- [JavaScript SDK](/docs/reference/javascript.md)
- [Connecting to SurrealDB](/docs/reference/javascript/concepts/connecting-to-surrealdb.md)
- [SurrealDB Cloud](/docs/running/cloud.md)

---

Source: https://surrealdb.com/docs/integrate/integrations/vercel/ai-sdk

# AI SDK

Use SurrealDB with the Vercel AI SDK 7 - store embeddings from embedMany, give models vector search and graph traversal tools, and persist chat history in a Next.js route.

The [AI SDK](https://ai-sdk.dev) is Vercel's TypeScript library for calling language and embedding models. SurrealDB stores the data that those calls need: embeddings in a vector index, the relations between documents as graph edges, and the chat history of each conversation. This page builds a question-answering chat route in which the model searches a knowledge base through tools that query SurrealDB.

> [!NOTE]
> This page stores data in a SurrealDB database that you run. For managed long-term memory that the AI SDK reads and writes through middleware, see the [Agent Memory AI SDK integration](/docs/agent-memory/integrations/ai-sdks/vercel-ai-sdk.md).

## Requirements

- [SurrealDB v3](/docs/running/installation.md), local or on [SurrealDB Cloud](/docs/running/cloud.md)
- AI SDK 7 (the `ai` package) and Node.js 22 or later
- Access to [Vercel AI Gateway](https://vercel.com/docs/ai-gateway), through the `AI_GATEWAY_API_KEY` environment variable locally or automatically on Vercel. The examples pass models as `provider/model` strings, which go through the gateway.

## Setup

Start SurrealDB locally:

```sh
surreal db start --user root --pass secret memory
```

Save the schema below as `schema.surql`. The `HNSW` index uses 1536 dimensions, because that is the size of the vectors that `openai/text-embedding-3-small` returns. If you use another embedding model, set `DIMENSION` to its output size.

```surql title="schema.surql"
DEFINE NAMESPACE IF NOT EXISTS app;
USE NS app;
DEFINE DATABASE IF NOT EXISTS main;
USE DB main;

DEFINE USER app_server ON DATABASE PASSWORD 'strongPassword' ROLES EDITOR;

-- Documents and their embeddings
DEFINE TABLE document SCHEMAFULL;
DEFINE FIELD title ON document TYPE string;
DEFINE FIELD content ON document TYPE string;
DEFINE FIELD embedding ON document TYPE array<float>;
DEFINE INDEX document_embedding ON document
    FIELDS embedding HNSW DIMENSION 1536 DIST COSINE;

-- One document cites another
DEFINE TABLE cites SCHEMAFULL TYPE RELATION FROM document TO document;

-- Chat history, one record per conversation
DEFINE TABLE conversation SCHEMALESS;
```

Apply it:

```sh
curl -X POST -u "root:secret" -H "Accept: application/json" \
  --data-binary @schema.surql http://localhost:8000/sql
```

The `conversation` table is schemaless because the AI SDK message format has many part types, and the application reads the history back in the same shape it wrote it.

## Install dependencies

```sh
npm install ai @ai-sdk/react zod surrealdb
```

The examples use the `getDb()` helper from the Next.js page, which signs in once and shares the client between requests. Create `lib/surreal.ts` as shown in [Create one shared client](/docs/integrate/integrations/vercel/nextjs.md#create-one-shared-client), and set the `SURREALDB_*` environment variables listed there.

## Store documents with embeddings

`embedMany` returns one embedding for each input value, in the same order. Combine each embedding with its document and insert them all with one `INSERT` statement:

```ts title="lib/ingest.ts"
import { embedMany } from "ai";
import { getDb } from "@/lib/surreal";

export async function ingest(documents: { title: string; content: string }[]) {
    const { embeddings } = await embedMany({
        model: "openai/text-embedding-3-small",
        values: documents.map((document) => document.content),
    });

    const db = await getDb();
    await db.query("INSERT INTO document $documents", {
        documents: documents.map((document, index) => ({
            ...document,
            embedding: embeddings[index],
        })),
    });
}
```

When one document refers to another, record it as an edge so that a tool can follow it later:

```surql
RELATE document:knn->cites->document:hnsw;
```

## Give the model a search tool

A tool is a function that the model can decide to call. This one embeds the question with the same model that embedded the documents, and runs a nearest-neighbour search against the `HNSW` index:

```ts title="lib/tools.ts"
import { embed, tool } from "ai";
import { z } from "zod";
import { getDb } from "@/lib/surreal";

export const searchDocuments = tool({
    description: "Search the knowledge base for passages that answer a question.",
    inputSchema: z.object({
        query: z.string().describe("The question or topic to search for"),
    }),
    execute: async ({ query }) => {
        const { embedding } = await embed({
            model: "openai/text-embedding-3-small",
            value: query,
        });

        const db = await getDb();
        const [results] = await db
            .query(
                `SELECT id, title, content, vector::distance::knn() AS distance
                FROM document
                WHERE embedding <|5,100|> $embedding
                ORDER BY distance`,
                { embedding },
            )
            .json();

        return results;
    },
});
```

In `<|5,100|>`, `5` is the number of documents to return and `100` is the size of the candidate list that the `HNSW` search keeps while it looks for them. A larger second number finds closer matches more reliably and takes longer. `vector::distance::knn()` returns the distance that the search computed, so the query does not calculate it twice. [Similarity search](/docs/learn/data-models/vector-search/similarity-search.md) explains the operator and how to combine it with a `WHERE` filter.

`.json()` turns each record ID into a string such as `document:knn`, which the model can read and pass back to another tool.

## Give the model a graph tool

Vector search finds passages that use similar words. The `cites` edges add something that similarity cannot find: which documents depend on a passage, and which ones it depends on. A second tool lets the model follow those edges from a document that the search returned:

```ts title="lib/tools.ts"
export const relatedDocuments = tool({
    description: "List the documents that a document cites and the documents that cite it.",
    inputSchema: z.object({
        id: z.string().describe("A document id returned by searchDocuments, such as document:abc"),
    }),
    execute: async ({ id }) => {
        const db = await getDb();
        const [result] = await db
            .query(
                `SELECT
                    ->cites->document.{ id, title } AS cites,
                    <-cites<-document.{ id, title } AS cited_by
                FROM ONLY <record<document>> $id`,
                { id },
            )
            .json();

        return result;
    },
});
```

The model supplies `id` as a string. The cast `<record<document>> $id` turns it into a record ID, and the query fails unless the string is a record ID in the `document` table. The model therefore cannot use this tool to read from any other table. For `document:knn`, the tool returns:

```json title="Output"
{
    "cited_by": [],
    "cites": [{ "id": "document:hnsw", "title": "HNSW indexes" }]
}
```

## Keep chat history in SurrealDB

The route below loads the stored messages of a conversation, adds the new message from the client, and streams the answer. When the stream ends, `onEnd` receives the complete list of messages, including the new answer and its tool calls, and the route saves it:

```ts title="app/api/chat/route.ts"
import { convertToModelMessages, isStepCount, streamText, type UIMessage } from "ai";
import { RecordId } from "surrealdb";
import { relatedDocuments, searchDocuments } from "@/lib/tools";
import { getDb } from "@/lib/surreal";

export async function POST(request: Request) {
    const { id, message }: { id: string; message: UIMessage } = await request.json();

    const db = await getDb();
    const conversation = new RecordId("conversation", id);

    const [stored] = await db.query<[UIMessage[] | undefined]>(
        "SELECT VALUE messages FROM ONLY $conversation",
        { conversation },
    );
    const messages = [...(stored ?? []), message];

    const result = streamText({
        model: "anthropic/claude-sonnet-5.5",
        instructions: "Answer from the knowledge base. Call searchDocuments before answering.",
        messages: await convertToModelMessages(messages),
        tools: { searchDocuments, relatedDocuments },
        stopWhen: isStepCount(5),
    });

    return result.toUIMessageStreamResponse({
        originalMessages: messages,
        onEnd: async ({ messages }) => {
            await db.query(
                "UPSERT $conversation CONTENT { messages: $messages, updated_at: time::now() }",
                { conversation, messages },
            );
        },
    });
}
```

Some details of this route:

- The client sends only the new message, and the server owns the history. Configure `useChat` on the client to send `{ id, message }` instead of the full list, as shown below.
- `SELECT VALUE messages FROM ONLY $conversation` returns `undefined` for a new conversation, so the first request starts with an empty history.
- `stopWhen: isStepCount(5)` lets the model call tools and read their results for up to five steps before it must answer.
- The conversation ID comes from the client. If conversations belong to signed-in users, check that the user owns the conversation before you load it.

The client component gives `useChat` a transport that sends the conversation ID and the last message only:

```tsx title="components/chat.tsx"
"use client";

import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";

export function Chat({ id }: { id: string }) {
    const { messages, sendMessage } = useChat({
        id,
        transport: new DefaultChatTransport({
            api: "/api/chat",
            prepareSendMessagesRequest: ({ id, messages }) => ({
                body: { id, message: messages.at(-1) },
            }),
        }),
    });

    // Render messages and call sendMessage({ text }) from a form
}
```

## See also

- [Next.js](/docs/integrate/integrations/vercel/nextjs.md)
- [Eve](/docs/integrate/integrations/vercel/eve.md), for agents that run as durable workflows
- [Vector indexes](/docs/learn/data-models/vector-search/vector-indexes.md)
- [Hybrid search](/docs/learn/data-models/vector-search/hybrid-search.md), to combine vector and full-text results
- [AI SDK documentation](https://ai-sdk.dev/docs)

---

Source: https://surrealdb.com/docs/integrate/integrations/vercel/eve

# Eve

Connect eve agents to SurrealDB - tools that query your records with parameters and approval, and a custom memory provider with scoped vector recall and idempotent capture.

[eve](https://eve.dev) is Vercel's open-source framework for building agents in TypeScript. An eve agent is a directory of files: the model and instructions, one file for each tool, and optional memory slots, channels and schedules. eve runs each conversation as a durable workflow, so a session continues after a crash or a redeploy. This page connects an eve agent to SurrealDB in two ways: as tools that read and change your application's data, and as a memory provider that stores what the agent learns about each caller.

> [!NOTE]
> This page uses a SurrealDB database that you run. For a managed memory service with an eve adapter, see the [Agent Memory eve integration](/docs/agent-memory/integrations/frameworks/eve.md).

## Requirements

- [SurrealDB v3](/docs/running/installation.md), local or on [SurrealDB Cloud](/docs/running/cloud.md)
- An eve project and Node.js 24 or later. To create a project, run `npx eve@latest init my-agent`.
- An embedding model for the memory provider. The examples use `openai/text-embedding-3-small` through [Vercel AI Gateway](https://vercel.com/docs/ai-gateway).

## What SurrealDB stores

eve keeps its own state: the session history, the workflow steps and the values from `defineState`. SurrealDB holds the data that exists outside any single session:

| Data | Where it lives |
| --- | --- |
| Conversation history and workflow progress | eve |
| Orders, customers and the other records the agent works with | SurrealDB, reached through tools |
| Facts the agent remembers about a caller across sessions | SurrealDB, through a memory provider |

## Setup

Start SurrealDB locally:

```sh
surreal db start --user root --pass secret memory
```

Save the schema below as `schema.surql`. It defines the store's data, the `memory` table for the memory provider, and a database user for the agent:

```surql title="schema.surql"
DEFINE NAMESPACE IF NOT EXISTS app;
USE NS app;
DEFINE DATABASE IF NOT EXISTS main;
USE DB main;

DEFINE USER agent ON DATABASE PASSWORD 'strongPassword' ROLES EDITOR;

DEFINE TABLE customer SCHEMAFULL;
DEFINE FIELD name ON customer TYPE string;
DEFINE FIELD email ON customer TYPE string;

DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD name ON product TYPE string;
DEFINE FIELD price ON product TYPE decimal;

DEFINE TABLE order SCHEMAFULL;
DEFINE FIELD customer ON order TYPE record<customer>;
DEFINE FIELD items ON order TYPE array<record<product>>;
DEFINE FIELD total ON order TYPE decimal;
DEFINE FIELD status ON order TYPE 'pending' | 'shipped' | 'cancelled' DEFAULT 'pending';
DEFINE FIELD created_at ON order TYPE datetime DEFAULT time::now() READONLY;

DEFINE TABLE memory SCHEMAFULL;
DEFINE FIELD scope ON memory TYPE string;
DEFINE FIELD content ON memory TYPE string;
DEFINE FIELD embedding ON memory TYPE array<float>;
DEFINE FIELD created_at ON memory TYPE datetime DEFAULT time::now() READONLY;
DEFINE INDEX memory_embedding ON memory
    FIELDS embedding HNSW DIMENSION 1536 DIST COSINE;

CREATE customer:ada CONTENT { name: 'Ada Lovelace', email: 'ada@example.com' };
CREATE product:lamp CONTENT { name: 'Desk lamp', price: 39.90dec };
CREATE order:a1b2c3 CONTENT { customer: customer:ada, items: [product:lamp], total: 39.90dec };
```

Apply it:

```sh
curl -X POST -u "root:secret" -H "Accept: application/json" \
  --data-binary @schema.surql http://localhost:8000/sql
```

## Install dependencies

From the root of the eve project:

```sh
npm install surrealdb
```

eve projects already depend on `ai` and `zod`, which the examples also use.

Add the connection details to `.env.local`, and to the Vercel project's environment variables before you deploy:

```sh title=".env.local"
SURREALDB_URL=http://localhost:8000
SURREALDB_NAMESPACE=app
SURREALDB_DATABASE=main
SURREALDB_USER=agent
SURREALDB_PASS=strongPassword
```

## Connect to SurrealDB

Tools and memory providers run in your application's runtime, not in eve's sandbox, so they can read `process.env` and share one client. Create `agent/lib/surreal.ts` with the `getDb()` helper from [Create one shared client](/docs/integrate/integrations/vercel/nextjs.md#create-one-shared-client) on the Next.js page, and leave out its first line, `import "server-only"`, which belongs to Next.js. `getDb()` signs in once with the `SURREALDB_*` variables above and stores the connection promise, so tool calls that start at the same time share one sign-in.

## Query data from a tool

eve names each tool after its file, so `agent/tools/get_order.ts` becomes the `get_order` tool. The model chooses the input, and the tool passes it to a fixed query as a parameter:

```ts title="agent/tools/get_order.ts"
import { defineTool } from "eve/tools";
import { z } from "zod";
import { getDb } from "../lib/surreal";

export default defineTool({
    description: "Look up an order by its id, with the customer and the items in it.",
    inputSchema: z.object({
        order_id: z.string().describe("The order id, such as order:a1b2c3"),
    }),
    async execute({ order_id }) {
        const db = await getDb();
        const [order] = await db
            .query(
                `SELECT id, status, total, created_at,
                    customer.{ name, email } AS customer,
                    items.{ name, price } AS items
                FROM ONLY <record<order>> $order_id`,
                { order_id },
            )
            .json();

        return order ?? { error: `No order ${order_id}` };
    },
});
```

The record links in `customer` and `items` are followed inside the query, so one call returns the order with its customer and products. The cast `<record<order>> $order_id` makes the query fail unless the input is a record ID in the `order` table. For `order:a1b2c3`, the tool returns:

```json title="Output"
{
    "created_at": "2026-10-15T05:07:01.376601Z",
    "customer": { "email": "ada@example.com", "name": "Ada Lovelace" },
    "id": "order:a1b2c3",
    "items": [{ "name": "Desk lamp", "price": "39.9" }],
    "status": "pending",
    "total": "39.9"
}
```

> [!IMPORTANT]
> Do not give the model a tool that runs SurrealQL queries written by the model. A fixed query with parameters limits each tool to one operation, and the agent's database user limits what any query can reach.

## Change data from a tool

A tool that changes data needs two more safeguards. eve can run a tool call again if the step was interrupted before it finished, so the change must give the same result when it runs twice. A person may also need to approve the change before it happens.

```ts title="agent/tools/cancel_order.ts"
import { defineTool } from "eve/tools";
import { always } from "eve/tools/approval";
import { z } from "zod";
import { getDb } from "../lib/surreal";

export default defineTool({
    description: "Cancel an order that has not shipped yet.",
    inputSchema: z.object({
        order_id: z.string().describe("The order id, such as order:a1b2c3"),
    }),
    approval: always(),
    async execute({ order_id }) {
        const db = await getDb();
        const [updated] = await db.query<[unknown[]]>(
            `UPDATE <record<order>> $order_id
                SET status = 'cancelled'
                WHERE status = 'pending'`,
            { order_id },
        );

        return updated.length > 0
            ? { cancelled: true }
            : { cancelled: false, reason: "The order is not pending" };
    },
});
```

The `WHERE status = 'pending'` condition makes the update safe to repeat: the first run cancels the order, and a second run matches no record and changes nothing. `approval: always()` pauses the call until a person approves it. The pause is durable, so the session continues from the same point after the approval arrives.

## Back a memory slot with SurrealDB

An eve memory slot binds a provider to a scope, such as the signed-in caller. Before each turn, eve calls the provider's `recall` handler and adds the messages it returns to the model's context. After the turn, it calls `capture` so that the provider can store what happened. The provider below stores each user message with its embedding, and recalls the five closest memories at the start of the next turn:

```ts title="agent/lib/surreal-memory.ts"
import { embed, type ModelMessage } from "ai";
import { defineMemoryProvider } from "eve/memory";
import { defineTool } from "eve/tools";
import { RecordId } from "surrealdb";
import { z } from "zod";
import { getDb } from "./surreal";

const embeddingModel = "openai/text-embedding-3-small";

function userText(messages: readonly ModelMessage[]): string {
    return messages
        .filter((message) => message.role === "user")
        .flatMap((message) =>
            typeof message.content === "string"
                ? [message.content]
                : message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])),
        )
        .join("\n")
        .trim();
}

export function surrealMemory() {
    return defineMemoryProvider({
        recall: {
            async "turn.started"(ctx) {
                const text = userText(ctx.turn.input);
                if (!text) return null;

                const { embedding } = await embed({ model: embeddingModel, value: text });
                const db = await getDb();
                const [memories] = await db.query<[{ id: RecordId; content: string }[]]>(
                    `SELECT id, content FROM memory
                    WHERE scope = $scope AND embedding <|5,100|> $embedding`,
                    { scope: ctx.memory.scope.key, embedding },
                );

                return {
                    messages: memories.map((memory) => ({
                        id: memory.id.toString(),
                        content: memory.content,
                    })),
                };
            },
        },
        capture: {
            async "turn.completed"(ctx) {
                const text = userText(ctx.turn.input);
                if (!text) return;

                const { embedding } = await embed({ model: embeddingModel, value: text });
                const db = await getDb();
                await db.query("INSERT IGNORE INTO memory $memory", {
                    memory: {
                        id: new RecordId("memory", ctx.operationId),
                        scope: ctx.memory.scope.key,
                        content: text,
                        embedding,
                    },
                });
            },
        },
        async tools(ctx) {
            return {
                forget: defineTool({
                    description: "Delete a remembered note by its id.",
                    inputSchema: z.object({ id: z.string() }),
                    async execute({ id }) {
                        const db = await getDb();
                        await db.query("DELETE <record<memory>> $id WHERE scope = $scope", {
                            id,
                            scope: ctx.memory.scope.key,
                        });
                        return { deleted: true };
                    },
                }),
            };
        },
    });
}
```

The provider follows the rules that eve sets for every memory provider:

- **Every read and write is limited to `ctx.memory.scope.key`.** The `scope` condition is part of the vector search itself, so the `HNSW` search skips other callers' memories while it collects the five results, rather than filtering them out afterwards. The `forget` tool has the same condition, so the model cannot delete another caller's memory even with a valid record ID.
- **Capture is idempotent.** eve can call a handler again with the same `operationId`. The memory record's ID is the `operationId`, and `INSERT IGNORE` leaves an existing record unchanged, so a repeated call stores nothing new.
- **Recalled memories have stable IDs.** eve uses the `id` of each recalled message to replace an earlier copy of the same memory instead of adding a duplicate.

Declare the slot in `agent/memory/`. The file name becomes the slot name, so the model sees the tool as `notes__forget`:

```ts title="agent/memory/notes.ts"
import { defineMemory } from "eve/memory";
import { byPrincipal } from "eve/memory/scope";
import { surrealMemory } from "../lib/surreal-memory";

export default defineMemory({
    description: "Facts and preferences the caller has shared in earlier conversations.",
    provider: surrealMemory(),
    scope: byPrincipal,
});
```

`byPrincipal` gives each authenticated caller their own scope. eve's [memory documentation](https://eve.dev/docs/memory) describes the other scopes, and [Build a memory provider](https://eve.dev/docs/memory/custom-provider) describes the full provider contract.

This provider stores every user message, which keeps the example short. A production provider usually stores less: for example, it can ask a model to extract durable facts from the turn and store only those, or it can store nothing in `capture` and offer the model a `remember` tool instead.

## Limit what the agent can reach

The `agent` user in the schema has the `EDITOR` role on one database. To limit the agent further, give it a [record user](/docs/learn/security/authentication/users.md#record-users) and define table permissions, or split the work between two users: a `VIEWER` user for tools that only read, and an `EDITOR` user for the tools that need approval. [DEFINE USER](/docs/reference/query-language/statements/define/user.md) lists the roles.

## See also

- [AI SDK](/docs/integrate/integrations/vercel/ai-sdk.md), for search and graph tools outside an eve agent
- [Similarity search](/docs/learn/data-models/vector-search/similarity-search.md)
- [Record links and graph relations](/docs/learn/data-models/graph/record-links-vs-graph-relations.md)
- [eve documentation](https://eve.dev/docs/getting-started)

---

Source: https://surrealdb.com/docs/integrate/integrations/vercel/nextjs

# Next.js

Connect a Next.js App Router application on Vercel to SurrealDB - one shared client, Server Components, Server Actions, Route Handlers and browser live queries with record users.

[Next.js](https://nextjs.org) renders React on the server, so most of your SurrealDB queries run in server code: Server Components read data, Server Actions change it, and Route Handlers serve it as JSON. This page builds a small task list that does all three, then adds live updates in the browser. The same code runs locally and on Vercel.

## Requirements

- [SurrealDB v3](/docs/running/installation.md), local or on [SurrealDB Cloud](/docs/running/cloud.md)
- Next.js 16 with the App Router
- Node.js 20.9 or later

## Setup

Start SurrealDB locally, either [installed directly](/docs/running/installation.md):

```sh
surreal db start --user root --pass secret memory
```

or [with Docker](/docs/running/docker.md):

```sh
docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass secret
```

Save the schema below as `schema.surql`. It defines the namespace and database, a `task` table, and a database-level user for the application to sign in as:

```surql title="schema.surql"
DEFINE NAMESPACE IF NOT EXISTS app;
USE NS app;
DEFINE DATABASE IF NOT EXISTS main;
USE DB main;

DEFINE USER app_server ON DATABASE PASSWORD 'strongPassword' ROLES EDITOR;

DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD title ON task TYPE string ASSERT $value.len() > 0;
DEFINE FIELD done ON task TYPE bool DEFAULT false;
DEFINE FIELD created_at ON task TYPE datetime DEFAULT time::now() READONLY;
```

Apply it through the `/sql` endpoint:

```sh
curl -X POST -u "root:secret" -H "Accept: application/json" \
  --data-binary @schema.surql http://localhost:8000/sql
```

## Install dependencies

In an existing Next.js project, add the SDK and the `server-only` package:

```sh
npm install surrealdb server-only
```

Add the connection details to `.env.local`. On Vercel, set the same variables in the project settings, as described in [Store credentials as environment variables](/docs/integrate/integrations/vercel.md#store-credentials-as-environment-variables):

```sh title=".env.local"
SURREALDB_URL=http://localhost:8000
SURREALDB_NAMESPACE=app
SURREALDB_DATABASE=main
SURREALDB_USER=app_server
SURREALDB_PASS=strongPassword
```

## Create one shared client

Signing in with a password takes a few hundred milliseconds, because SurrealDB hashes the password with a function that is slow on purpose, so that an attacker can only test a few guesses per second. See [Passwords](/docs/learn/security/best-practices/security-best-practices.md#passwords) in the security best practices, and [A bit of cryptography](/learn/book/chapter-15#a-bit-of-cryptography) in chapter 15 of Aeon's Surreal Renaissance for how these functions work. Sign in once per server instance and reuse the client for every request. On Vercel's Fluid compute, one instance serves many requests, so a client stored at module scope is shared between them.

```ts title="lib/surreal.ts"
import "server-only";
import { Surreal } from "surrealdb";

let connection: Promise<Surreal> | undefined;

export function getDb(): Promise<Surreal> {
    connection ??= connect().catch((error) => {
        connection = undefined;
        throw error;
    });
    return connection;
}

async function connect(): Promise<Surreal> {
    const db = new Surreal();
    const namespace = process.env.SURREALDB_NAMESPACE!;
    const database = process.env.SURREALDB_DATABASE!;

    await db.connect(process.env.SURREALDB_URL!, {
        namespace,
        database,
        authentication: {
            namespace,
            database,
            username: process.env.SURREALDB_USER!,
            password: process.env.SURREALDB_PASS!,
        },
    });
    return db;
}
```

Three details in this file matter:

- `getDb()` stores the promise rather than the client. Requests that arrive while the first connection is still opening wait for the same promise, so the instance signs in only once. If the connection fails, the next call tries again.
- `import "server-only"` makes the build fail if a Client Component imports this file, which keeps the credentials out of the browser bundle.
- An `http://` or `https://` URL makes the SDK send each query as its own HTTP request. Nothing has to stay open while Vercel pauses the instance between requests.

## Read data in a Server Component

A Server Component can be `async` and query the database directly. The result type is passed as a generic, with one element for each statement in the query:

```tsx title="app/page.tsx"
import type { RecordId } from "surrealdb";
import { getDb } from "@/lib/surreal";
import { addTask } from "./actions";

type Task = {
    id: RecordId<"task">;
    title: string;
    done: boolean;
};

export default async function Page() {
    const db = await getDb();
    const [tasks] = await db.query<[Task[]]>(
        "SELECT id, title, done, created_at FROM task ORDER BY created_at DESC LIMIT 50",
    );

    return (
        <main>
            <form action={addTask}>
                <input name="title" required />
                <button type="submit">Add task</button>
            </form>
            <ul>
                {tasks.map((task) => (
                    <li key={task.id.toString()}>{task.title}</li>
                ))}
            </ul>
        </main>
    );
}
```

`created_at` is in the selection because SurrealDB requires a field used in `ORDER BY` to be selected.

Record IDs arrive as `RecordId` objects, which keep the table and the key separate. React cannot pass a class instance such as `RecordId` from a Server Component to a Client Component, so convert it with `.toString()`, or call `.json()` on the query, before you pass a result down as a prop.

## Change data in a Server Action

A Server Action runs on the server when the form is submitted. Pass user input as a query parameter, never by building the query string, and then revalidate the page so that it shows the new record:

```ts title="app/actions.ts"
"use server";

import { revalidatePath } from "next/cache";
import { getDb } from "@/lib/surreal";

export async function addTask(formData: FormData) {
    const title = String(formData.get("title") ?? "").trim();
    if (!title) return;

    const db = await getDb();
    await db.query("CREATE task CONTENT { title: $title }", { title });

    revalidatePath("/");
}
```

The `ASSERT` on the `title` field rejects an empty title in the database as well, so the rule holds for every client, not only for this form.

## Serve JSON from a Route Handler

A Route Handler returns a `Response`. The `.json()` method on a query converts SurrealDB values such as record IDs and datetimes to their JSON forms, so the result can go straight into `Response.json()`:

```ts title="app/api/tasks/route.ts"
import { getDb } from "@/lib/surreal";

export async function GET() {
    const db = await getDb();
    const [tasks] = await db
        .query("SELECT id, title, done, created_at FROM task ORDER BY created_at DESC")
        .json();

    return Response.json(tasks);
}
```

A request to `/api/tasks` returns the tasks:

```json title="Example output"
[
    {
        "created_at": "2026-10-15T05:05:43.7823Z",
        "done": false,
        "id": "task:s97vxaoriwi01cuf7d5p",
        "title": "Write docs"
    }
]
```

## Stream live updates to the browser

A [live query](/docs/reference/javascript/concepts/live-queries.md) sends a message to the client each time a matching record changes. It needs a WebSocket connection that stays open, so it belongs in the browser rather than in a Vercel Function.

The browser must never receive the `app_server` password. Instead, each person signs in as a [record user](/docs/learn/security/authentication/users.md#record-users), and table permissions decide what that user can see. Add a `user` table, a [record access method](/docs/reference/query-language/statements/define/access/record.md), and permissions on `task` to the schema:

```surql title="schema.surql"
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD email ON user TYPE string;
DEFINE FIELD password ON user TYPE string;
DEFINE INDEX user_email ON user FIELDS email UNIQUE;

DEFINE ACCESS account ON DATABASE TYPE RECORD
    SIGNUP (CREATE user CONTENT { email: $email, password: crypto::argon2::generate($password) })
    SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(password, $password))
    DURATION FOR SESSION 12h;

DEFINE TABLE OVERWRITE task SCHEMAFULL
    PERMISSIONS
        FOR select FULL
        FOR create, update, delete NONE;
```

`DEFINE TABLE OVERWRITE` replaces the earlier table definition and keeps its fields. With these permissions, a signed-in record user can read every task but cannot change one. The permissions apply only to record users, so the `app_server` user in the Server Action can still create tasks. Your sign-in flow calls `signin` or `signup` with `access: "account"` and receives an access token.

The Client Component below connects with that token and keeps its list in step with the database:

```tsx title="components/live-tasks.tsx"
"use client";

import { useEffect, useState } from "react";
import { Surreal, Table } from "surrealdb";

type Task = { id: string; title: string; done: boolean };

export function LiveTasks({ token, initial }: { token: string; initial: Task[] }) {
    const [tasks, setTasks] = useState(initial);

    useEffect(() => {
        const db = new Surreal();

        async function subscribe() {
            await db.connect(process.env.NEXT_PUBLIC_SURREALDB_URL!, {
                namespace: process.env.NEXT_PUBLIC_SURREALDB_NAMESPACE,
                database: process.env.NEXT_PUBLIC_SURREALDB_DATABASE,
                authentication: token,
            });

            const live = await db.live<Omit<Task, "id">>(new Table("task"));
            live.subscribe((message) => {
                if (message.action === "KILLED") return;
                const id = message.recordId.toString();
                setTasks((current) => {
                    const others = current.filter((task) => task.id !== id);
                    if (message.action === "DELETE") return others;
                    return [{ ...message.value, id }, ...others];
                });
            });
        }

        subscribe().catch(console.error);
        return () => {
            db.close();
        };
    }, [token]);

    return (
        <ul>
            {tasks.map((task) => (
                <li key={task.id}>{task.title}</li>
            ))}
        </ul>
    );
}
```

Set `NEXT_PUBLIC_SURREALDB_URL` to the WebSocket address of the server, such as `wss://<your-instance>.aws.surrealdb.cloud`. Variables with the `NEXT_PUBLIC_` prefix are included in the browser bundle, so put only the address, namespace and database in them, never a password.

## Deploy to Vercel

1. Make sure that Vercel can reach the database. A server on `localhost` is not reachable from a deployment, so use a SurrealDB Cloud instance or another server with a public address.
2. Add `SURREALDB_URL`, `SURREALDB_NAMESPACE`, `SURREALDB_DATABASE`, `SURREALDB_USER` and `SURREALDB_PASS` to the project's environment variables, and the `NEXT_PUBLIC_` variables if you use live queries.
3. Deploy:

```sh
vercel deploy
```

Routes that use the shared client run on the Node.js runtime, which is the default in Next.js and the runtime that Vercel recommends.

## See also

- [AI SDK](/docs/integrate/integrations/vercel/ai-sdk.md), which adds a chat route to an application like this one
- [Connecting to SurrealDB](/docs/reference/javascript/concepts/connecting-to-surrealdb.md)
- [Live queries](/docs/reference/javascript/concepts/live-queries.md)
- [Record users](/docs/learn/security/authentication/users.md#record-users)

---

Source: https://surrealdb.com/docs/integrate/integrations/vercel/vercel-sandbox

# Vercel Sandbox

Run a temporary SurrealDB server inside a Vercel Sandbox microVM for tests and agent scratch data, or give sandboxed code read-only access to a SurrealDB database.

[Vercel Sandbox](https://vercel.com/docs/vercel-sandbox) creates isolated Linux virtual machines on demand, controlled from TypeScript with the `@vercel/sandbox` package. The virtual machines run Linux on Vercel's infrastructure, while the code that controls them runs on any system that has Node.js, including Windows. Agents use sandboxes to run code they have generated, and test suites use them to start clean environments. This page shows two ways to use SurrealDB with a sandbox: start a temporary SurrealDB server inside one, or let code inside a sandbox query a database that runs elsewhere.

This page is about Vercel's product. The [SurrealDB Studio Sandbox](/docs/running/sandbox.md) is a separate, browser-based environment for trying SurrealQL.

## Requirements

- A Vercel account and a project linked with the Vercel CLI
- Node.js 22 or later
- For the second pattern, a SurrealDB server that the sandbox can reach, such as a [SurrealDB Cloud](/docs/running/cloud.md) instance

## Install dependencies

```sh
npm install @vercel/sandbox surrealdb
```

The SDK authenticates with a Vercel OIDC token. On Vercel it is available automatically. On your computer, link the project and pull the token into `.env.local`:

```sh
vercel link
vercel env pull
```

The pulled token expires after a few hours, so run `vercel env pull` again when the SDK reports that it cannot get credentials.

## Choose a pattern

| Pattern | Use it for | Where the data lives |
| --- | --- | --- |
| SurrealDB inside a sandbox | Integration tests, preview environments, and scratch databases that an agent creates and then discards | In the sandbox, until it stops |
| Sandboxed code that connects out | Running generated code, such as a report or a data check, against your real data | In your SurrealDB server |

> [!WARNING]
> A sandbox is not a place to host a database that other systems depend on. It stops when its timeout ends, and each session has a maximum length that depends on your Vercel plan. Keep data that must last in [SurrealDB Cloud](/docs/running/cloud.md) or on a server that you manage.

## Run SurrealDB inside a sandbox

The script below creates a sandbox, installs SurrealDB, starts it with the `memory` storage engine, and queries it from your computer through the sandbox's public URL:

```ts title="surreal-in-sandbox.ts"
import { Sandbox } from "@vercel/sandbox";
import { Surreal } from "surrealdb";

const password = crypto.randomUUID();

await using sandbox = await Sandbox.create({
    ports: [8000],
    timeout: 10 * 60 * 1000,
});

await sandbox.runCommand({
    cmd: "sh",
    args: ["-c", "curl -sSf https://install.surrealdb.com | sh"],
    sudo: true,
});

await sandbox.runCommand({
    cmd: "surreal",
    args: ["start", "--bind", "0.0.0.0:8000", "--user", "root", "--pass", password, "memory"],
    detached: true,
});

const url = sandbox.domain(8000);
await waitForHealth(url);

const db = new Surreal();
await db.connect(url, {
    authentication: { username: "root", password },
});

await db.query("DEFINE NAMESPACE app; USE NS app; DEFINE DATABASE main;");
await db.use({ namespace: "app", database: "main" });

await db.query("CREATE person CONTENT { name: 'Ada' }");
const [people] = await db.query("SELECT * FROM person").json();
console.log(people);

await db.close();

async function waitForHealth(url: string) {
    for (let attempt = 0; attempt < 30; attempt++) {
        const response = await fetch(`${url}/health`).catch(() => undefined);
        if (response?.ok) return;
        await new Promise((resolve) => setTimeout(resolve, 1000));
    }
    throw new Error("SurrealDB did not become healthy");
}
```

Run it with the token from `.env.local`:

```sh
npx tsx --env-file=.env.local surreal-in-sandbox.ts
```

The script prints the new record:

```text title="Example output"
[ { id: 'person:si33pkkzl1fh2rs000a7', name: 'Ada' } ]
```

Each step in the script has a purpose:

- **`ports: [8000]`** exposes the port, and `sandbox.domain(8000)` returns its public HTTPS address.
- **`sudo: true`** lets the install script write the `surreal` binary to `/usr/local/bin`.
- **`detached: true`** returns as soon as the server process starts, instead of waiting for it to exit.
- **`waitForHealth`** polls the `/health` endpoint, because the server takes a moment to start listening.
- **`DEFINE NAMESPACE` and `DEFINE DATABASE`** create the namespace and database, because SurrealDB does not create them when a client first selects them.
- **`await using`** stops the sandbox when the script ends, even after an error. Without it, call `await sandbox.stop()` yourself.

> [!IMPORTANT]
> The address from `sandbox.domain()` is public. Anyone who finds it can try to sign in, so the script creates a random root password for each sandbox instead of a fixed one, and never logs it.

The example connects through the public URL over HTTPS. Vercel does not document WebSocket support for sandbox ports, so do not depend on WebSocket connections or [live queries](/docs/reference/javascript/concepts/live-queries.md) through that URL.

With the `memory` storage engine, the data is deleted when the process stops. That is usually what a test or a scratch database needs: every run starts from an empty database.

## Let sandboxed code connect to your database

To run code inside a sandbox against a database that already exists, give the sandbox credentials for a user that can do only what the code needs. A database-level user with the `VIEWER` role can read every table in one database and cannot change anything:

```surql
DEFINE USER sandbox ON DATABASE PASSWORD 'strongPassword' ROLES VIEWER;
```

A write from this user does not raise an error. The statement returns no records and leaves the data unchanged.

The script below passes the credentials as environment variables and limits the sandbox's network access to the npm registry and your SurrealDB host. It then writes a small program into the sandbox and runs it:

```ts title="connect-out.ts"
import { Sandbox } from "@vercel/sandbox";

const surrealHost = new URL(process.env.SURREALDB_URL!).hostname;

await using sandbox = await Sandbox.create({
    timeout: 5 * 60 * 1000,
    env: {
        SURREALDB_URL: process.env.SURREALDB_URL!,
        SURREALDB_USER: "sandbox",
        SURREALDB_PASS: process.env.SURREALDB_SANDBOX_PASS!,
    },
    networkPolicy: {
        allow: ["registry.npmjs.org", surrealHost],
    },
});

await sandbox.runCommand("npm", ["install", "surrealdb"]);

await sandbox.writeFiles([
    {
        path: "report.mjs",
        content: `
import { Surreal } from "surrealdb";

const db = new Surreal();
await db.connect(process.env.SURREALDB_URL, {
    namespace: "app",
    database: "main",
    authentication: {
        namespace: "app",
        database: "main",
        username: process.env.SURREALDB_USER,
        password: process.env.SURREALDB_PASS,
    },
});

const [result] = await db.query("SELECT count() AS orders FROM order GROUP ALL").json();
console.log(JSON.stringify(result));
await db.close();
`,
    },
]);

const run = await sandbox.runCommand("node", ["report.mjs"]);
console.log(await run.stdout());
```

When an agent writes the program instead of you, the same two limits apply: the `VIEWER` role stops the program from changing data, and the network policy stops it from sending the data to any other host.

## See also

- [Vercel](/docs/integrate/integrations/vercel.md), for credentials and connection guidance that apply to all Vercel products
- [Eve](/docs/integrate/integrations/vercel/eve.md), whose agents run generated code in Vercel Sandbox
- [System users](/docs/learn/security/authentication/users.md#system-users)
- [Vercel Sandbox SDK reference](https://vercel.com/docs/vercel-sandbox/sdk-reference)

---

Source: https://surrealdb.com/docs/integrate/migrating

# Migrating to SurrealDB

Move data into SurrealDB from other databases, from files and streams, or from an older SurrealDB version, using Surreal Sync, the CLI import or an SDK.

This section describes how to move data into SurrealDB: from other databases, from files or streams (for example CSV, JSON Lines, or Kafka), and from older SurrealDB versions. Use the part that matches your source.

<img src="~/assets/img/diagrams/light/hub-migrating-sources-light.webp" darkSrc="~/assets/img/diagrams/hub-migrating-sources.webp" alt="Other databases, such as PostgreSQL, MySQL, MongoDB, Neo4j and Snowflake, and files and streams, such as CSV, JSON Lines and Kafka, move into SurrealDB through Surreal Sync. An older SurrealDB reaches a newer one by following the upgrade guide for each version. A database that Surreal Sync does not cover can be exported as JSON and loaded with surreal import." />

## From other databases

Each page maps the data, queries and concepts of a database you may know to SurrealDB. All of these sources can be imported automatically with the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool.

- [MongoDB](/docs/integrate/migrating/from-other-databases/from-mongodb.md)
- [MySQL](/docs/integrate/migrating/from-other-databases/from-mysql.md)
- [Neo4j](/docs/integrate/migrating/from-other-databases/from-neo4j.md)
- [PostgreSQL](/docs/integrate/migrating/from-other-databases/from-postgresql.md)
- [Snowflake](/docs/integrate/migrating/from-other-databases/from-snowflake.md)

## From files and streams

Surreal Sync also imports these sources. [CSV data](/docs/integrate/migrating/from-files-and-streams/csv.md) can also be imported in SurrealDB Studio with its [built-in functionality](/docs/reference/studio.md).

- [CSV data](/docs/integrate/migrating/from-files-and-streams/csv.md)
- [JSON Lines](/docs/integrate/migrating/from-files-and-streams/json-lines.md)
- [Kafka](/docs/integrate/migrating/from-files-and-streams/kafka.md)

## A source that Surreal Sync does not cover

Export the data as [JSON Lines](/docs/integrate/migrating/from-files-and-streams/json-lines.md) and import it with Surreal Sync, or write it out as SurrealQL `INSERT` statements and load the file with [`surreal db import`](/docs/reference/cli/db/commands/import.md), which takes a SurrealQL file. You can also use [one of the many available SDKs](/docs/languages.md) to read from your existing database and transfer its content directly to a SurrealDB instance.

## From an older SurrealDB version

The [upgrade guides](/docs/operate/upgrading.md) explain how to upgrade, with a guide for each version change: [1.x to 2.x](/docs/operate/upgrading/1x-to-2x.md), [2.6 to 2.7](/docs/operate/upgrading/26-to-27.md), [2.x to 3.x](/docs/operate/upgrading/2x-to-3x.md), [3.2 to 3.3](/docs/operate/upgrading/32-to-33.md) and [3.x to 4.0](/docs/operate/upgrading/3x-to-4x.md).

## Moving between SurrealDB Cloud instances

A Free instance moves to a paid instance type in place, from the **Compute** tab of its settings, with no migration. See [Scaling](/docs/operate/instances/scaling.md#scaling-a-start-instance).

Moving from Start to Scale, or to another region, needs a new instance. Deploy it, then [restore a backup](/docs/operate/instances/backups.md) or [import an export](/docs/operate/instances/import-and-export.md) into it.

---

Source: https://surrealdb.com/docs/integrate/migrating/from-files-and-streams/csv

# Importing CSV data

SurrealDB Studio can be used to import CSV data to SurrealDB.

This page details some methods to import CSV data to SurrealDB.

## Using SurrealDB Studio

CSV data is the easiest external data type to import to SurrealDB, as it can be imported directly via the [SurrealDB Studio](/docs/reference/studio.md) UI.

Importing the data is done by going to the Explorer tab, clicking on Import database below, and following the prompts. For more details, see [this page](/docs/reference/studio.md) in the SurrealDB Studio documentation.

## Importing CSV data using Surreal Sync

The [Surreal Sync](https://github.com/surrealdb/surreal-sync) tool can be used to import CSV files in the local filesystem or S3 buckets into a SurrealDB table with automatic type detection and optional record ID generation.

For more on how this is done, please see the [CSV Import for Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/csv.md) page in its repo.

---

Source: https://surrealdb.com/docs/integrate/migrating/from-files-and-streams/json-lines

# Importing JSON Lines data

Import JSON Lines files with Surreal Sync, and the type mapping.

This page details JSON data types and their SurrealQL equivalents, followed by links to the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool which allows this data to be automatically imported to SurrealDB.

## Data types

|      JSON Data Type      |           JSON Representation            | Recommended SurrealQL type    |
| ------------------------ | ---------------------------------------- | ----------------------------- |
| **String**               | `"text"`                                 | `string`                      |
| **Number**               | `42` or `3.14`                           | `int`, `float`, or `decimal`  |
| **Boolean**              | `true`/`false`                           | `bool`                        |
| **null**                 | `null`                                   | `none` or `null`              |
| **Array**                | `[1, 2, 3]`                              | `array` or `set`              |
| **Object**               | `{"key": "value"}`                       | `object`                      |
| **ISO 8601 Date String** | `"2024-01-15T14:30:00Z"`                 | `datetime` or `string`        |
| **UUID String**          | `"550e8400-e29b-41d4-a716-446655440000"` | `uuid` or `string`            |
| **Base64 String**        | `"SGVsbG8gV29ybGQ="`                     | `bytes` or `string`           |

## Importing JSON Lines data using Surreal Sync

The JSONL source in Surreal Sync allows you to import JSON Lines (JSONL) files into SurrealDB. Each JSONL file becomes a table in SurrealDB, and each line in the file becomes a document in that table.

For more on how to import JSON Lines data to SurrealDB, please see the following pages in the Surreal Sync repo.

* [JSONL Source Usage Guide](https://github.com/surrealdb/surreal-sync/blob/main/docs/jsonl.md)
* [JSONL Data Types Support in Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/jsonl.md)

---

Source: https://surrealdb.com/docs/integrate/migrating/from-files-and-streams/kafka

# Importing Kafka data

SurrealDB's Surreal Sync tool can be used to import Kafka data to SurrealDB.

Kafka data can be imported to SurrealDB using the Surreal Sync tool, as follows:

* The specified Kafka topic becomes a table in SurrealDB, where each message from the topic becomes a record in the table, with configurable deduplication.
* Each Kafka message must be encoded using Protobuf. The Kafka source decodes every message payload using Protobuf and converts it into SurrealDB Upsert queries, transforming the payloads into SurrealDB records.
* Message Key Strategy: Use Kafka message keys as record IDs (base64 encoded)
* Field Strategy: Extract IDs from a field in the message payload (default: "id" field)

For more on how to import Kafka data to SurrealDB, please see the [Kafka Source Usage Guide](https://github.com/surrealdb/surreal-sync/blob/main/docs/kafka.md) page in the Surreal Sync repo.

---

Source: https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-mongodb

# Migrating from MongoDB

How to map existing data and concepts from MongoDB to SurrealDB

This page details some MongoDB data types and their SurrealQL equivalents, followed by links to the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool which allows data from MongoDB to be automatically imported to SurrealDB.

## Data types

The following chart shows MongoDB data types along with the equivalent or near-equivalent [SurrealQL data type](/docs/reference/query-language/language-primitives/data-types.md) for each.

|     MongoDB Data Type     |        BSON Type        |                                          JSON Extended Format v2                                           | SurrealDB Mapping |
| ------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------- |
| **Double**                | Double                  | `3.14` (Relaxed) or `{"$numberDouble": "3.14"}` (Canonical)                                                | `float`           |
| **String**                | String                  | `"text"`                                                                                                   | `string`          |
| **Object**                | Document                | `{"key": "value"}`                                                                                         | `object`          |
| **Array**                 | Array                   | `[1, 2, 3]`                                                                                                | `array`           |
| **Binary data**            | Binary                  | `{"$binary": {"base64": "...", "subType": "..."}}`                                                         | `bytes`           |
| **Undefined**             | Undefined               | `{"$undefined": true}`                                                                                     | `none`            |
| **ObjectId**              | ObjectId                | `{"$oid": "507f1f77bcf86cd799439011"}`                                                                     | `string`          |
| **Boolean**               | Boolean                 | `true`/`false`                                                                                             | `bool`            |
| **Date**                  | DateTime                | `{"$date": "2024-01-01T00:00:00Z"}` (Relaxed) or `{"$date": {"$numberLong": "1672531200000"}}` (Canonical) | `datetime`        |
| **Null**                  | Null                    | `null`                                                                                                     | `null`            |
| **Regular Expression**    | RegularExpression       | `{"$regularExpression": {"pattern": "...", "options": "..."}}`                                             | `regex`           |
| **DBPointer**             | DbPointer               | `{"$dbPointer": {"$ref": "...", "$id": {...}}}`                                                            | `string`          |
| **JavaScript**            | JavaScriptCode          | `{"$code": "function(){}"}`                                                                                | `string`          |
| **Symbol**                | Symbol                  | `{"$symbol": "text"}`                                                                                      | `string`          |
| **JavaScript with scope** | JavaScriptCodeWithScope | `{"$code": "...", "$scope": {...}}`                                                                        | `object`          |
| **32-bit integer**        | Int32                   | `42` (Relaxed) or `{"$numberInt": "42"}` (Canonical)                                                       | `int`             |
| **Timestamp**             | Timestamp               | `{"$timestamp": {"t": 1672531200, "i": 1}}`                                                                | `datetime`        |
| **64-bit integer**        | Int64                   | `{"$numberLong": "123"}`                                                                                   | `int`             |
| **Decimal128**            | Decimal128              | `{"$numberDecimal": "123.45"}`                                                                             | `number`          |
| **DBRef**                 | Document                | `{"$ref": "users", "$id": "123"}`                                                                          | `thing`           |
| **Min key**               | MinKey                  | `{"$minKey": 1}`                                                                                           | `object`          |
| **Max key**               | MaxKey                  | `{"$maxKey": 1}`                                                                                           | `object`          |

## Importing from MongoDB using Surreal Sync

Surreal Sync can be used to export MongoDB collections to SurrealDB.

It supports inconsistent full syncs and consistent incremental syncs, and together these provide the ability to reproduce consistent snapshots from the source MongoDB collections onto the target SurrealDB tables.

For more on how to import data from MongoDB to SurrealDB, please see the following pages in the Surreal Sync repo.

* [Surreal Sync for MongoDB](https://github.com/surrealdb/surreal-sync/blob/main/docs/mongodb.md)
* [MongoDB Data Types Support in Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/mongodb-data-types.md)

---

Source: https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-mysql

# Migrating from MySQL

How to map existing data and concepts from MySQL to SurrealDB

This page details some MySQL data types and their SurrealQL equivalents, followed by links to the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool which allows data from MySQL to be automatically imported to SurrealDB.

From SurrealDB 4.0, MySQL clients and drivers can also connect to SurrealDB directly and run MySQL queries. See the [MySQL wire protocol](/docs/reference/protocols/mysql-protocol.md) page, which also lists the builds that include the listener.

## Data types

The following chart shows MySQL data types along with the equivalent or near-equivalent [SurrealQL data type](/docs/reference/query-language/language-primitives/data-types.md) for each.

|   MySQL Data Type   | Wire Protocol Type |               SQL Representation                | SurrealDB Mapping |                     Notes                      |
| ------------------- | ------------------ | ----------------------------------------------- | ----------------- | ---------------------------------------------- |
| **BOOLEAN/BOOL**    | Tiny               | `0`/`1`                                         | `bool`            | 0=false, 1=true conversion                     |
| **TINYINT**         | Tiny               | `-128` to `127`                                 | `int`             | Converted to 64-bit integer                    |
| **SMALLINT**        | Short              | `-32768` to `32767`                             | `int`             | Converted to 64-bit integer                    |
| **MEDIUMINT**       | Int24              | `-8388608` to `8388607`                         | `int`             | Converted to 64-bit integer                    |
| **INT/INTEGER**     | Long               | `-2147483648` to `2147483647`                   | `int`             | Converted to 64-bit integer                    |
| **BIGINT**          | LongLong           | `-9223372036854775808` to `9223372036854775807` | `int`             | Direct conversion                              |
| **FLOAT**           | Float              | `3.14`                                          | `float` (f64)     | Converted to double precision                  |
| **DOUBLE**          | Double             | `3.141592653589793`                             | `float` (f64)     | Direct conversion                              |
| **DECIMAL/NUMERIC** | NewDecimal         | `123.45`                                        | `number`          | Converted to SurrealDB Number with precision   |
| **CHAR(n)**         | String             | `'text'`                                        | `string`          | Fixed-length, padding removed                  |
| **VARCHAR(n)**      | VarString          | `'text'`                                        | `string`          | Variable-length string                         |
| **TEXT**            | Blob               | `'long text'`                                   | `string`          | Text blob as string                            |
| **TINYTEXT**        | TinyBlob           | `'short text'`                                  | `string`          | Small text as string                           |
| **MEDIUMTEXT**      | MediumBlob         | `'medium text'`                                 | `string`          | Medium text as string                          |
| **LONGTEXT**        | LongBlob           | `'very long text'`                              | `string`          | Large text as string                           |
| **BINARY(n)**       | String             | `0x48656c6c6f`                                  | `bytes`           | Fixed-length binary data                       |
| **VARBINARY(n)**    | VarString          | `0x48656c6c6f`                                  | `bytes`           | Variable-length binary data                    |
| **BLOB**            | Blob               | `0x48656c6c6f`                                  | `bytes`           | Binary large object                            |
| **TINYBLOB**        | TinyBlob           | `0x48656c6c6f`                                  | `bytes`           | Small binary data                              |
| **MEDIUMBLOB**      | MediumBlob         | `0x48656c6c6f`                                  | `bytes`           | Medium binary data                             |
| **LONGBLOB**        | LongBlob           | `0x48656c6c6f`                                  | `bytes`           | Large binary data                              |
| **DATE**            | Date               | `'2024-01-15'`                                  | `datetime`        | Converted to datetime at midnight UTC          |
| **TIME**            | Time               | `'14:30:00'`                                    | `string`          | Time format as string (HH:MM:SS.microseconds)  |
| **DATETIME**        | DateTime           | `'2024-01-15 14:30:00'`                         | `datetime`        | Converted to UTC datetime                      |
| **TIMESTAMP**       | Timestamp          | `'2024-01-15 14:30:00'`                         | `datetime`        | Timezone-aware, converted to UTC               |
| **YEAR**            | Year               | `2024`                                          | `int`             | Year as integer                                |
| **JSON**            | Json               | `'{"key": "value"}'`                            | `object`          | Parsed and converted recursively               |
| **GEOMETRY**        | Geometry           | `ST_GeomFromText('POINT(1 2)')`                 | `object`          | Converted to geometric object with coordinates |
| **POINT**           | Geometry           | `POINT(1.5, 2.5)`                               | `object`          | Converted to `{"x": 1.5, "y": 2.5}` object     |
| **ENUM**            | Enum               | `'option1'`                                     | `string`          | Enum value as string, constraints lost         |
| **SET**             | Set                | `'value1,value2'`                               | `array`           | Converted to array of strings                  |
| **BIT(n)**          | Bit                | `b'1010'`                                       | `string`          | Bit string as binary string representation     |

## Importing from MySQL using Surreal Sync

Surreal Sync can be used to export MySQL tables to SurrealDB.

It supports inconsistent full syncs and consistent incremental syncs, and together these provide the ability to reproduce consistent snapshots from the source MySQL tables onto the target SurrealDB tables.

For more on how to import data from MySQL to SurrealDB, please see the following pages in the Surreal Sync repo.

* [Surreal Sync for MySQL](https://github.com/surrealdb/surreal-sync/blob/main/docs/mysql.md)
* [MySQL Data Types Support in Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/mysql-data-types.md)

---

Source: https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-neo4j

# Migrating from Neo4j

How to map existing data and concepts from Neo4j to SurrealDB

This page details some Neo4j data types and patterns in the Cypher query language along with their SurrealQL equivalents or near equivalents, followed by links to the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool which allows data from Neo4j to be automatically imported to SurrealDB.

## Concept mapping

<table>
    <thead>
        <tr>
            <th colspan="2" scope="col">Neo4j</th>
            <th colspan="2" scope="col">SurrealDB</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                database
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                database
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                node label
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                table
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                node
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                record
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                node property
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                field
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                index
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                index
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                id
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                record id
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                transactions
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                transactions
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Neo4j">
                relationships
            </td>
            <td colspan="2" scope="row" data-label="SurrealDB">
                record links, embedding and graph relations
            </td>
        </tr>
    </tbody>
</table>

## Data types

The following chart shows Neo4j data types along with the equivalent or near-equivalent SurrealQL data type for each.

| Neo4j Data Type    | SurrealDB Mapping | Notes                                                                                     |
|--------------------|-------------------|-------------------------------------------------------------------------------------------|
| **Boolean**        | `bool`            |                                                                         |
| **Integer**        | `int`             |                                                                     |
| **Float**          | `float` (f64)     |                                                                          |
| **String**         | `string`          |                                                                          |
| **List**           | `array`           |                                              |
| **Map**            | `object`          |                                                |
| **Null**           | `null`            |                                                                         |
| **Date**           | `datetime`        | Convert to UTC datetime (assuming local timezone)                                        |
| **DateTime**       | `datetime`        | Convert to UTC datetime                                                                 |
| **LocalDateTime**  | `datetime`        | Convert to UTC datetime (assuming UTC)                                                   |
| **Duration**       | `duration`        |                                                                          |
| **Bytes**          | `bytes`           |                                                                          |
| **Time**           | `object`          | Convert to object with `type: "$Neo4jTime"`, hour, minute, second, nanosecond, offset_seconds fields |
| **LocalTime**      | `object`          | Convert to object with `type: "$Neo4jLocalTime"`, hour, minute, second, nanosecond fields |
| **Point2D**        | `object`          | Convert to GeoJSON-like object with `type: "Point"`, `srid` (4326), `coordinates: [longitude, latitude]`            |
| **Point3D**        | `object`          | Convert to GeoJSON-like object with `type: "Point"`, `srid` (4979), `coordinates: [longitude, latitude, elevation]` |
| **DateTimeZoneId** | `datetime`        | Convert to UTC datetime using embedded timezone ID                                      |

## Syntax mapping

The following shows some CRUD examples using SurrealQL syntax.

### Create

As Neo4j is schemaless, only the SurrealQL schemaless approach is shown below. For a schemafull option see the [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md) page.

For more SurrealQL examples, see the [`CREATE`](/docs/reference/query-language/statements/create.md), [`INSERT`](/docs/reference/query-language/statements/insert.md) and [`RELATE`](/docs/reference/query-language/statements/relate.md) pages.

Simple create/insert operations:

```cypher
// Cypher
CREATE (John:Person {name:'John'}), (Jane:Person {name: 'Jane'})
```

```surql
-- SurrealQL
-- Table implicitly created if it doesn't exist
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ]
```

Graph relations via the [RELATE](/docs/reference/query-language/statements/relate.md) statement:

```cypher
// Cypher
MATCH (p:Person {name:'Jane'}), (pr:Product {name:'iPhone'}) CREATE (p)-[:ORDER]->(pr)
```

```surql
-- SurrealQL
RELATE person:Jane->order->product:iPhone
```

Defining an index:

```cypher
// Cypher
CREATE INDEX personNameIndex FOR (p:Person) ON (p.name)
```

```surql
-- SurrealQL
DEFINE INDEX idx_name ON TABLE person FIELDS name
```

### Read

For more SurrealQL examples, see the [`SELECT`](/docs/reference/query-language/statements/select.md), [`LIVE SELECT`](/docs/reference/query-language/statements/live-select.md) and [`RETURN`](/docs/reference/query-language/statements/return.md) pages.

Returning all the fields of a table:

```cypher
// Cypher
MATCH (p:Person) RETURN p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT * FROM person
```

Returning a single field of a table:

```cypher
// Cypher
MATCH (p:Person) RETURN p.name
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT name FROM person
```

Using the `WHERE` clause to return certain records:

```cypher
// Cypher
MATCH (p:Person) WHERE p.name = "Jane" RETURN p.name
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT name FROM person WHERE name = "Jane"
```

Using `EXPLAIN` to detail the query plan used:

```cypher
// Cypher
EXPLAIN MATCH (p:Person) WHERE p.name = "Jane" RETURN p.name
```

```surql
-- SurrealQL
SELECT name FROM person WHERE name = "Jane" EXPLAIN
```

Grouping and counting the number of records returned:

```cypher
// Cypher
MATCH (p:Person) RETURN count(*) as person_count
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT count() AS person_count FROM person GROUP ALL
```

See all distinct values for a field among the records of a table:

```cypher
// Cypher
MATCH (p:Person) RETURN distinct p.name
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT array::distinct(name) FROM person GROUP ALL
```

Returning up to a certain number of records:

```cypher
// Cypher
MATCH (p:Person) RETURN p LIMIT 10
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

SELECT * FROM person LIMIT 10
```

See which `person` records have ordered a `product` via the `order` graph edge:

```cypher
// Cypher
MATCH (p:Person)-[:ORDER]->(pr:Product) RETURN p.name, pr.name
```

```surql
-- SurrealQL
-- Setup from the examples above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];
CREATE product:iPhone CONTENT { name: "iPhone" };
RELATE person:Jane->order->product:iPhone;

SELECT name, ->order->product.name FROM person
```

Following a relationship a fixed number of times. SurrealQL uses a [recursive path](/docs/reference/query-language/language-primitives/idioms.md#recursive-paths), where `.{2}` repeats the path in parentheses twice:

```cypher
// Cypher
MATCH (:Person {id: 'a'})-[:KNOWS*2]->(p:Person) RETURN p
```

```surql
-- SurrealQL
person:a.{2}(->knows->person)
```

Following a relationship a variable number of times, returning every person reached. `+collect` gathers each person once, however many paths lead to them:

```cypher
// Cypher: from one to three hops, or any number with *1..
MATCH (:Person {id: 'a'})-[:KNOWS*1..3]->(p:Person) RETURN DISTINCT p
```

```surql
-- SurrealQL: from one to three hops, or any number with .{..+collect}
person:a.{1..3+collect}(->knows->person)
```

A path without an upper bound stops at a depth of 256, which is the fixed limit for recursive paths.

Following a relationship in either direction. `<->` returns both ends of each edge, and that includes the starting record, so filter it out to match Cypher:

```cypher
// Cypher
MATCH (:Person {id: 'c'})-[:KNOWS]-(p:Person) RETURN p
```

```surql
-- SurrealQL
(person:c<->knows<->person).filter(|$p| $p != person:c)
```

Returning every node along a path, filtered by a property on the first node. Cypher returns `a`, `b` and `c` as separate columns of one row per path. SurrealQL returns one result per starting record, with each level nested inside the one before it, using [destructuring](/docs/reference/query-language/language-primitives/idioms.md#destructuring):

```cypher
// Cypher
MATCH (s:Service {env: 'prod'})-[:RUNS_ON]->(h:Host)-[:USES]->(d:Disk) RETURN s, h, d
```

```surql
-- SurrealQL
-- Setup
INSERT INTO service { id: 'api', name: 'api', env: 'prod' };
INSERT INTO host [
	{ id: 'h1', name: 'h1', region: 'eu' },
	{ id: 'h2', name: 'h2', region: 'us' }
];
INSERT INTO disk [
	{ id: 'd1', size: 100 },
	{ id: 'd2', size: 500 },
	{ id: 'd3', size: 50 }
];
RELATE service:api->runs_on->[host:h1, host:h2];
RELATE host:h1->uses->[disk:d1, disk:d2];
RELATE host:h2->uses->disk:d3;

SELECT
    name,
    ->runs_on->host.{ name, region, disks: ->uses->disk.{ id, size } } AS hosts
FROM service WHERE env = 'prod';
```

```surql title="Possible output"
[
	{
		hosts: [
			{
				disks: [
					{ id: disk:d1, size: 100 },
					{ id: disk:d2, size: 500 }
				],
				name: 'h1',
				region: 'eu'
			},
			{
				disks: [{ id: disk:d3, size: 50 }],
				name: 'h2',
				region: 'us'
			}
		],
		name: 'api'
	}
]
```

The order of the hosts depends on the IDs of the edges, which are random unless you set them. To filter the nodes at any level, as a Cypher `WHERE` on `h` or `d` would, put the condition in parentheses after the table name in the path:

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO service { id: 'api', name: 'api', env: 'prod' };
INSERT INTO host [
	{ id: 'h1', name: 'h1', region: 'eu' },
	{ id: 'h2', name: 'h2', region: 'us' }
];
INSERT INTO disk [
	{ id: 'd1', size: 100 },
	{ id: 'd2', size: 500 },
	{ id: 'd3', size: 50 }
];
RELATE service:api->runs_on->[host:h1, host:h2];
RELATE host:h1->uses->[disk:d1, disk:d2];
RELATE host:h2->uses->disk:d3;

-- Only hosts in the eu region, and only their disks over 80
SELECT
    name,
    ->runs_on->(host WHERE region = 'eu').{
        name,
        disks: ->uses->(disk WHERE size > 80).size
    } AS hosts
FROM service WHERE env = 'prod';
```

```surql title="Output"
[
	{
		hosts: [{ disks: [100, 500], name: 'h1' }],
		name: 'api'
	}
]
```

To get the records at the end of the path without the structure, leave out the destructuring: `service:api->runs_on->host->uses->disk` returns the disks as one flat array.

### Update

For more SurrealQL examples, see the [`UPDATE`](/docs/reference/query-language/statements/update.md) page.

Conditionally updating records that have a certain value for a field:

```cypher
// Cypher
MATCH (p:Person)  WHERE p.name = "Jane"  SET p.last_name = 'Doe'  RETURN p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

UPDATE person SET last_name = "Doe" WHERE name = "Jane"
```

Unsetting (removing) the value of a field for certain records:

```cypher
// Cypher
MATCH (p:Person)   WHERE p.name = "Jane"   REMOVE p.last_name RETURN p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

UPDATE person UNSET last_name WHERE name = "Jane"
```

### Delete

For more SurrealQL examples, see the [`DELETE`](/docs/reference/query-language/statements/delete.md) and [`REMOVE`](/docs/reference/query-language/statements/remove.md) pages.

Conditionally deleting records based on the value of a field:

```cypher
// Cypher
MATCH (p:Person)  WHERE p.name = "Jane"  DELETE p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

DELETE person WHERE name = "Jane"
```

Deleting all records for a table (SurrealQL: table still exists):

```cypher
// Cypher
MATCH (p:Person)  DELETE p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

DELETE person
```

Deleting all records and table definition for a table:

```cypher
// Cypher
MATCH (p:Person)  DELETE p
```

```surql
-- SurrealQL
-- Setup from the example above
INSERT INTO person [ {id: "John", name: "John"}, {id: "Jane", name: "Jane"} ];

REMOVE TABLE person
```

## Importing from Neo4j using Surreal Sync

Surreal Sync can be used to export Neo4j nodes and relationships to SurrealDB.

It supports inconsistent full syncs and consistent incremental syncs, and together these provide the ability to reproduce consistent snapshots from the source Neo4j graph onto the target SurrealDB tables.

For more on how to import data from Neo4j to SurrealDB, please see the following pages in the Surreal Sync repo.

* [Surreal Sync for Neo4j](https://github.com/surrealdb/surreal-sync/blob/main/docs/neo4j.md)
* [Neo4j Data Types Support in Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/neo4j-data-types.md)

---

Source: https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-postgresql

# Migrating from PostgreSQL

How to map existing data and concepts from PostgreSQL to SurrealDB

This page details some common PostgreSQL patterns and their SurrealQL equivalents, followed by links to the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool which allows data from PostgreSQL to be automatically imported to SurrealDB.

Agent prompt:

```text
Help me move this project's PostgreSQL database to SurrealDB. Read https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-postgresql.md first, and agree a plan with me before you change anything.
```

## Importing from PostgreSQL using Surreal Sync

For more on how to import data from PostgreSQL to SurrealDB, please see the following pages in the Surreal Sync repo.

* [Surreal Sync for PostgreSQL (Trigger-Based)](https://github.com/surrealdb/surreal-sync/blob/main/docs/postgresql.md)
* [PostgreSQL wal2json Source](https://github.com/surrealdb/surreal-sync/blob/main/docs/postgresql-wal2json-source.md)
* [PostgreSQL Data Types Support in Surreal Sync](https://github.com/surrealdb/surreal-sync/blob/main/docs/postgresql-data-types.md)

Surreal Sync reads from a running PostgreSQL server through a connection string, and has no source that reads a `pg_dump` file. `surreal db import` cannot read one either, because it expects SurrealQL. To migrate from a dump, restore it into a PostgreSQL server first, such as a temporary one in Docker, and run Surreal Sync against that server. For a small number of tables, another option is to export each table to CSV with the PostgreSQL `COPY` command and [import the CSV files](/docs/integrate/migrating/from-files-and-streams/csv.md).

## Data types

The following chart shows PostgreSQL data types along with the equivalent or near-equivalent [SurrealQL data type](/docs/reference/query-language/language-primitives/data-types.md) for each.

| PostgreSQL Data Type | Wire Protocol Type |            SQL Representation            | SurrealDB Mapping |                            Notes                             |
| -------------------- | ------------------ | ---------------------------------------- | ----------------- | ------------------------------------------------------------ |
| **BOOLEAN**          | Boolean            | `true`/`false`                           | `bool`            |                                             |
| **SMALLINT**         | Int2               | `32767`                                  | `int`             |                                   |
| **INTEGER**          | Int4               | `2147483647`                             | `int`             |                                  |
| **BIGINT**           | Int8               | `9223372036854775807`                    | `int`             |                                             |
| **SERIAL**           | Int4               | `1, 2, 3...`                             | `int`             | Auto-increment converted to regular integer                  |
| **BIGSERIAL**        | Int8               | `1, 2, 3...`                             | `int`             | Auto-increment converted to regular integer                  |
| **REAL**             | Float4             | `3.14`                                   | `float` (f64)     | Converted to double precision                                |
| **DOUBLE PRECISION** | Float8             | `3.141592653589793`                      | `float` (f64)     |                                             |
| **NUMERIC/DECIMAL**  | Numeric            | `123.45`                                 | `number`          | Converted to SurrealDB Number with exact precision preserved |
| **MONEY**            | Money              | `$123.45`                                | `number`          | Currency symbol removed, converted to number                 |
| **CHAR(n)**          | Bpchar             | `'text'`                                 | `string`          | Fixed-length, padding removed                                |
| **VARCHAR(n)**       | Varchar            | `'text'`                                 | `string`          | Variable-length string                                       |
| **TEXT**             | Text               | `'long text'`                            | `string`          | Unlimited length string                                      |
| **BYTEA**            | Bytea              | `\\x48656c6c6f`                          | `bytes`           | Binary data, hex decoded                                     |
| **DATE**             | Date               | `'2024-01-15'`                           | `datetime`        | Converted to datetime at midnight UTC                        |
| **TIME**             | Time               | `'14:30:00'`                             | `string`          | Time-only as string (SurrealDB has no pure time type)        |
| **TIMESTAMP**        | Timestamp          | `'2024-01-15 14:30:00'`                  | `datetime`        | Converted to UTC datetime                                    |
| **TIMESTAMPTZ**      | Timestamptz        | `'2024-01-15 14:30:00+00'`               | `datetime`        | Timezone-aware, converted to UTC                             |
| **INTERVAL**         | Interval           | `'1 day 2 hours'`                        | `duration`        | Converted to SurrealDB duration                              |
| **UUID**             | Uuid               | `'550e8400-e29b-41d4-a716-446655440000'` | `string`          | UUID string representation                                   |
| **JSON**             | Json               | `'{"key": "value"}'`                     | `string`          | JSON stored as string representation                         |
| **JSONB**            | Jsonb              | `'{"key": "value"}'`                     | `string`          | Binary JSON stored as string representation                  |
| **ARRAY**            | Array              | `'{1,2,3}'`                              | `array`           | Recursively processed, element types converted               |
| **POINT**            | Point              | `'(1.5, 2.5)'`                           | `object`          | Convert to `{"x": 1.5, "y": 2.5}` object                   |
| **LINE**             | Line               | `'{1,2,3}'`                              | `object`          | Convert to coefficient object                              |
| **LSEG**             | Lseg               | `'[(1,2),(3,4)]'`                        | `object`          | Line segment as start/end point object                       |
| **BOX**              | Box                | `'(1,2),(3,4)'`                          | `object`          | Bounding box as corner points object                         |
| **PATH**             | Path               | `'[(1,2),(3,4)]'`                        | `array`           | Array of point objects                                       |
| **POLYGON**          | Polygon            | `'((1,2),(3,4),(5,6))'`                  | `array`           | Array of point objects                                       |
| **CIRCLE**           | Circle             | `'<(1,2),3>'`                            | `object`          | Center point and radius object                               |
| **INET**             | Inet               | `'192.168.1.1'`                          | `string`          | IP address as string                                         |
| **CIDR**             | Cidr               | `'192.168.0.0/24'`                       | `string`          | Network address as string                                    |
| **MACADDR**          | Macaddr            | `'08:00:2b:01:02:03'`                    | `string`          | MAC address as string                                        |

## Inserting data

```sql
// PostgreSQL
INSERT INTO product
    (name, description, price, category, images, options)
    VALUES
    ("Shirt", "Slim fit", 6, "clothing", ARRAY['image1.jpg', 'image2.jpg', 'image3.jpg'])
;
```

```surql
-- SurrealQL
CREATE product CONTENT {
    name: 'Shirt',
    id: 'shirt',
    description: 'Slim fit',
    price: 6,
    category: 'clothing',
    images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
};
```

## Defining a schemafull table

A table in PostgreSQL might be defined as follows.

```sql
CREATE TABLE product (
    id SERIAL PRIMARY KEY,
    name TEXT,
    description TEXT,
    price NUMERIC(8,2),
    category TEXT,
    images TEXT[]
);
```

In SurrealQL, a table does not by default need to be defined before it can be used. However, the following statements will produce a strict schema similar to the PostgreSQL one above.

```surql
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD name ON TABLE product TYPE string;
DEFINE FIELD description ON TABLE product TYPE string;
DEFINE FIELD price ON TABLE product 
    TYPE number 
    -- Only show two digits after decimal point
    VALUE math::fixed($value, 2) 
    -- Price must be within this range
    ASSERT $value IN 0..=99999999;
DEFINE FIELD category ON TABLE product TYPE string;
DEFINE FIELD images ON TABLE product TYPE array<string>;
```

One difference between this and the PostgreSQL schema above is that a `product` will have a randomly generated ID as opposed to an incrementing one.

```surql
CREATE product SET 
    name = 'Shirt', 
    description = 'Nice shirt', 
    price = 20.449, 
    category = 'Clothing', 
    images = ["some_img.ping", "another_img.png"];

-- Output
[
	{
		category: 'Clothing',
		description: 'Nice shirt',
		id: product:1j29aq5q0do48k6xvyem,
		images: [
			'some_img.ping',
			'another_img.png'
		],
		name: 'Shirt',
		price: 20.45f
	}
]
```

### Selecting data

Selecting records using an ID:

```sql
// PostgreSQL
SELECT * FROM product WHERE id=1;
```

```surql
-- Setup from the example above
CREATE product CONTENT {
    name: 'Shirt',
    id: 'shirt',
    description: 'Slim fit',
    price: 6,
    category: 'clothing',
    images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
};

-- SurrealQL
SELECT * FROM product:shirt;
```

Selecting multiple specific records:

```sql
// PostgreSQL
SELECT * FROM product WHERE id IN (1, 2, 3);
```

```surql
-- Setup from the example above
CREATE product CONTENT {
    name: 'Shirt',
    id: 'shirt',
    description: 'Slim fit',
    price: 6,
    category: 'clothing',
    images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
};

-- SurrealQL
SELECT * FROM [product:1, product:2, product:3];
```

Counting the number of records in a table:

```sql
// PostgreSQL
SELECT COUNT(*) FROM product;
```

```surql
-- Setup from the example above
CREATE product CONTENT {
    name: 'Shirt',
    id: 'shirt',
    description: 'Slim fit',
    price: 6,
    category: 'clothing',
    images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
};

-- SurrealQL
SELECT count() FROM product GROUP ALL;
```

### Queries with identical syntax

As SurrealQL is inspired by SQL, many queries between it and PostgreSQL are identical.

```surql
-- Setup from the example above
CREATE product CONTENT {
    name: 'Shirt',
    id: 'shirt',
    description: 'Slim fit',
    price: 6,
    category: 'clothing',
    images: ['image1.jpg', 'image2.jpg', 'image3.jpg']
};

-- Setup
CREATE order_item SET product = product:shirt, quantity = 2;
CREATE order_item SET product = product:shirt, quantity = 1;

SELECT * FROM product LIMIT 5;
SELECT name, price FROM product;
SELECT * FROM product ORDER BY price DESC;
SELECT * FROM order_item WHERE quantity = 2;
```

### Using record ID instead of the `WHERE` clause

If a record ID is known ahead of time and you are using a version of SurrealDB before 3.0, be sure to query by the record ID itself instead of using a `WHERE` clause in SurrealQL. This will avoid a full table scan if the field is not indexed.

```sql
// PostgreSQL
SELECT * FROM product WHERE id = 1;

// Immediate access in SurrealDB 3.0+, table scan in previous versions
SELECT * FROM product WHERE id = product:1;

// Accessing the record directly will
// take a fraction of the time in 2.x
product:1.*;
```

### Joining and querying related tables

Take the following query with joins in PostgreSQL:

```sql
SELECT p.id AS product_id, p.name AS product_name
FROM product p
JOIN order_item oi ON p.id = oi.product_id
JOIN customer_order co ON oi.order_id = co.order_id
JOIN customer c ON co.customer_id = c.customer_id
WHERE c.name = 'Pratim'
ORDER BY p.id;
```

In SurrealQL, tables can be joined to each other via edges, such as the `bought` edge in this example.

```surql
-- Relate a 'customer' to a 'product' via 'bought'
RELATE customer:tobie->bought->product:iphone CONTENT {
    option: { Size: 'M', Color: 'Max' },
    quantity: 1,
    total: 600,
    status: 'Pending',
    created_at: time::now()
};
```

Once the tables have been related (joined), they can be queried with this syntax.

```surql
SELECT * FROM customer:tobie->bought;
```

An example of more complex query with joins to return all people who bought the same products as a certain customer (including the original customer).

```sql
// PostgreSQL
SELECT DISTINCT c.*
FROM customer c
JOIN customer_order co ON c.customer_id = co.customer_id
JOIN order_item oi ON co.order_id = oi.order_id
JOIN product p ON oi.product_id = p.id
WHERE p.id IN (
    -- Subquery: Get all product IDs bought by Tobie
    SELECT p2.id
    FROM product p2
    JOIN order_item oi2 ON p2.id = oi2.product_id
    JOIN customer_order co2 ON oi2.order_id = co2.order_id
    JOIN customer c2 ON co2.customer_id = c2.customer_id
    WHERE c2.name = 'Tobie'
)
```

```surql
-- SurrealQL
customer:tobie->bought->product<-bought<-customer.*;
```

Each `JOIN` in the PostgreSQL query crosses a foreign key, while the SurrealQL path walks the `bought` edges out to Tobie's products and back to everyone who bought them:

<img src="~/assets/img/diagrams/light/join-vs-graph-light.webp" darkSrc="~/assets/img/diagrams/join-vs-graph.webp" alt="On the left, four PostgreSQL tables joined in a chain: customer, customer_order, order_item and product. On the right, customer:tobie has bought edges to product:iphone and product:ipad, which customer:jaime and customer:pratim also bought. The path customer:tobie->bought->product<-bought<-customer reaches Jaime, Pratim and Tobie, but not customer:martin, who bought only product:watch." />

---

Source: https://surrealdb.com/docs/integrate/migrating/from-other-databases/from-snowflake

# Migrating from Snowflake

How to map existing data and concepts from Snowflake to SurrealDB

This page shows how Snowflake data types map to their SurrealQL equivalents, then explains how to load Snowflake tables into SurrealDB with the [Surreal Sync](https://github.com/surrealdb/surreal-sync/) tool.

## Data types

The following chart shows Snowflake data types along with the equivalent or near-equivalent [SurrealQL data type](/docs/reference/query-language/language-primitives/data-types.md) for each. Surreal Sync reads values through the Snowflake SQL REST API, which returns every cell as a string together with the column's logical type, and converts each one using that type.

| Snowflake Data Type | SurrealDB Mapping | Notes |
| ------------------- | ----------------- | ----- |
| **BOOLEAN**         | `bool`            |                                                              |
| **NUMBER / INT / INTEGER / BIGINT** | `int` | Whole numbers (scale 0) that fit a 64-bit integer      |
| **NUMBER(p,s) / DECIMAL / NUMERIC** | `number` | Values with a scale, or larger than a 64-bit integer, keep their precision and scale as a decimal |
| **FLOAT / REAL / DOUBLE** | `float` (f64) | Double-precision floating point                         |
| **VARCHAR / STRING / TEXT / CHAR** | `string` |                                                       |
| **DATE**            | `datetime`        | Stored as days since the Unix epoch, converted to a datetime at midnight UTC |
| **TIME**            | `datetime`        | Seconds since midnight                                        |
| **TIMESTAMP_NTZ / DATETIME** | `datetime` | No timezone; taken as the given wall-clock instant           |
| **TIMESTAMP_LTZ / TIMESTAMP_TZ / TIMESTAMP** | `datetime` | Timezone-aware; the absolute instant is preserved as UTC     |
| **VARIANT / OBJECT** | `object`         | Parsed from the stored JSON document                         |
| **ARRAY**           | `array`           | Parsed from the stored JSON array                            |
| **BINARY / VARBINARY** | `bytes`        | Hex-decoded to raw bytes                                      |

Any column whose logical type is not listed above is preserved as a `string` rather than failing the import.

## Importing from Snowflake using Surreal Sync

Surreal Sync can read tables from a Snowflake database and write them to SurrealDB.

> [!NOTE]
> The Snowflake source is ingestion-only. It performs a single full snapshot of the selected tables and does not support incremental synchronisation or change data capture. There is no durable cursor, so an interrupted run cannot be resumed part-way; re-run the command to start again.

Rows are read one Snowflake result partition at a time and written in batches, so a large table does not need to fit in memory.

### Prerequisites

Surreal Sync connects to Snowflake through the [SQL REST API](https://docs.snowflake.com/en/developer-guide/sql-api/index) using key-pair (JWT) authentication. Before running an import:

1. Generate an unencrypted PKCS#8 RSA key pair. Encrypted private keys are not supported yet.
2. Register the public key on the Snowflake user that Surreal Sync will authenticate as:

   ```sql
   ALTER USER my_user SET RSA_PUBLIC_KEY='MIIBIjANBgkq...';
   ```

3. Make sure that user has a role able to read the target database and schema, and a virtual warehouse to run the queries.

Keep the private key file accessible to Surreal Sync and pass its path with `--private-key-path`.

### Usage

```bash
surreal-sync from snowflake \
  --account myorg-myaccount \
  --user my_user \
  --private-key-path ./rsa_key.p8 \
  --warehouse COMPUTE_WH \
  --database MY_DB \
  --schema PUBLIC \
  --to-namespace my_namespace \
  --to-database my_database \
  --surreal-endpoint ws://localhost:8000 \
  --surreal-username root \
  --surreal-password secret
```

When `--tables` is omitted, every base table in the schema is imported (views and temporary tables are skipped). Each table becomes a table of the same name in SurrealDB, and each row becomes a record. Snowflake upper-cases unquoted identifiers, so table and column names arrive upper-cased.

Most connection options also read from an environment variable, which is useful for keeping credentials out of shell history.

### Options

| Option | Environment variable | Required | Description |
| ------ | -------------------- | -------- | ----------- |
| `--account` | `SNOWFLAKE_ACCOUNT` | Yes | Account identifier as used in the host `<account>.snowflakecomputing.com`, for example `myorg-myaccount` or `xy12345.us-east-1`. |
| `--user` | `SNOWFLAKE_USER` | Yes | User whose key pair is registered for JWT authentication. |
| `--private-key-path` | `SNOWFLAKE_PRIVATE_KEY_PATH` | Yes | Path to the unencrypted PKCS#8 private key PEM file. |
| `--private-key-passphrase` | `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE` | No | Passphrase for an encrypted key. Not supported yet; setting it returns an error. |
| `--warehouse` | `SNOWFLAKE_WAREHOUSE` | Yes | Virtual warehouse used to run the queries. |
| `--database` | `SNOWFLAKE_DATABASE` | Yes | Database to read from. |
| `--schema` | `SNOWFLAKE_SCHEMA` | No | Schema within the database. Defaults to `PUBLIC`. |
| `--role` | `SNOWFLAKE_ROLE` | No | Role to assume for the session. |
| `--tables` | - | No | Comma-separated list of tables to import. When omitted, all base tables in the schema are imported. |
| `--id-columns` | - | No | Comma-separated columns forming the SurrealDB record ID. See [Record IDs](#record-ids). |
| `--transforms-config` | - | No | Path to a TOML file describing a transform pipeline. Omit to import rows unchanged. |
| `--to-namespace` | - | Yes | Target SurrealDB namespace. |
| `--to-database` | - | Yes | Target SurrealDB database. |

The `--surreal-endpoint`, `--surreal-username`, `--surreal-password`, `--batch-size`, and `--dry-run` options are shared with the other Surreal Sync sources. Use `--dry-run` to read and convert rows without writing to SurrealDB.

### Record IDs

Snowflake primary keys are optional and often absent, so the record ID for each row depends on `--id-columns`:

- **Omitted:** a sequential per-table integer is generated. It is deterministic within a run but not stable across re-runs, so prefer explicit ID columns when you need stable IDs.
- **A single column:** the value becomes the record ID, as an integer when it parses as one and otherwise as a string.
- **Several columns:** the values are joined with `:` into a string ID.

When ID columns are given, they are used only for the record ID and are not repeated as fields on the record. Column names are matched case-insensitively.

---

Source: https://surrealdb.com/docs/integrate

# Integrate

Connecting SurrealDB to your code and tools: integrations with frameworks and services, AI agents, embedding the engine, and migrating from another database.

This section is about the seams between SurrealDB and everything around it. Where [Learn](/docs/learn.md) covers the database itself, these pages cover getting it into a codebase and keeping it there.

## Connect

- [Integrations](/docs/integrate/integrations.md) - Connect frameworks, auth providers, embedding providers and data tooling.

- [AI agents](/docs/integrate/ai-agents.md) - Give an agent a database it can query, and rules that keep it accurate.

- [Embedding SurrealDB](/docs/integrate/embedding.md) - Run the engine inside your application, natively or through WebAssembly.

## Migrate

- [Migrating](/docs/integrate/migrating.md) - Import data and schemas from PostgreSQL, MongoDB and other databases, or upgrade from an older SurrealDB.

## Related sections

Language-specific setup lives with each SDK in [the reference](/docs/reference.md). Running the server, whether managed or on your own hardware, is covered in [Operate](/docs/operate.md).
