Skip to content

1.8 Vector Databases ​

Vector Database là loại database chuyên biệt cho việc lưu trữ và tìm kiếm vectors (embeddings) - thường được sử dụng trong AI/ML applications như semantic search, recommendation systems, và RAG (Retrieval-Augmented Generation).

Lọc metadata làm vector search trả thiếu kết quả ​

Tình huống: RAG xin 10 chunk thuộc category = 'tech', nhưng pgvector chỉ trả 3 dòng dù bảng có hàng nghìn chunk tech.

Quy tắc: Đo số dòng trả về và recall khi CÓ filter, không chỉ khi không filter. Dùng hnsw.iterative_scan (pgvector ≥ 0.8) hoặc partial index cho nhóm lọc cố định. Đừng giả định "lọc trước rồi tìm" đang xảy ra.

Ví dụ giải sẵn (triệu chứng → sửa → đo lại, chạy trên PostgreSQL 18 + pgvector 0.8):

sql
-- PostgreSQL 18 + pgvector 0.8: chạy trên database sạch
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE kb_chunks (
    id        serial PRIMARY KEY,
    category  text,
    content   text,
    embedding vector(8)
);

-- 50 000 chunk ngẫu nhiên, 5 % thuộc category 'tech'
INSERT INTO kb_chunks (category, content, embedding)
SELECT CASE WHEN g % 20 = 0 THEN 'tech' ELSE 'other' END,
       'chunk ' || g,
       (SELECT array_agg(random()::real) FROM generate_series(1, 8) WHERE g > 0)::vector
FROM generate_series(1, 50000) g;

CREATE INDEX kb_chunks_hnsw ON kb_chunks
    USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
ANALYZE kb_chunks;

-- Triệu chứng: xin 10 dòng thuộc 'tech' nhưng nhận ít hơn
SELECT count(*) AS rows_returned FROM (
    SELECT id FROM kb_chunks WHERE category = 'tech'
    ORDER BY embedding <=> '[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]' LIMIT 10) s;

-- Sửa 1: cho index duyệt tiếp tới khi đủ dòng sau lọc
SET hnsw.iterative_scan = relaxed_order;
SELECT count(*) AS rows_iterative FROM (
    SELECT id FROM kb_chunks WHERE category = 'tech'
    ORDER BY embedding <=> '[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]' LIMIT 10) s;
RESET hnsw.iterative_scan;

-- Sửa 2: partial index cho nhóm lọc cố định
CREATE INDEX kb_chunks_tech_hnsw ON kb_chunks
    USING hnsw (embedding vector_cosine_ops) WHERE category = 'tech';
SELECT count(*) AS rows_partial FROM (
    SELECT id FROM kb_chunks WHERE category = 'tech'
    ORDER BY embedding <=> '[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]' LIMIT 10) s;

Kết quả đã đo (50 000 dòng, 5 % là tech): lọc thường trả 1-3 dòng (dữ liệu ngẫu nhiên không đặt seed: chạy lại được 3 và 1), iterative_scan trả 10, partial index trả 10.

Vì sao: HNSW lấy hnsw.ef_search ứng viên gần nhất (mặc định 40) rồi Postgres mới áp WHERE category = 'tech'; filter giữ 5 % thì còn khoảng 2-3 dòng. Hình cơ chế HNSW nằm ở mục "Indexing Algorithms" bên dưới.

Bẫy production:

  • iterative_scan duyệt thêm đồ thị tới hnsw.max_scan_tuples (mặc định 20 000, đo bằng SHOW) nên độ trễ tăng khi filter hiếm; theo dõi bằng EXPLAIN (ANALYZE) và số dòng trả về so với LIMIT.
  • Partial index nhân số index theo số giá trị lọc; mỗi index chiếm RAM và thời gian ghi.
  • Lui: RESET hnsw.iterative_scan; hoặc DROP INDEX CONCURRENTLY kb_chunks_tech_hnsw;.

Tự kiểm: Bảng có 1 triệu chunk, filter tenant_id = 42 chỉ giữ 0,1 % dòng, query trả 4 dòng thay vì 10. Chọn index nào?

Đáp án

Partial index theo tenant_id (hoặc partition theo tenant) nếu số tenant ít; còn không thì bật hnsw.iterative_scan và đo độ trễ với filter hiếm. Tăng ef_search không đủ vì nó vẫn lấy 40 ứng viên của toàn bảng.

Phải nhớ:

  • Filter sau index HNSW làm thiếu dòng; đo số dòng trả về, không chỉ độ trễ.
  • Recall và độ trễ phụ thuộc dữ liệu và tham số: đo bằng recall@K trên tập đánh giá của bạn.
  • pgvector đo được: vector index tối đa 2000 chiều, halfvec 4000.

Chi tiết Vector Database ​

Phần dưới là kiến thức nền, đọc sau khi đã làm ví dụ ở trên.

Nền tảng về Vector Database ​

Vector Database là gì?

text
Traditional Database:
- Stores structured data (rows, columns)
- Exact match queries (WHERE id = 123)
- Index types: B-tree, Hash, etc.

Vector Database:
- Stores high-dimensional vectors (embeddings)
- Similarity search (find most similar vectors)
- Index types: HNSW, IVF, LSH, Annoy, etc.

Vector = Numerical representation of data
Example: Text "Hello world" → [0.12, -0.45, 0.78, ..., 0.23] (1536 dimensions)

Similar meaning → Similar vectors (close in vector space)
- "cat" and "kitten" → similar embeddings
- "cat" and "car" → very different embeddings

Embedding Dimensions:

text
Model                              Dimensions    Use Case
─────────────────────────────────────────────────────────────────────
OpenAI text-embedding-3-large      3072          Best quality
OpenAI text-embedding-3-small      1536          Good balance
Sentence Transformers              768           Open-source
BERT                               768           General NLP
CLIP (images)                      512           Multi-modal
ResNet (images)                    2048          Image similarity

Giới hạn chiều của index pgvector (đo bằng CREATE INDEX: lỗi "column cannot have more than 2000 dimensions for hnsw index"): vector 2000, halfvec 4000, bit 64000, sparsevec 1000 phần tử khác 0 (README). Model 3072 chiều (text-embedding-3-large) cần cột halfvec hoặc cắt chiều:

sql
-- PostgreSQL 18 + pgvector 0.8
CREATE TABLE emb3072 (id serial PRIMARY KEY, embedding halfvec(3072));
CREATE INDEX ON emb3072 USING hnsw (embedding halfvec_cosine_ops);

Use Cases:

text
Use Case                    Vector Source               Why Vector DB?
───────────────────────────────────────────────────────────────────────
Semantic Search             Text → OpenAI/Cohere        Find meaning, not keywords
Image/Video Similarity      Image → CLIP/ResNet         Visual similarity search
Recommendation Systems      User/Item → Embedding       Find similar users/items
RAG (LLM + Knowledge)       Document chunks → Vector    Retrieve relevant context
Anomaly Detection           Metrics → Embedding         Find unusual patterns
Deduplication               Content → Vector            Near-duplicate detection

Độ đo tương đồng (Similarity Metrics) ​

Các hàm khoảng cách thường dùng:

text
Metric              Formula                     Best For
───────────────────────────────────────────────────────────────────────
Cosine Similarity   cos(θ) = A·B / (|A||B|)     Normalized embeddings (most text)
Euclidean (L2)      √Σ(Ai - Bi)²                Image embeddings, unnormalized
Dot Product         Σ(Ai × Bi)                  When magnitude matters
Hamming Distance    XOR and count bits          Binary vectors, LSH

Cosine: Measures angle, ignores magnitude
- Same direction = 1, Perpendicular = 0, Opposite = -1
- Most embedding models normalize, so cosine is standard

Euclidean: Measures straight-line distance
- Cares about both direction AND magnitude

Tip: "We'd use cosine similarity" is usually the right answer
     in system design interviews

Toán tử pgvector (đo với [1,2,3] và [4,5,6]): <-> khoảng cách L2 (5,196), <=> khoảng cách cosine (0,0254; bằng 1 − độ tương đồng cosine: giống nhau 0, vuông góc 1, ngược 2), <#> âm của tích vô hướng (−32), <+> khoảng cách L1 (9). Sắp xếp tăng dần; index phải khớp toán tử: vector_cosine_ops cho <=>, vector_l2_ops cho <->.

Bài toán láng giềng gần nhất (The Nearest Neighbor Problem) ​

K láng giềng gần nhất (KNN):

text
Problem: Given a query vector, find K most similar vectors

Naive approach: Compare against ALL vectors
- O(n) complexity
- 1M vectors × 1536 dims ≈ 1.5 billion multiply-adds (~3 GFLOP) per query
- TOO SLOW for production

Approximate Nearest Neighbor (ANN):
- Trade accuracy for speed
- Find vectors that are *probably* the nearest neighbors
- Recall và tốc độ phụ thuộc dữ liệu và ef_search: đo bằng recall@K trên tập đánh giá của bạn
- Ví dụ đo (pgvector 0.8.7, 100k vector 128 chiều, HNSW m=16, ef_construction=64, ef_search=40; đổi theo máy):
  dữ liệu có cụm: recall@10 0,94, 2,7 ms so với 84 ms quét đủ;
  dữ liệu ngẫu nhiên không cấu trúc: recall@10 0,34 (0,77 khi ef_search=400)

Key metric: Recall
- Of the true top-K nearest neighbors, what fraction did we find?
- Recall 0.95 = found 95% of true nearest neighbors

KNN vét cạn (mã giả):

python
# minh hoạ, không chạy độc lập: compute_similarity và thuộc tính vector.id do bạn định nghĩa
from heapq import heappush, heapreplace

def exact_knn(query_vector, all_vectors, k):
    heap = []  # min-heap by similarity

    for vector in all_vectors:
        similarity = compute_similarity(query_vector, vector)
        if len(heap) < k:
            heappush(heap, (similarity, vector.id))
        elif similarity > heap[0][0]:
            heapreplace(heap, (similarity, vector.id))

    return sorted(heap, reverse=True)

Thuật toán index (HNSW, IVF, LSH, Annoy) ​

HNSW (đồ thị nhiều tầng, điều hướng theo thế giới nhỏ):

Ẩn dụ: đường cao tốc ở tầng trên, đường làng ở tầng dưới: tới gần đích rất nhanh, nhưng không chắc tới đúng điểm gần nhất (ẩn dụ không còn đúng ở tầng 0, nơi đồ thị là mạng lân cận chứ không phải một con đường).

text
Được nhiều hệ vector cung cấp (pgvector có HNSW, Milvus có tài liệu HNSW riêng); không có số xếp hạng mức phổ biến!

How it works:
1. Each vector becomes a node in a multi-layer graph
2. Edges connect to nearest neighbors (geometrically close vectors)
3. Higher layers have fewer nodes = "express lanes"

Search process:
1. Start at top layer (sparse, fast jumps)
2. Greedy search: move to neighbor closest to query
3. Repeat until can't get closer
4. Drop to next layer (more detail)
5. At Layer 0: thorough local search for K nearest

Độ phức tạp tìm kiếm tăng chậm (xấp xỉ logarit) theo n; recall phụ thuộc dữ liệu và ef_search: đo bằng recall@K.

Parameters (tên pgvector, đo bằng CREATE INDEX / SHOW):
- m (M): số kết nối tối đa mỗi nút; mặc định 16, hợp lệ 2-100
- ef_construction: chất lượng lúc xây; mặc định 64, phải >= 2 × m
- hnsw.ef_search: chất lượng lúc truy vấn; mặc định 40, hợp lệ 1-1000

Pros: Very fast queries, recall cao khi dữ liệu có cấu trúc
Cons: Bộ nhớ lớn (đo: 831 byte/vector cho 128 chiều so với 512 byte vector thô; 8192-10 345 byte/vector cho 1536 chiều), xây index chậm (đo: 100k × 128 chiều 23-44 s)
Best for: Real-time search, moderate scale

IVF (index tệp đảo ngược):

text
Architecture: Partition vectors into clusters using k-means

Cluster centroids:   C1      C2      C3      C4
                     │       │       │       │
Vectors:           [v1,v2]  [v3]  [v4,v5] [v6,v7,v8]

Search process:
1. Find nearest nprobe centroids to query
2. Search only vectors in those clusters
3. Return K nearest neighbors

Example:
- 1000 clusters, search 10 → eliminate 99% of comparisons

Parameters:
- nlist (pgvector: lists): số cụm; khởi điểm rows/1000 đến 1M hàng, sqrt(rows) khi trên 1M
- nprobe (pgvector: probes): số cụm được tìm; khởi điểm sqrt(lists), cao hơn thì recall tốt hơn nhưng chậm hơn

Pros: Low memory, fast build, handles inserts well
Cons: Recall có thể thấp hơn HNSW ở cùng độ trễ (phụ thuộc dữ liệu; đo lại bằng dữ liệu của mình)
Best for: Large datasets, memory constrained

Edge problem: Query near cluster boundary may miss neighbors
Solution: Search multiple adjacent clusters (nprobe > 1)

LSH (băm nhạy theo vùng lân cận):

text
Different approach: Hash functions that CAUSE collisions for similar items

How it works:
1. Draw random hyperplanes through vector space
2. Each vector is "above" or "below" each hyperplane = 1 bit
3. 8 hyperplanes = 8-bit hash
4. Similar vectors → same side of most hyperplanes → similar hash

Multiple hash tables improve recall:
- Single table might miss similar vectors
- Multiple tables with different hyperplanes increase probability

Query time:
1. Hash query vector in all tables
2. Collect candidates from matching buckets
3. Compute exact distances on candidate set

Pros: Simple, fast index build, good for streaming data
Cons: Recall có thể thấp hơn HNSW (doc không nêu số; đo lại bằng dữ liệu của mình)
Best for: Very fast index building, Hamming distance

Annoy (Approximate Nearest Neighbors Oh Yeah):

text
From Spotify - forest of random projection trees

Build:
1. Pick two random vectors, draw hyperplane between them
2. Split: left subtree (one side), right subtree (other)
3. Repeat until leaves have ~100 vectors
4. Build many trees (10-100) with different random splits

Search:
1. Traverse all trees toward query's leaf
2. Collect candidate leaves
3. Compute exact distances on union

Killer feature: Memory mapping (mmap)
- Index as single file, multiple processes share it
- Works with indexes larger than RAM
- Instant loading (no deserialization)

Downside: IMMUTABLE - can't add/remove vectors after build
Best for: Static datasets, memory-mapped indexes

Algorithm Comparison:

text
Algorithm     Memory     Build Time    Query Time    Recall                      Updates
────────────────────────────────────────────────────────────────────────────────────────
HNSW          High       Slow          Very Fast     đo theo ef_search           Expensive
IVF           Medium     Fast          Medium        đo theo nprobe              Easy
LSH           Medium     Very Fast     Medium        đo                          Easy
Annoy         Low*       Medium        Fast          đo theo số cây/search_k     None
Flat (Exact)  Low        None          Very Slow     100%                        Easy

* Annoy uses mmap, can exceed RAM
Ví dụ đo, không phải quy luật (pgvector 0.8.7, 100k vector 128 chiều ngẫu nhiên, đổi theo máy):
HNSW m=16 ef_search=40 recall@10 0,34; IVFFlat lists=316 probes=10 recall@10 0,22.

Bài toán lọc:

text
Real queries: "Find similar items THAT ARE in stock AND under $100"
Not just: "Find similar items"

Two approaches:

Post-filtering (search then filter):
1. Find top-N similar vectors (N >> K)
2. Apply filters
3. Keep top-K
Problem: Restrictive filter → might not find K results

Pre-filtering (filter then search):
1. Filter metadata first
2. Vector search on filtered subset
Problem: May not use fancy index structures

Best approach: Depends on data selectivity
- Highly selective filter (1% match) → pre-filter
- Low selectivity (50% match) → post-filter or hybrid

Database Implementations:

text
pgvector (PostgreSQL):
- Query planner chooses: vector index OR B-tree
- Highly selective filter → skip vector index, brute force on filtered rows
- Awkward middle ground → suboptimal plans; pgvector ≥0.8.0 has iterative index scans (hnsw.iterative_scan) to return enough rows after filtering

Elasticsearch:
- Filter during HNSW traversal, not after
- Restrictive filters slow down (traverse more graph)
- Guaranteed K results if they exist
- Native hybrid: BM25 keyword + vector similarity

Pinecone:
- Metadata filtering as first-class feature
- Filter + vector search in single operation

Tìm kiếm lai (Vector + từ khoá):

text
Query: "red running shoes"

Vector alone: May return "comfortable sneakers" (similar meaning)
Keyword alone: May miss semantically related products

Hybrid:
score = α × vector_score + (1-α) × keyword_score

α = 0.5 → balanced
α = 0.7 → favor semantic
α = 0.3 → favor keywords

Ghi, cập nhật và bảo trì index (Inserts, Updates, and Index Maintenance) ​

Write Challenges:

text
Vector DBs optimized for reads, writes are complex:

HNSW Insert:
- Find position in graph
- Update connections at each layer
- Sau nhiều lần chèn nên đo lại recall (chưa có số đo ở đây); nếu giảm thì xây lại index

IVF Insert:
- Assign to nearest cluster → easy
- But clusters drift, may need rebuild

Solution: Hot/Cold Index Architecture
┌─────────────┐    ┌──────────────┐
│  Hot Index  │ +  │  Cold Index  │
│  (recent)   │    │  (older)     │
│  small/fast │    │  optimized   │
└─────────────┘    └──────────────┘
        ↓ periodic merge & rebuild

Index Rebuild:

text
Đo thời gian xây trên dữ liệu của bạn (ví dụ đo: HNSW 100k vector 128 chiều mất 23-44 s, đổi theo máy; tăng theo n, số chiều, ef_construction).
Options:
- Background rebuild while serving from old index
  (pgvector: CREATE INDEX CONCURRENTLY rồi DROP INDEX CONCURRENTLY, hoặc REINDEX INDEX CONCURRENTLY; không khoá ghi)
- Blue-green deployment with new index
- Hot index for recent, scheduled cold rebuild

Các Vector Database phổ biến ​

Comparison Matrix:

text
Database      Type           Best For                    Index Types
────────────────────────────────────────────────────────────────────────
Pinecone      Managed        Ease of use, serverless     Proprietary
Milvus        Open-source    Large scale, flexibility    HNSW, IVF, DiskANN
Weaviate      Open-source    Hybrid search, GraphQL      HNSW
Qdrant        Open-source    Rust-based; đo benchmark trên dữ liệu của bạn    HNSW
Chroma        Open-source    Simplicity, local dev       HNSW
pgvector      Extension      PostgreSQL users            IVFFlat, HNSW
Elasticsearch Add-on         Existing ES infrastructure  HNSW

Pinecone:

python
# pip install pinecone
# minh hoạ, không chạy độc lập: cần API key, index "my-index" đã tạo với dimension khớp,
# và vector đủ chiều (dấu ... chỉ phần còn lại của vector)
from pinecone import Pinecone

pc = Pinecone(api_key="xxx")
index = pc.Index("my-index")

# Upsert
index.upsert(vectors=[
    ("id1", [0.1, 0.2, ...], {"text": "Hello"}),
    ("id2", [0.3, 0.4, ...], {"text": "World"})
])

# Query with filter
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=10,
    filter={"category": {"$eq": "tech"}}
)

Pros: Zero ops, auto-scaling, low latency (đo trên index và workload của bạn) Cons: Không có bản tự host mã nguồn (có BYOC: data plane chạy trong tài khoản cloud của bạn), vendor lock-in, cost at scale

Milvus:

python
# pip install pymilvus
# chưa chạy: cần Milvus server (etcd + MinIO + milvus) ở localhost:19530
from pymilvus import connections, Collection, CollectionSchema, FieldSchema, DataType

connections.connect("default", host="localhost", port="19530")

schema = CollectionSchema([
    FieldSchema("id", DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema("embedding", DataType.FLOAT_VECTOR, dim=768),
])
collection = Collection("documents", schema)

# Create with HNSW index
index_params = {
    "metric_type": "COSINE",
    "index_type": "HNSW",
    "params": {"M": 16, "efConstruction": 200}
}
collection.create_index("embedding", index_params)
collection.load()

# Search (query_vector: list 768 số thực)
collection.search(
    data=[query_vector],
    anns_field="embedding",
    param={"metric_type": "COSINE", "params": {"ef": 100}},
    limit=10
)

Kiến trúc:

  • Compute (query node) tách khỏi storage (S3/MinIO)
  • Metadata nằm trong etcd (hoặc TiKV)
  • Dự án của LF AI & Data Foundation, cộng đồng hoạt động

Pros: scale ngang, nhiều loại index, hỗ trợ GPU Cons: triển khai phức tạp, cần kinh nghiệm vận hành

Weaviate:

python
# pip install weaviate-client   (v4)
# Chưa chạy với OpenAI: cần khoá OPENAI_APIKEY; đã chạy cùng API với Configure.Vectors.self_provided()
import weaviate
from weaviate.classes.config import Configure, Property, DataType

client = weaviate.connect_to_local()

# Auto-vectorize with OpenAI
client.collections.create(
    name="Document",
    vector_config=Configure.Vectors.text2vec_openai(),
    properties=[Property(name="content", data_type=DataType.TEXT)],
)
documents = client.collections.use("Document")

# Hybrid search (vector + keyword): alpha=0 chỉ từ khoá, alpha=1 chỉ vector
response = documents.query.hybrid(query="greeting message", alpha=0.5, limit=10)
for obj in response.objects:
    print(obj.properties["content"])

client.close()

Pros: có sẵn hybrid search, embedding tích hợp, GraphQL API Cons: chưa có số so sánh quy mô với Milvus ở đây; thử bằng tải thật

pgvector (PostgreSQL):

sql
-- PostgreSQL 18 + pgvector 0.8: bảng 1536 chiều có dữ liệu thật để chạy được
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
    id        serial PRIMARY KEY,
    category  text,
    content   text,
    embedding vector(1536)
);

-- 5 000 dòng ngẫu nhiên, 5 % thuộc category 'tech'
INSERT INTO documents (category, content, embedding)
SELECT CASE WHEN g % 20 = 0 THEN 'tech' ELSE 'other' END,
       'doc ' || g,
       (SELECT array_agg(random()::real) FROM generate_series(1, 1536) WHERE g > 0)::vector
FROM generate_series(1, 5000) g;

-- Index HNSW (vector index được tối đa 2000 chiều; 1536 vừa đủ)
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);

-- Tìm 10 dòng gần nhất theo khoảng cách cosine, lọc theo category
-- (vector truy vấn lấy từ dòng id = 1; ứng dụng thật truyền embedding của câu hỏi)
SELECT id, content, embedding <=> q.v AS distance
FROM documents, (SELECT embedding AS v FROM documents WHERE id = 1) q
WHERE category = 'tech'
ORDER BY embedding <=> q.v
LIMIT 10;

Pros: SQL quen thuộc, transaction ACID, join được với dữ liệu quan hệ Cons: Giới hạn theo RAM/đĩa của một node (bảng không phân vùng tối đa 32 TB), ít loại index hơn (IVFFlat, HNSW); dùng halfvec/quantization hoặc partition để mở rộng Best for: quy mô nhỏ đến vừa, đội đã dùng PostgreSQL

Mẫu RAG (Retrieval-Augmented Generation) ​

Kiến trúc:

text
User Query: "What are the benefits of exercise?"
         ↓
    [Embed Query]
         ↓
    [Vector Search] → Top 5 relevant document chunks
         ↓
    [Augment Prompt with Context]
         ↓
    [LLM (GPT-4, Claude)] → Answer with citations

Implementation:

python
# pip install openai
# minh hoạ, không chạy độc lập: cần khoá OPENAI_API_KEY, import openai và đối tượng vector_db do bạn dựng
# 1. Embed query
query = "What are the benefits of exercise?"
query_embedding = openai.embeddings.create(
    model="text-embedding-3-small", input=query
).data[0].embedding

# 2. Retrieve relevant chunks
results = vector_db.search(query_embedding, limit=5)
context = "\n\n".join([r.payload["content"] for r in results])

# 3. Generate answer
prompt = f"""Answer based on context below.

Context:
{context}

Question: {query}

Answer:"""

response = openai.chat.completions.create(
    model="<tên-model-chat>",  # thay bằng model hiện hành của nhà cung cấp
    messages=[{"role": "user", "content": prompt}]
)

Thực hành tốt khi chia chunk:

text
Document: 10,000 words
         ↓
Split into chunks
         ↓
[chunk1: 500 tokens] [chunk2: 500 tokens] ...
         ↓
Embed each chunk separately

Strategies:
- Fixed size: ví dụ khởi điểm 256-512 tokens mỗi chunk (không phải chuẩn; đo recall trên dữ liệu của mình)
- Semantic: Split by paragraphs/sections
- Overlapping: ví dụ khởi điểm 10-20% giữa các chunk (minh hoạ)

Include metadata: source, page, section

Mẫu scale Vector DB ​

Khuyến nghị theo quy mô:

text
Scale                   Strategy                    Database (ví dụ, mốc minh hoạ: đo trên dữ liệu và phần cứng của bạn)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────
<1M vectors             Single node, HNSW           Any
1M-100M vectors         Replicas + sharding         Milvus, Qdrant
100M-1B vectors         Distributed, IVF-PQ         Milvus, Pinecone
1B+ vectors             Tiered hot/cold, DiskANN    Milvus

Memory estimation (đo bằng pg_relation_size trên pgvector 0.8.7):
- Vector thô: 1M vectors × 1536 dims × 4 bytes = 6,144 GB (float32)
- HNSW pgvector, 20 000 vector 1536 chiều: 8192-10 345 byte mỗi vector (khoảng 1-1,3 trang 8 KB mỗi vector, đổi theo lần xây), nên 1M vector ≈ 8,2-10,3 GB index
- Cột halfvec(1536): 4096 byte mỗi vector trong index, 1M vector ≈ 4,1 GB
- Bảng gốc (vector lớn bị TOAST) và metadata cộng thêm: đo trên bảng thật

Tối ưu chi phí:

text
- Use IVF-PQ for cold data (compressed, less RAM)
- Keep hot data with HNSW (fast queries)
- Archive rarely accessed vectors to S3
- halfvec giảm index còn 4096 byte/vector (đo; vector 1536 chiều đo 8192-10 345), tức giảm khoảng 2-2,5 lần; Product Quantization nén nhiều lần hơn, đổi lấy recall: đo recall@K trước khi chọn

Khi nào dùng Vector Database ​

✅ Nên dùng khi:

text
- Semantic/similarity search (not exact match)
- Working with embeddings (text, image, audio)
- Building RAG applications
- Recommendation systems
- Anomaly detection with embeddings

❌ Không nên dùng khi:

text
- Exact match queries → traditional DB
- Small dataset (<10K vectors) → in-memory array is fine
- No semantic understanding needed
- ACID transactions required → pgvector
- Complex relational queries

Ma trận chọn:

text
Requirement                              Solution
────────────────────────────────────────────────────────────────
Just trying out, <1M vectors             Chroma (local), pgvector
Production, managed, no ops              Pinecone
Production, self-hosted, large scale     Milvus
Hybrid search (vector + keyword)         Weaviate, Elasticsearch
Existing PostgreSQL, moderate scale      pgvector
Cần hiệu năng cao, tự host               Qdrant (đo benchmark trên dữ liệu của bạn)

Tìm kiếm vector nhẹ (NumPy/FAISS) ​

Không phải lúc nào cũng cần Vector DB! Với small-medium datasets, NumPy hoặc FAISS là đủ. Use case thực tế: Load master data (JSON) từ S3, search với NumPy - đơn giản, không cần thêm infrastructure.

NumPy vs Vector DB:

text
                    NumPy/FAISS             Vector DB (Milvus, Pinecone)
────────────────────────────────────────────────────────────────────────
Scale               NumPy <100K; FAISS (IVF/HNSW/PQ) tới tỷ vector   Millions-Billions ✅
Search              Brute-force O(n)        ANN (HNSW/IVF), không quét đủ
Speed               đo: 100k×768, NumPy 19-84 ms/query, FAISS Flat 9 ms (đổi theo máy)   đo trên dữ liệu của bạn (ví dụ: 100k×128, HNSW 2,7 ms)
RAM                 Load all in memory      Index optimized
Setup               0 dependencies          Cần deploy service
Accuracy            100% (exact)            Phụ thuộc dữ liệu và ef_search: đo recall@K

Khi nào NumPy đủ dùng:

text
✅ NumPy/FAISS OK:
- <100K vectors (master data, product catalog)
- Batch processing, không cần realtime <10ms
- Data load từ S3/file, refresh định kỳ
- Simple POC/prototype
- Cần 100% accuracy (exact search)

❌ Cần Vector DB:
- >100K vectors, growing continuously
- Realtime search requirement (<50ms)
- Production với concurrent users
- Need filtering + persistence built-in

Code mẫu - NumPy search (đang dùng):

python
# pip install numpy boto3
# minh hoạ: cần bucket S3 có master_data.json và query_embedding là vector cùng chiều
import numpy as np
import json
import boto3

# Load master data từ S3
s3 = boto3.client('s3')
obj = s3.get_object(Bucket='my-bucket', Key='master_data.json')
master_data = json.loads(obj['Body'].read())

# Extract vectors, chuẩn hoá MỘT lần lúc nạp
vectors = np.array([item['embedding'] for item in master_data], dtype='float32')
vectors_norm = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
ids = [item['id'] for item in master_data]

# Search function
def search(query_vector, top_k=10):
    # Cosine similarity
    query_norm = query_vector / np.linalg.norm(query_vector)
    similarities = vectors_norm @ query_norm

    top_indices = np.argpartition(similarities, -top_k)[-top_k:]
    top_indices = top_indices[np.argsort(similarities[top_indices])[::-1]]
    return [(ids[i], similarities[i]) for i in top_indices]

# Usage
results = search(query_embedding, top_k=5)

Upgrade path khi cần scale:

text
Scale              Solution                   Effort   (mốc minh hoạ: đo độ trễ trên dữ liệu của bạn)
────────────────────────────────────────────────────────────────
<10K vectors       NumPy (hiện tại) ✅         None
10K-100K           FAISS (drop-in faster)     Low - thêm library
100K-1M            pgvector (đã có Postgres)  Medium - thêm extension
>1M vectors        Milvus/Pinecone            High - new infrastructure

FAISS thay thế trực tiếp:

python
# pip install faiss-cpu numpy
# chạy sau khối NumPy ở mục này (dùng `vectors` và `query_vector`, cùng 768 chiều)
import faiss

# Thay thế NumPy khi cần nhanh hơn
index = faiss.IndexFlatIP(768)  # 768 dimensions, Inner Product
xb = vectors.astype('float32'); faiss.normalize_L2(xb); index.add(xb)  # normalize vectors và cả query để IP = cosine

# Search - IndexFlat vẫn là exact brute-force (BLAS): đo 100k×768 nhanh hơn NumPy 2-9 lần (9 ms so với 19-84 ms, đổi theo máy); nhanh hơn nhiều chỉ khi dùng IVF/HNSW
q = query_vector.reshape(1, -1).astype('float32')
faiss.normalize_L2(q)
distances, indices = index.search(q, k=10)

Anti-pattern của Vector DB ​

❌ Sai model embedding:

text
Sai: Tài liệu y khoa dùng embedding đa dụng
Đúng: Model theo miền (PubMedBERT, LegalBERT)

❌ Không có chiến lược chunking:

text
Sai: Embed cả tài liệu 10 000 từ thành một vector
Đúng: Cắt thành các chunk, có chồng lấp; đo recall@K để chọn cỡ chunk

❌ Bỏ qua lọc metadata:

text
Sai: Vector search toàn bộ sản phẩm
Đúng: Lọc category/stock và đo recall khi có filter: HNSW lọc SAU khi duyệt index nên có thể trả thiếu dòng (xem mục đầu: iterative_scan, partial index)

❌ Không theo dõi recall:

text
Sai: Deploy rồi bỏ đó
Đúng: Tập đánh giá, đo recall@K, cảnh báo khi giảm