iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
AI & Data

Notion遇上LLM:30天打造我的AI知識管理系統系列 第 11

【Day 11】把 Notion JSON 寫入 SQLite:建立可查詢的筆記資料庫

  • 分享至 

  • xImage
  •  

Day 9,我們設計了 SQLite Schema 並畫出了 ERD;Day 10時,調整了 Pipeline 的 JSON 格式,補齊 Schema 需要的欄位。
今天,我們要把 JSON 匯入 SQLite,讓 Notion 筆記不只是「一份檔案」,而是能用 SQL 查詢、分析的 結構化知識庫!

1. 開發環境建置

1.1 使用 VS Code + SQLite

我們會用 VS Code 搭配 SQLite Extension 來檢視資料。如果你還沒安裝 VS Code環境,可以先參考 【Day 4】環境建置與 Notion API 測試 的說明。

  • 安裝 SQLite 官方 CLI 或使用 Python 內建的 sqlite3。
  • 在 VS Code Marketplace 安裝 SQLite、SQLite Viewer、SQLite3 Editor 擴充套件,這樣就能直接點擊 .db 檔,檢視資料表與資料:
    https://ithelp.ithome.com.tw/upload/images/20250925/20178104QCQdG0g2qn.png

1.2 初始化資料庫 Schema

先執行一支 Python 程式建立 Table(對應 Day 9 的 Schema):
src/init_sqlite.py

import sqlite3

def init_db(db_path="data/notion.db"):
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()

    cur.executescript("""
    CREATE TABLE IF NOT EXISTS notion_databases (
        database_id      TEXT PRIMARY KEY,
        database_name    TEXT NOT NULL,
        category         TEXT,
        created_time     TEXT,
        last_edited_time TEXT
    );

    CREATE TABLE IF NOT EXISTS notion_pages (
        page_id          TEXT PRIMARY KEY,
        page_name        TEXT,
        database_id      TEXT NOT NULL,
        created_time     TEXT,
        last_edited_time TEXT,
        FOREIGN KEY(database_id) REFERENCES notion_databases(database_id)
    );

    CREATE TABLE IF NOT EXISTS notion_blocks (
        block_id         TEXT PRIMARY KEY,
        page_id          TEXT NOT NULL,
        order_index      INTEGER,
        block_type       TEXT,
        block_text       TEXT,
        code_language    TEXT,
        created_time     TEXT,
        last_edited_time TEXT,
        FOREIGN KEY(page_id) REFERENCES notion_pages(page_id)
    );
    """)
    conn.commit()
    conn.close()
    print("SQLite schema initialized.")

if __name__ == "__main__":
    init_db()

2. 實作 Notion JSON 寫入 SQLite

接下來,把 Day 10 Pipeline 生成的 JSON 寫進 SQLite

load_to_sqlite.py

import os, json, sqlite3

def load_json_to_sqlite(json_path, db_path="data/notion.db"):
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()

    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    db = data["database"]
    pages = data["pages"]
    blocks = data["blocks"]

    # 1. 匯入 Database
    cur.execute("""
        INSERT OR REPLACE INTO notion_databases
        (database_id, database_name, category, created_time, last_edited_time)
        VALUES (?, ?, ?, ?, ?)
    """, (
        db["database_id"], db["database_name"], db.get("category"),
        db.get("created_time"), db.get("last_edited_time")
    ))

    # 2. 匯入 Pages
    for p in pages:
        cur.execute("""
            INSERT OR REPLACE INTO notion_pages
            (page_id, page_name, database_id, created_time, last_edited_time)
            VALUES (?, ?, ?, ?, ?)
        """, (
            p["page_id"], p.get("page_name"), p["database_id"],
            p.get("created_time"), p.get("last_edited_time")
        ))

    # 3. 匯入 Blocks
    for b in blocks:
        cur.execute("""
            INSERT OR REPLACE INTO notion_blocks
            (block_id, page_id, order_index, block_type, block_text, code_language, created_time, last_edited_time)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            b["block_id"], b["page_id"], b.get("order_index"), b.get("block_type"),
            b.get("block_text"), b.get("code_language"),
            b.get("created_time"), b.get("last_edited_time")
        ))

    conn.commit()
    conn.close()
    print(f"Loaded {json_path} → {db_path}")

if __name__ == "__main__":
    os.makedirs("data", exist_ok=True)
    for file in os.listdir("data/clean"):
        if file.endswith(".json"):
            load_json_to_sqlite(os.path.join("data/clean", file))

3. 確認資料寫入 SQLite

執行完成後,Terminal 顯示:

Loaded data/clean/Learning_PythonBasicNotes.json → data/notion.db
Loaded data/clean/Life_BusanTravelPlan.json → data/notion.db

代表 JSON 已順利寫進 SQLite,可以在 VS Code 的 SQLite 插件裡看到三張表都已經有資料:

  • notion_databases:保存 Database 基本資訊(含分類與時間)。
  • notion_pages:保存 Page(筆記主題)。
  • notion_blocks:保存 Block(細節內容,例如段落、程式碼)。
    https://ithelp.ithome.com.tw/upload/images/20250925/20178104oe80c3qVO5.png

4. 使用 SQL 查詢 notion.db

接下來我們要實際使用 SQL 來查詢 notion.db

4.1 查詢步驟

  • 搜尋 >SQLite: New Query
    https://ithelp.ithome.com.tw/upload/images/20250925/20178104Y6ExydTUMD.png

  • 撰寫 script 後,按右鍵選擇 Run Query 或按 Shift + command + Q (Mac),就可以執行 Query 囉!
    https://ithelp.ithome.com.tw/upload/images/20250925/2017810423VmMl3U3z.png

4.2 查詢範例

  1. 找出 block 中的所有 Python 程式碼

    SELECT p.page_name, b.block_text
    FROM notion_blocks b
    JOIN notion_pages p ON b.page_id = p.page_id
    WHERE b.block_type = 'code' AND b.code_language = 'python'
    

    https://ithelp.ithome.com.tw/upload/images/20250925/20178104Qi5KWPt64a.png

  2. 統計各分類 Database 的 Page 數

    SELECT d.category, COUNT(p.page_id) AS page_count
    FROM notion_databases d
    JOIN notion_pages p ON d.database_id = p.database_id
    GROUP BY d.category
    

    https://ithelp.ithome.com.tw/upload/images/20250925/20178104ZwuN09kM5Q.png

  3. 最近更新的 5 筆 Page

    SELECT page_name, last_edited_time
    FROM notion_pages
    ORDER BY last_edited_time DESC
    LIMIT 5
    

    https://ithelp.ithome.com.tw/upload/images/20250925/20178104I6fnruTd5e.png

5. 小結與下篇預告

到目前為止,我們完成了 Notion API -> Json -> SQLite,現在,我們的 Notion 筆記已經能用 SQL 直接檢索,不再只是靜態的 JSON

在 Day 12,我們將開始進入下一個里程碑 -- 向量化 (Embedding):

  • 介紹嵌入模型 (embedding model) 的概念。
  • 向量資料庫的選擇(FAISS / Chroma / Pinecone)。
  • 思考如何把 SQLite 資料轉換成向量,進一步支持 RAG 知識檢索。

上一篇
【Day 10】資料清理與格式調整:讓 Notion JSON 與 SQLite Schema 對齊
系列文
Notion遇上LLM:30天打造我的AI知識管理系統11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言