🧬 Embedding Documents
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Hiểu Embeddings là gì và cách chúng hoạt động
✅ Biết cách config Embeddings node trong n8n
✅ Xây dựng full indexing pipeline từ load đến index
✅ Implement batch indexing với rate limiting
✅ Thiết lập re-indexing strategy cho document updates
Embeddings biến text thành vectors — cho phép machines hiểu semantic similarity. Bài này cover embedding workflow trong n8n.
🔍 Embeddings là gì?
"Cat" và "Dog" có vectors gần nhau (cả hai là animals). "Car" có vector khác xa.
Checkpoint
Embeddings biến text thành gì? Tại sao 'Cat' và 'Dog' có vectors gần nhau?
🔄 Embedding Workflow trong n8n
Embeddings Node Configuration
1// n8n Embeddings Node2// Provider: OpenAI3// Model: text-embedding-3-small4// Dimensions: 1536 (default)56// Or for higher quality:7// Model: text-embedding-3-large8// Dimensions: 3072910// Cost comparison (per 1M tokens):11// text-embedding-3-small: $0.0212// text-embedding-3-large: $0.13Checkpoint
Mô tả các bước trong embedding workflow. So sánh cost và quality của 2 OpenAI embedding models.
🏗️ Full Indexing Pipeline
Step 1: Load Documents
1// HTTP Request or Google Drive node2// Supports: PDF, TXT, DOCX, CSV, Markdown, HTML34// For PDF: Use n8n PDF loader5// For web pages: HTTP Request + Extract HTML6// For Google Docs: Google Drive nodeStep 2: Clean Text
1// Code node: Clean and normalize text2function cleanText(text) {3 return text4 .replace(/\s+/g, ' ') // Multiple spaces to single5 .replace(/\n{3,}/g, '\n\n') // Multiple newlines to double6 .replace(/[^\S\n]+/g, ' ') // Normalize whitespace7 .replace(/\u0000/g, '') // Remove null chars8 .trim();9}1011return { json: { text: cleanText($json.text), source: $json.source } };Step 3: Split and Embed
1// Text Splitter node → Embeddings node → Vector Store node2// These are connected as sub-nodes in the Vector Store Insert operation34// Vector Store Insert node configuration:5// Mode: Insert6// Embedding: OpenAI Embeddings (sub-node)7// Text Splitter: Recursive Character (sub-node)8// - Chunk Size: 8009// - Chunk Overlap: 150Checkpoint
Liệt kê các bước trong full indexing pipeline từ Google Drive đến Report Stats.
📦 Batch Indexing
1// Code node: Batch processing for large document sets2const documents = $input.all();3const batchSize = 20;4const batches = [];56for (let i = 0; i < documents.length; i += batchSize) {7 batches.push(documents.slice(i, i + batchSize));8}910// Process each batch with a wait between them11// to avoid rate limits12return batches.map((batch, i) => ({13 json: {14 batchIndex: i,15 documents: batch.map(d => d.json),16 totalBatches: batches.length17 }18}));Checkpoint
Tại sao cần batch processing khi indexing? Batch size nên là bao nhiêu?
✅ Verifying Indexed Data
1// After indexing, verify with test queries2const testQueries = [3 "What is our return policy?",4 "Company mission statement",5 "How to contact support"6];78// Vector Store Search node9// Query each test query10// Verify relevant chunks are returned11// Check similarity scores > 0.7Checkpoint
Làm thế nào để verify data đã indexed đúng? Similarity score threshold nên là bao nhiêu?
🔄 Re-indexing Strategy
1// Code node: Track document versions2const docTracker = {3 documentId: $json.fileId,4 lastModified: $json.modifiedTime,5 chunkCount: $json.chunks.length,6 version: ($json.currentVersion || 0) + 1,7 indexedAt: new Date().toISOString()8};910// Save to Google Sheets for tracking11return { json: docTracker };- Consistent model: Dùng cùng embedding model cho indexing và querying
- Batch processing: Index documents theo batches, không 1-by-1
- Metadata: Luôn attach source info, date, và type
- Version tracking: Track versions khi re-index
- Test after indexing: Verify với known queries
Checkpoint
Mô tả các bước trong re-indexing strategy khi document thay đổi.
📝 Bài tập thực hành
- Build pipeline: Load 10 documents, clean, split, embed, index
- Test retrieval accuracy với 5 test queries
- Implement batch indexing với rate limiting
- Create re-indexing workflow triggered by file changes
Checkpoint
Liệt kê 4 exercises cần hoàn thành. Exercise nào quan trọng nhất?
🚀 Bài tiếp theo
Query Pipeline → — Xây dựng query pipeline hoàn chỉnh cho RAG.
