jpskill.com
💬 コミュニケーション コミュニティ

surrealdb-python

Pythonを使ってSurrealDB 2.3.xを操作し、データの作成・読み込み・更新・削除、グラフ構造の関連付け、ベクトル検索、リアルタイムクエリなど、様々なデータベース操作を効率的に行うSkill。

📜 元の英語説明(参考)

Master SurrealDB 2.3.x with Python for multi-model database operations including CRUD, graph relationships, vector search, and real-time queries. Use when working with SurrealDB databases, implementing graph traversal, semantic search with embeddings, or building RAG applications.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Pythonを使ってSurrealDB 2.3.xを操作し、データの作成・読み込み・更新・削除、グラフ構造の関連付け、ベクトル検索、リアルタイムクエリなど、様々なデータベース操作を効率的に行うSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o surrealdb-python.zip https://jpskill.com/download/16986.zip && unzip -o surrealdb-python.zip && rm surrealdb-python.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/16986.zip -OutFile "$d\surrealdb-python.zip"; Expand-Archive "$d\surrealdb-python.zip" -DestinationPath $d -Force; ri "$d\surrealdb-python.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して surrealdb-python.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → surrealdb-python フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
3

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

SurrealDB Python

概要

SurrealDBは、ドキュメント、グラフ、ベクトル検索の機能を単一のシステムに組み合わせたマルチモデルデータベースです。このスキルは、Python SDKを使用してSurrealDB 2.3.xを操作するための包括的なガイダンスを提供し、標準的なデータベース操作、グラフ関係、ベクトル類似性検索、およびリアルタイムデータサブスクリプションを網羅しています。

このスキルを使用する場面

このスキルは、以下の場合に適用します。

  • SurrealDB接続をセットアップし、CRUD操作を実行する場合
  • RELATEステートメントとトラバーサルクエリを使用してグラフデータベースを実装する場合
  • ベクトル埋め込みを使用してセマンティック検索またはRAG (Retrieval-Augmented Generation) アプリケーションを構築する場合
  • ライブクエリでリアルタイムアプリケーションを作成する場合
  • ドキュメント、グラフ、およびベクトルを組み合わせたマルチモデルスキーマを設計する場合

主要な機能

1. 接続と認証

適切な認証を使用して、Python SDKを使用してSurrealDBへの接続を確立します。

from surrealdb import AsyncSurreal

async with AsyncSurreal("ws://localhost:8000/rpc") as db:
    await db.signin({"user": "root", "pass": "root"})
    await db.use("namespace", "database")
    # 操作を実行

2. CRUD操作

直感的なPythonメソッドを使用して、標準的なデータベース操作を実行します。

  • create() - 特定のIDまたは自動生成されたIDで新しいレコードを挿入します
  • select() - 単一のレコードまたはテーブル全体を取得します
  • update() - レコードの内容全体を置き換えます
  • merge() - 新しいフィールドをマージしてレコードを部分的に更新します
  • patch() - 正確な変更のためにJSON Patch操作を適用します
  • upsert() - 存在しない場合は作成し、存在する場合は更新します
  • delete() - レコードまたはテーブル全体を削除します
  • query() - 複雑な操作のために生のSurrealQLを実行します

ワークフローの例:

# 作成
user = await db.create("user", {
    "name": "Alice",
    "email": "alice@example.com"
})

# 特定のフィールドを更新
await db.merge("user:alice", {"age": 30})


# パラメータ付きのクエリ
results = await db.query(
    "SELECT * FROM user WHERE age > $min_age",
    {"min_age": 25}
)

3. グラフデータベース操作

SurrealDBのネイティブグラフ機能を利用して、JOINなしで関係をモデル化およびトラバースします。

関係の作成:

# エンティティを作成
await db.create("person:alice", {"name": "Alice"})
await db.create("person:bob", {"name": "Bob"})

# メタデータ付きの関係を作成
await db.query("""
    RELATE person:alice->knows->person:bob
    SET since = "2024-01-01", strength = "close"
""")

グラフのトラバース:

# 友達の友達を見つける
result = await db.query("""
    SELECT ->knows->person->knows->person AS friends_of_friends
    FROM person:alice
""")

# 双方向トラバース
result = await db.query("""
    SELECT <->connected_to<->city AS connected_cities
    FROM city:nyc
""")

# 再帰クエリ (可変深度)
result = await db.query("""
    SELECT @.{1,5}->manages->person AS management_chain
    FROM person:ceo
""")

主要なグラフ機能:

  • ノード間のエッジを作成するためのRELATEステートメント
  • 直感的なトラバースのための矢印構文 (->, <->)
  • @.{depth}表記による再帰パターン
  • トラバース中にフィルタリングするためのグラフ句
  • 関係メタデータを格納するエッジテーブル

包括的なグラフパターン、スキーマ定義、およびベストプラクティスについては、references/graph_operations.mdを参照してください。

4. ベクトル検索と埋め込み

ベクトル埋め込みを使用して、セマンティック検索と類似性ベースの検索を実装します。

ベクトルの格納:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

# 埋め込みを生成して格納
text = "SurrealDB is a multi-model database"
embedding = model.encode(text).tolist()

await db.create("documents", {
    "content": text,
    "embedding": embedding,
    "metadata": {"source": "docs"}
})

KNNによるセマンティック検索:

# クエリ埋め込みを生成
query_text = "database features"
query_embedding = model.encode(query_text).tolist()

# 最も類似した5つのドキュメントを見つける
result = await db.query("""
    SELECT content,
           vector::similarity::cosine(embedding, $query_vector) AS similarity
    FROM documents
    WHERE embedding <|5|> $query_vector
    ORDER BY similarity DESC
""", {"query_vector": query_embedding})

主要なベクトル機能:

  • k近傍探索のためのKNN演算子 <|k|>
  • 複数の距離メトリック (コサイン、ユークリッド、マンハッタン)
  • ベクトル検索と全文検索を組み合わせたハイブリッド検索
  • 一般的な埋め込みモデル (OpenAI, HuggingFace, Sentence Transformers) との統合

完全なRAG実装、埋め込みモデルの比較、および最適化手法については、references/vector_search.mdを参照してください。

5. リアルタイムクエリ

リアルタイムアプリケーションのために、ライブデータ変更をサブスクライブします。

# ライブクエリを開始
live_id = await db.live("user")

# 変更をサブスクライブ
async for notification in db.subscribe_live(live_id):
    action = notification['action']  # 'CREATE', 'UPDATE', 'DELETE'
    data = notification['result']
    print(f"Change detected: {action} - {data}")

# 完了したらライブクエリを停止
await db.kill(live_id)

ワークフローパターン

RAGアプリケーションの構築

  1. スキーマの定義:

    await db.query("""
        DEFINE TABLE documents SCHEMAFULL;
        DEFINE FIELD content ON TABLE documents TYPE string;
        DEFINE FIELD embedding ON TABLE documents TYPE array;
        DEFINE FIELD metadata ON TABLE documents TYPE object;
    """)
  2. ドキュメントのインデックス作成:

    for doc in documents:
        embedding = model.encode(doc["content"]).tolist()
        await db.create("documents", {
            "content": doc["content"],
            "embedding": embedding,
            "metadata": doc.get("metadata", {})
        })
  3. セマンティック検索:

    
    query_embedding = model.encode("user query").tolist()
    results = await db.query("""
        SELECT content, metadata,
               vector::similarity::cosine(embedding, $qu
    (原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

SurrealDB Python

Overview

SurrealDB is a multi-model database that combines document, graph, and vector search capabilities in a single system. This skill provides comprehensive guidance for working with SurrealDB 2.3.x using the Python SDK, covering standard database operations, graph relationships, vector similarity search, and real-time data subscriptions.

When to Use This Skill

Apply this skill when:

  • Setting up SurrealDB connections and performing CRUD operations
  • Implementing graph databases with the RELATE statement and traversal queries
  • Building semantic search or RAG (Retrieval-Augmented Generation) applications with vector embeddings
  • Creating real-time applications with live queries
  • Designing multi-model schemas that combine documents, graphs, and vectors

Core Capabilities

1. Connection and Authentication

Establish connections to SurrealDB using the Python SDK with proper authentication:

from surrealdb import AsyncSurreal

async with AsyncSurreal("ws://localhost:8000/rpc") as db:
    await db.signin({"user": "root", "pass": "root"})
    await db.use("namespace", "database")
    # Perform operations

2. CRUD Operations

Perform standard database operations using intuitive Python methods:

  • create() - Insert new records with specific or auto-generated IDs
  • select() - Retrieve single records or entire tables
  • update() - Replace entire record contents
  • merge() - Partially update records by merging new fields
  • patch() - Apply JSON Patch operations for precise modifications
  • upsert() - Create if absent, update if present
  • delete() - Remove records or entire tables
  • query() - Execute raw SurrealQL for complex operations

Example workflow:

# Create
user = await db.create("user", {
    "name": "Alice",
    "email": "alice@example.com"
})

# Update specific fields
await db.merge("user:alice", {"age": 30})


# Query with parameters
results = await db.query(
    "SELECT * FROM user WHERE age > $min_age",
    {"min_age": 25}
)

3. Graph Database Operations

Leverage SurrealDB's native graph capabilities to model and traverse relationships without JOINs:

Creating Relationships:

# Create entities
await db.create("person:alice", {"name": "Alice"})
await db.create("person:bob", {"name": "Bob"})

# Create relationship with metadata
await db.query("""
    RELATE person:alice->knows->person:bob
    SET since = "2024-01-01", strength = "close"
""")

Traversing Graphs:

# Find friends of friends
result = await db.query("""
    SELECT ->knows->person->knows->person AS friends_of_friends
    FROM person:alice
""")

# Bidirectional traversal
result = await db.query("""
    SELECT <->connected_to<->city AS connected_cities
    FROM city:nyc
""")

# Recursive queries (variable depth)
result = await db.query("""
    SELECT @.{1,5}->manages->person AS management_chain
    FROM person:ceo
""")

Key Graph Features:

  • RELATE statement for creating edges between nodes
  • Arrow syntax (->, <->) for intuitive traversal
  • Recursive patterns with @.{depth} notation
  • Graph clauses for filtering during traversal
  • Edge tables that store relationship metadata

For comprehensive graph patterns, schema definitions, and best practices, see references/graph_operations.md.

4. Vector Search and Embeddings

Implement semantic search and similarity-based retrieval using vector embeddings:

Storing Vectors:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

# Generate and store embedding
text = "SurrealDB is a multi-model database"
embedding = model.encode(text).tolist()

await db.create("documents", {
    "content": text,
    "embedding": embedding,
    "metadata": {"source": "docs"}
})

Semantic Search with KNN:

# Generate query embedding
query_text = "database features"
query_embedding = model.encode(query_text).tolist()

# Find 5 most similar documents
result = await db.query("""
    SELECT content,
           vector::similarity::cosine(embedding, $query_vector) AS similarity
    FROM documents
    WHERE embedding <|5|> $query_vector
    ORDER BY similarity DESC
""", {"query_vector": query_embedding})

Key Vector Features:

  • KNN operator <|k|> for k-nearest neighbor search
  • Multiple distance metrics (cosine, euclidean, manhattan)
  • Hybrid search combining vector and full-text search
  • Integration with popular embedding models (OpenAI, HuggingFace, Sentence Transformers)

For complete RAG implementations, embedding model comparisons, and optimization techniques, reference references/vector_search.md.

5. Real-Time Queries

Subscribe to live data changes for real-time applications:

# Start live query
live_id = await db.live("user")

# Subscribe to changes
async for notification in db.subscribe_live(live_id):
    action = notification['action']  # 'CREATE', 'UPDATE', 'DELETE'
    data = notification['result']
    print(f"Change detected: {action} - {data}")

# Stop live query when done
await db.kill(live_id)

Workflow Patterns

Building a RAG Application

  1. Define Schema:

    await db.query("""
        DEFINE TABLE documents SCHEMAFULL;
        DEFINE FIELD content ON TABLE documents TYPE string;
        DEFINE FIELD embedding ON TABLE documents TYPE array;
        DEFINE FIELD metadata ON TABLE documents TYPE object;
    """)
  2. Index Documents:

    for doc in documents:
        embedding = model.encode(doc["content"]).tolist()
        await db.create("documents", {
            "content": doc["content"],
            "embedding": embedding,
            "metadata": doc.get("metadata", {})
        })
  3. Semantic Search:

    query_embedding = model.encode("user query").tolist()
    results = await db.query("""
        SELECT content, metadata,
               vector::similarity::cosine(embedding, $query_vector) AS score
        FROM documents
        WHERE embedding <|5|> $query_vector
        ORDER BY score DESC
    """, {"query_vector": query_embedding})
  4. Pass to LLM: Use retrieved context with language model for generation

Implementing a Knowledge Graph

  1. Create Entities:

    await db.create("concept:ai", {"name": "Artificial Intelligence"})
    await db.create("concept:ml", {"name": "Machine Learning"})
  2. Define Relationships:

    await db.query("""
        RELATE concept:ml->is_subset_of->concept:ai
        SET confidence = 0.95
    """)
  3. Traverse and Query:

    # Find all parent concepts recursively
    result = await db.query("""
        SELECT @.{1,}->is_subset_of->concept AS parents
        FROM concept:ml
    """)

Combining Graph and Vector Search

Leverage both graph relationships and semantic similarity:

# Find semantically similar documents connected through graph relationships
result = await db.query("""
    SELECT *,
           vector::similarity::cosine(embedding, $query_vector) AS vec_score
    FROM documents
    WHERE embedding <|10|> $query_vector
      AND ->cited_by->document<-authored_by<-person = $author_id
    ORDER BY vec_score DESC
""", {
    "query_vector": query_embedding,
    "author_id": "person:researcher1"
})

Best Practices

Connection Management

  • Use context managers (async with) for automatic cleanup
  • Handle SurrealException for proper error handling
  • Set appropriate timeouts for long-running queries

Schema Design

  • Define schemas with SCHEMAFULL for data integrity
  • Create indexes on frequently queried fields
  • Use assertions for validation and referential integrity

Graph Operations

  • Define unique indexes on edge tables to prevent duplicate relationships
  • Add timeouts to recursive queries (TIMEOUT 5s)
  • Use FETCH to optimize queries that need related data
  • Store metadata in edge tables when relationships have properties

Vector Search

  • Choose embedding models appropriate for your domain and latency requirements
  • Normalize embeddings when using cosine similarity
  • Create indexes on vector fields for production workloads
  • Chunk long documents (500-1000 tokens) with overlap for better retrieval
  • Combine vector search with metadata filtering for precision

Query Optimization

  • Parameterize queries to prevent injection attacks
  • Batch operations when inserting multiple records
  • Use appropriate k values for KNN (3-5 for precision, 10-20 for recall)
  • Leverage hybrid search (vector + full-text) for best results

Common Use Cases

Semantic Search & RAG: Store document embeddings and perform similarity searches to retrieve relevant context for language models.

Knowledge Graphs: Model complex relationships between entities with typed edges and metadata, enabling sophisticated graph traversal queries.

Social Networks: Represent users and their connections, traverse friend relationships, and find mutual connections or recommendations.

Recommendation Systems: Combine collaborative filtering (graph relationships) with content-based filtering (vector similarity) for hybrid recommendations.

Real-Time Applications: Subscribe to data changes for live dashboards, chat applications, or notification systems.

Reference Documentation

This skill includes comprehensive reference documentation:

  • references/graph_operations.md - In-depth guide to graph database operations, RELATE syntax, traversal patterns, and schema design
  • references/vector_search.md - Vector search implementation details, embedding model comparisons, RAG patterns, and LangChain integration

Load these references when implementing specific features or troubleshooting issues.

Additional Resources

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。