🗄️ Databases

SurrealDB

Multi-model Database

A multi-model cloud-native database written in Rust that unifies Document, Graph, and Relational models on a single platform. Supports an intuitive query language called SurrealQL and real-time subscriptions.

📖 Detailed Explanation

SurrealDB is a next-generation database released in 2022 that lets you use Document (like MongoDB), Graph (like Neo4j), and Relational (like PostgreSQL) models all in one DB. Written in Rust, it excels in performance and safety, and also supports an architecture in which the frontend accesses the DB directly without a backend.

Key feature: all models with a single query language

Handle relational JOINs, graph traversal, and document CRUD all with SurrealQL alone. Unify them in one without needing to combine multiple DBs.

Supported data models

📄
Document
Schemaless JSON document storage like MongoDB
🕸️
Graph
Node/edge relationship traversal like Neo4j
📊
Relational
Table JOIN queries like SQL

💻 Code Example

1. Getting started with SurrealDB and basic CRUD

SurrealQL
-- SurrealDB 서버 시작 (메모리 모드) -- surreal start memory --user root --pass root -- 네임스페이스와 데이터베이스 선택 USE NS myapp DB production; -- Document 스타일 레코드 생성 (스키마 없이) CREATE user:john SET name = 'John Doe', email = 'john@example.com', age = 30, tags = ['developer', 'rust'], address = { city: 'Seoul', country: 'Korea' }; -- 자동 ID 생성 CREATE user CONTENT { name: 'Jane Smith', email: 'jane@example.com', age: 28 }; -- 조회 (SQL과 유사) SELECT * FROM user WHERE age >= 25; SELECT name, email FROM user WHERE 'developer' IN tags; -- 업데이트 UPDATE user:john SET age = 31, updated_at = time::now(); -- 부분 업데이트 (MERGE) UPDATE user:john MERGE { address: { zip: '06000' } }; -- 삭제 DELETE user:john;

2. Graph relationships (Record Links)

SurrealQL
-- 사용자와 게시글 생성 CREATE user:alice SET name = 'Alice'; CREATE user:bob SET name = 'Bob'; CREATE user:charlie SET name = 'Charlie'; CREATE post:1 SET title = 'Getting Started with SurrealDB', author = user:alice, created_at = time::now(); -- 그래프 관계 생성 (팔로우) RELATE user:alice->follows->user:bob SET since = time::now(); RELATE user:alice->follows->user:charlie; RELATE user:bob->follows->user:charlie; -- 그래프 탐색: Alice가 팔로우하는 사람들 SELECT ->follows->user.name FROM user:alice; -- 결과: ['Bob', 'Charlie'] -- 역방향 탐색: Charlie를 팔로우하는 사람들 SELECT <-follows<-user.name FROM user:charlie; -- 결과: ['Alice', 'Bob'] -- 2단계 관계: Alice의 팔로워가 팔로우하는 사람 (친구의 친구) SELECT ->follows->user->follows->user.name FROM user:alice; -- 복잡한 그래프 쿼리: 팔로워 수와 함께 사용자 조회 SELECT name, count(<-follows) AS follower_count, count(->follows) AS following_count FROM user;

3. JavaScript/TypeScript client

TypeScript
import Surreal from 'surrealdb.js'; const db = new Surreal(); async function initDB() { // 연결 await db.connect('http://localhost:8000/rpc'); await db.signin({ user: 'root', pass: 'root' }); await db.use({ ns: 'myapp', db: 'production' }); } // CRUD 작업 async function createUser(userData: UserInput) { const [user] = await db.create('user', { name: userData.name, email: userData.email, created_at: new Date(), }); return user; } async function getUser(id: string) { return await db.select(`user:${id}`); } async function searchUsers(query: string) { const users = await db.query(` SELECT * FROM user WHERE name ~ $query OR email ~ $query ORDER BY created_at DESC LIMIT 20 `, { query }); return users[0].result; } // 그래프 쿼리 async function getFollowers(userId: string) { const result = await db.query(` SELECT <-follows<-user.* AS followers FROM user:$userId `, { userId }); return result[0].result[0]?.followers ?? []; } // 실시간 구독 async function subscribeToMessages(roomId: string, onMessage: (msg: Message) => void) { await db.live('message', (data) => { if (data.action === 'CREATE' && data.result.room === `room:${roomId}`) { onMessage(data.result); } }); }

4. Schema definition and permissions

SurrealQL
-- 테이블 스키마 정의 DEFINE TABLE user SCHEMAFULL; DEFINE FIELD name ON user TYPE string; DEFINE FIELD email ON user TYPE string ASSERT string::is::email($value); DEFINE FIELD age ON user TYPE int ASSERT $value >= 0 AND $value <= 150; DEFINE FIELD created_at ON user TYPE datetime DEFAULT time::now(); -- 유니크 인덱스 DEFINE INDEX email_idx ON user FIELDS email UNIQUE; -- 전체 텍스트 검색 인덱스 DEFINE INDEX name_search ON user FIELDS name SEARCH ANALYZER ascii BM25; -- 권한 설정 (Row Level Security처럼) DEFINE TABLE post SCHEMAFULL PERMISSIONS FOR select FULL FOR create WHERE $auth.id != NONE FOR update, delete WHERE author = $auth.id; -- 스코프 (인증 컨텍스트) DEFINE SCOPE user_scope SESSION 24h SIGNUP ( CREATE user SET email = $email, password = crypto::argon2::generate($password), name = $name ) SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(password, $password) );

5. Real-time subscriptions (Live Queries)

TypeScript
// 실시간 변경 감지 async function setupRealtimeChat(roomId: string) { const db = new Surreal(); await db.connect('ws://localhost:8000/rpc'); await db.use({ ns: 'myapp', db: 'production' }); // LIVE 쿼리로 메시지 구독 const queryUuid = await db.live( 'message', (action, result) => { switch (action) { case 'CREATE': console.log('New message:', result); addMessageToUI(result); break; case 'UPDATE': console.log('Message updated:', result); updateMessageInUI(result); break; case 'DELETE': console.log('Message deleted:', result); removeMessageFromUI(result); break; } } ); // 구독 해제 return () => db.kill(queryUuid); } // 메시지 전송 (다른 클라이언트에 실시간 전파) async function sendMessage(roomId: string, content: string, userId: string) { await db.create('message', { room: `room:${roomId}`, author: `user:${userId}`, content, timestamp: new Date(), }); }

💬 Real-world conversation examples

Full-stack developer
"With SurrealDB you don't need MongoDB and Neo4j separately. I solved social features and document storage with a single DB."
Backend developer
"SurrealQL is similar to SQL, so it was easy to adapt to. Graph queries are also intuitive with the -> arrow."
Senior developer
"It's still at an early stage, so I'm hesitant to use it in production. I think more clustering and large-scale processing cases need to accumulate."
Startup CTO
"It's perfect for an MVP. You can even access the DB directly from the frontend without a backend server, so development is fast."

⚠️ Cautions

Lack of production cases

It is a relatively new DB released in 2022. Large-scale production cases and stability validation are still lacking, so careful consideration is needed for critical services.

Limited ecosystem

The ecosystem of ORMs, migration tools, monitoring solutions, and so on is limited compared to PostgreSQL or MongoDB.

Security of direct client access

When accessing the DB directly from the frontend, you must configure permissions (PERMISSIONS) thoroughly. Incorrect settings can lead to data leaks.

🔗 Related Terms

📚 Learn More