DEV Community

Alex Spinov
Alex Spinov

Posted on

SurrealDB Has a Free API — Here's How to Build Multi-Model Apps with One Database

Why SurrealDB?

SurrealDB is a multi-model database that combines document, graph, relational, and time-series capabilities in one. Write SQL-like queries that traverse graph relationships, handle documents, and join tables — all in one query language (SurrealQL).

Free and open source. SurrealDB Cloud has a free tier.

Getting Started

Install

# macOS
brew install surrealdb/tap/surreal

# Docker
docker run -d -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass root

# Or download from surrealdb.com
Enter fullscreen mode Exit fullscreen mode

Connect

surreal sql --endpoint http://localhost:8000 --username root --password root --namespace test --database test
Enter fullscreen mode Exit fullscreen mode

SurrealQL Examples

Document Style

-- Create records (schemaless by default)
CREATE user:alice SET name = 'Alice', email = 'alice@example.com', plan = 'pro', tags = ['developer', 'writer'];
CREATE user:bob SET name = 'Bob', email = 'bob@example.com', plan = 'free', tags = ['designer'];

-- Query with filters
SELECT * FROM user WHERE plan = 'pro' ORDER BY name;

-- Nested objects — no separate table needed
CREATE product:1 SET
  name = 'Widget',
  price = 29.99,
  specs = { weight: '150g', color: 'blue', dimensions: { w: 10, h: 5, d: 3 } };

SELECT name, specs.dimensions.w FROM product;
Enter fullscreen mode Exit fullscreen mode

Graph Relationships

-- Create graph edges (RELATE)
RELATE user:alice->purchased->product:1 SET quantity = 2, date = time::now();
RELATE user:alice->follows->user:bob SET since = '2024-01-15';
RELATE user:bob->follows->user:alice SET since = '2024-02-20';

-- Traverse the graph
SELECT ->purchased->product.name FROM user:alice;
-- Returns: ['Widget']

SELECT ->follows->user.name FROM user:alice;
-- Returns: ['Bob']

-- Find mutual followers
SELECT id, name FROM user WHERE ->follows->user CONTAINS user:alice AND <-follows<-user CONTAINS user:alice;
Enter fullscreen mode Exit fullscreen mode

Aggregation

SELECT
  plan,
  count() AS user_count,
  array::distinct(array::flatten(tags)) AS all_tags
FROM user
GROUP BY plan;
Enter fullscreen mode Exit fullscreen mode

JavaScript SDK

import Surreal from "surrealdb.js";

const db = new Surreal();
await db.connect("http://localhost:8000/rpc");
await db.signin({ username: "root", password: "root" });
await db.use({ namespace: "test", database: "test" });

// Create
await db.create("article", {
  title: "SurrealDB is Amazing",
  content: "Multi-model database that does everything...",
  author: "user:alice",
  published: true
});

// Query
const results = await db.query(
  "SELECT *, ->purchased->product.* AS purchases FROM user WHERE plan = $plan",
  { plan: "pro" }
);
console.log(results);

// Live queries (real-time!)
await db.live("article", (action, result) => {
  console.log(`${action}: ${result.title}`);
});
Enter fullscreen mode Exit fullscreen mode

Python SDK

from surrealdb import Surreal
import asyncio

async def main():
    async with Surreal("ws://localhost:8000/rpc") as db:
        await db.signin({"user": "root", "pass": "root"})
        await db.use("test", "test")

        # Create
        await db.create("user", {
            "name": "Charlie",
            "email": "charlie@example.com",
            "plan": "enterprise"
        })

        # Query
        results = await db.query("SELECT * FROM user ORDER BY name")
        for user in results[0]["result"]:
            print(f"{user['name']} ({user['plan']})")

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

SurrealDB vs Others

Feature SurrealDB MongoDB Neo4j PostgreSQL
Documents Yes Yes No JSONB
Graph Yes No Yes No
SQL-like Yes No Cypher Yes
Real-time Built-in Change Streams No LISTEN
Schemaless Yes Yes Yes No
Multi-model Yes No No No

Need to scrape data for your SurrealDB app? I build production-ready scrapers. Check out my Apify actors or email spinov001@gmail.com for custom data pipelines.

Tried SurrealDB? What do you think of the multi-model approach? Comment below!

Top comments (0)