06.5 Vector Databases: Choosing and Using One

RetrievalLesson 5 of 1017,041 words14 parts
Module 06 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Lesson 02.3 taught what embeddings are and gave you a two-paragraph overview of vector databases. Lesson 06.3 showed how similarity becomes a search operation, and lesson 06.4 went deep on how approximate indexes (HNSW, IVF, quantization) actually work. This lesson is the practical one: which system do you put your vectors in, and how do you use it on day one? We compare the landscape as of November 2026, go hands-on with three of the most common choices — pgvector (vectors inside Postgres), Qdrant (a dedicated vector database), and Chroma (an embedded database you can run in your own process) — and then cover every other option end to end (FAISS and hnswlib, sqlite-vec, DuckDB VSS, LanceDB, Elasticsearch, OpenSearch, Redis, Pinecone and AWS S3 Vectors), all behind one shared interface you can test without any server.

What you'll learn

  • What a vector database actually adds beyond an index: persistence, CRUD, metadata and filtering, multi-tenancy, replication, backups, auth and observability — and how that differs from a vector library and from vector support inside a database you already run
  • The landscape as of November 2026: a verified comparison table covering NumPy/FAISS/hnswlib, pgvector, sqlite-vec, DuckDB VSS, Chroma, LanceDB, Qdrant, Pinecone, Elasticsearch, OpenSearch, Redis and AWS S3 Vectors — plus a decision flow and a decision table for picking one
  • pgvector end to end: vector/halfvec columns, distance operators, HNSW and IVFFlat indexes, ef_search, metadata WHERE filters, EXPLAIN checks, upserts, deletes and transactions, from psycopg
  • Qdrant end to end: collections, points and payloads, named vectors, payload filters and payload indexes, hnsw_ef, snapshots, local mode vs server mode, sync and async clients
  • Chroma end to end: ephemeral vs persistent clients, collections and embedding functions, add/upsert/query/get, where filters, HNSW configuration and its limits
  • A VectorStore protocol with adapters for pgvector, Qdrant and Chroma plus a pure-NumPy in-memory store — the seam that keeps your application code testable and your database choice reversible
  • The other options end to end (Part 8): for FAISS/hnswlib, sqlite-vec, DuckDB VSS, LanceDB, Elasticsearch, OpenSearch, Redis, Pinecone and AWS S3 Vectors you get the mental model, install, a VectorStore adapter with create/upsert/filtered query/delete, persistence, honest pros and cons, when to choose or avoid it, and gotchas — ending in a one-table "which one when" summary
  • Data modelling for vector stores: the shape of a record, where the text lives, deterministic IDs, collections vs namespaces vs filters, multiple vectors per record, schema evolution, dimensions and dtypes, and databases that embed for you
  • Operations: persistence and backups, capacity planning arithmetic, replication and sharding, upgrades, monitoring, managed-service cost drivers, and migrating between stores without lock-in
  • Security: API keys, network isolation, encryption, tenant isolation, deletion guarantees and audit
  • Local and embedded options for prototypes and tests, and the honest advice to not deploy a cluster for 20,000 chunks
  • How to test code that talks to a vector store: fakes, in-memory implementations and contract tests
  • The failure gallery: the ways vector-store projects actually break in production — dimension mismatches, wrong distance metrics, missing indexes, filter shrinkage, orphan vectors, text/vector drift, cold starts and memory walls — and the fix for each

What you don't need

  • A running database. Every server-backed sample ships with a docker run/docker compose snippet or a cloud-setup note you can follow yourself later; the code is written to be copied and run. Qdrant's :memory: mode and Chroma's ephemeral client need no server at all, and the VectorStore in-memory adapter runs on plain Python.
  • API keys. Nothing in this lesson calls an embedding or chat API, and the managed-service samples (Pinecone, S3 Vectors, Elasticsearch, OpenSearch, Redis) read credentials from environment variables but are never run here; vectors in the examples are tiny hand-made ones or seeded synthetic data, and any output that would come from a real service is labelled illustrative.
  • Deep knowledge of ANN internals. Lesson 06.4 owns HNSW/IVF/quantization mechanics; this lesson uses them and links back. Filtering strategies in depth belong to lesson 06.6; here we cover enough to use them correctly on day one.

Setup

The samples need Python 3.11+ and these packages. The commands install the newest release of each (install commands in this lesson use package names only; pin versions in your own lockfile); the samples were written and checked against pgvector 0.5.1, psycopg 3.3.8, qdrant-client 1.20.0 and chromadb 1.5.9 as of November 2026. Vector database client libraries change their method names between releases, so a newer major version may break a call; check the library's changelog if something does not match:

bash
uv add numpy pgvector "psycopg[binary]" qdrant-client chromadb python-dotenv
# or: pip install numpy pgvector "psycopg[binary]" qdrant-client chromadb python-dotenv

The Part 8 stores each list their own install line (pip install faiss-cpu hnswlib, sqlite-vec, duckdb, lancedb, elasticsearch, opensearch-py, redis, pinecone, boto3); you only install the ones you evaluate.

First time? Create a project with uv init vector-stores --bare --python 3.13 && cd vector-stores, then run scripts with uv run python file.py. See lesson 03.1, Part 4 for the full setup.

The pgvector samples also need a Postgres server with the extension. As a reference (do not run it now — this phase writes code only):

bash
docker run --name pgvector -e POSTGRES_PASSWORD=postgres -p 5432:5432 pgvector/pgvector:pg17

Qdrant as a reference:

bash
docker run -p 6333:6333 -p 6334:6334 -v "$(pwd)/qdrant_storage:/qdrant/storage" qdrant/qdrant

Chroma needs nothing for the ephemeral client used in the samples. A .env file is only needed if you later point these samples at a hosted service:

bash
# .env  (never commit this file)
QDRANT_URL=http://localhost:6333
QDRANT_API_KEY=...        # only for Qdrant Cloud or a secured self-hosted instance
CHROMA_TENANT=...
CHROMA_DATABASE=...
CHROMA_API_KEY=...        # only for Chroma Cloud
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres

What you must be able to do after this lesson#

  • Explain what a vector database adds beyond an index
  • Store and query vectors in pgvector, Qdrant and Chroma
  • Write code against a VectorStore interface instead of one vendor
  • Design the data model for a vector collection
  • Decide when a vector database is not needed

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Do we need a vector database, or can we just use FAISS?" Part 1: What a vector database adds and 8.1 FAISS and hnswlib
"We're already on Postgres — is pgvector enough?" 1.3 Vector libraries vs vector databases vs in-database vector search and the decision flow
"Should we use Pinecone, Qdrant, pgvector or Elasticsearch?" Part 2: The landscape and 8.10 Which one when
"Can I just use SQLite, DuckDB or LanceDB for this?" 8.2 sqlite-vec, 8.3 DuckDB VSS, 8.4 LanceDB
"What does CREATE INDEX ... USING hnsw actually buy us?" 4.3 Exact vs approximate: what an index changes
"Why did my filtered query return two results instead of ten?" 4.4 The query, with metadata filtering (deep dive in 06.6)
"Where should the chunk text live — in the vector DB or in Postgres?" 9.1 What a record is
"How big will this cost at a million chunks?" 10.2 Capacity planning
"How do we test code that writes to Qdrant without a Qdrant?" Part 13: Testing
"We're locked into Pinecone — how painful is leaving?" 10.4 Migration and avoiding lock-in
"Search returns 3 results instead of 10, or nothing at all?" Part 14: The failure gallery

Part 1: What a vector database adds beyond an index#

1.1 Recap: the four layers#

A "vector search system" is really four separable pieces, and vendors blur them together:

flowchart LR
    subgraph app ["Your application"]
        Q["query text"] --> E1["embedding model<br/>(06.1)"]
        E1 --> VEC["query vector"]
    end
    subgraph store ["Storage + index"]
        VEC --> SEARCH["similarity search<br/>exact or ANN (06.3/06.4)"]
        SEARCH --> HITS["ranked ids + scores"]
    end
    subgraph extra ["Everything else a DB adds"]
        META["metadata + filters"]
        CRUD["insert/update/delete"]
        OPS["persistence, backups,<br/>replication, auth, metrics"]
    end
    HITS --> app
  1. Vectors — the embeddings themselves, produced by a model (lesson 06.1).
  2. The index — the data structure that makes nearest-neighbour search fast: brute force, HNSW, IVF, quantized variants (lesson 06.4).
  3. The store — persistence, point CRUD, and usually metadata storage with filtering.
  4. The service — replication, sharding, backups, auth, observability, managed operations.

A vector library (FAISS, hnswlib, USearch) gives you layer 2 and sometimes 3-in-memory. A vector database gives you 2+3+4 as a service. Vector support inside a general-purpose database (pgvector in Postgres, dense_vector in Elasticsearch, knn_vector in OpenSearch, vector indexes in Redis) gives you 2+3 inside infrastructure you may already run, with layer 4 inherited from that database.

1.2 What "a vector database" adds, concretely#

Capability What it means for you Who has it
Persistence Vectors survive restarts; data lives on disk/object storage, not just RAM Every real database; not a bare FAISS index unless you serialize it yourself
CRUD by ID Upsert, get, delete individual vectors/points; updates don't require rebuilding the index from scratch (though ANN indexes degrade gracefully, not perfectly — see 06.4) All of them
Metadata storage + filtering Store tenant, document, date, language, ACL fields next to each vector and filter during search All real ones; the quality varies a lot (Part 2, and 06.6)
Hybrid features BM25/keyword search, sparse vectors, reranking, fusion in one system Qdrant, Pinecone, Elasticsearch/OpenSearch, Redis, Chroma Cloud, LanceDB; pgvector only via Postgres FTS
Multi-tenancy Per-tenant isolation via namespaces, partitions or filter fields Namespaces (Pinecone, Qdrant collections, Chroma collections), partition keys and tenant shards (Qdrant payload shards, sqlite-vec partition keys), Postgres partitions/row-level security
Replication & sharding Survive node loss; spread a billion vectors across machines Dedicated engines and managed services; single-node embedded tools can't
Backups & upgrades Snapshots, point-in-time recovery, rolling upgrades Managed services and server-mode DBs
AuthN/AuthZ, TLS, audit API keys, RBAC, network isolation, audit logs Cloud services and server-mode DBs; embedded libraries have none of this by themselves
Observability Query latency, index build progress, memory, recall proxies, Prometheus metrics Managed services and server-mode DBs
Managed operations Someone else patches, scales and pages Cloud offerings only
flowchart TD
    A["I need vector search"] --> B{"How many vectors,<br/>and what else do I need?"}
    B -->|"under ~100k,<br/>one process, prototypes"| C["Vector library:<br/>NumPy brute force, FAISS, hnswlib"]
    B -->|"already run Postgres<br/>and the corpus is modest"| D["pgvector"]
    B -->|"need a dedicated,<br/>purpose-built engine"| E["Qdrant / Pinecone / ..."]
    B -->|"want zero new infra,<br/>embedded in the app"| F["Chroma / LanceDB / sqlite-vec / DuckDB VSS"]
    B -->|"already pay for<br/>Elasticsearch / OpenSearch / Redis"| G["Vector search inside that DB"]
Option Persistence Filtering Multi-tenancy Ops burden Best when
Vector library (FAISS, hnswlib, USearch — owned by 06.4) You serialize it yourself You post-filter or build it You build it You own everything Prototypes, batch jobs, a component inside a larger system
pgvector Postgres SQL WHERE + Postgres indexes Table partitioning / RLS You already run Postgres The corpus fits comfortably in one Postgres; you want joins, transactions, one backup story
Dedicated vector DB (Qdrant, Pinecone) Yes Native, usually fast Native (namespaces/tenants) Self-host cluster or managed cloud Vector search is a core workload at real scale, or you want the best-in-class filtering/hybrid story
Embedded DB (Chroma local, LanceDB, sqlite-vec, DuckDB VSS) Files on disk Varies Varies None — it is your process Single-node apps, edge, tests, "start simple"
Vector inside your existing DB (Elasticsearch dense_vector, OpenSearch knn_vector, Redis RediSearch) Yes Native, often excellent Native You already run it You're already paying for and operating that database

1.4 What this lesson will not do#

  • It will not re-teach ANN index internals — that's 06.4. When a store exposes hnsw_ef or ef_search, think "the query-time recall knob" and go there for the mechanics.
  • It will not teach deep filtering design — ACL filters, selectivity and partition strategies are 06.6. Here you learn the syntax each store uses so 06.6 has somewhere to stand.
  • It will not cover BM25 or hybrid fusion — 06.7 and 06.8. Where a store has native hybrid features, this lesson names them so you know they exist.

Part 2: The landscape as of November 2026#

Reference

2.1 The comparison table#

Type key: lib = library (no server), embedded = database that runs inside your process, server = self-hostable server/cluster, managed = hosted service (usually also self-hostable for open-source ones), cloud-only = proprietary hosted service.

Option Type Index types Filtering Hybrid / sparse Multi-tenancy Scale notes Licence Notable limits / gotchas
NumPy / FAISS / hnswlib lib flat, HNSW, IVF, PQ (FAISS); HNSW (hnswlib) you build it no you build it single node; FAISS has GPU indexes FAISS MIT; hnswlib/USearch Apache-2.0 no persistence/CRUD/auth; you own everything (06.4)
pgvector extension in Postgres HNSW, IVFFlat (+ binary-quantized expression indexes) full SQL WHERE, Postgres indexes, RLS, partitions Postgres FTS for BM25; sparsevec type partitions / row-level security comfortable to low-millions of vectors per node; memory-bound for HNSW PostgreSQL indexable limits: vector ≤ 2,000 dims, halfvec ≤ 4,000, bit ≤ 64,000, sparsevec ≤ 1,000 non-zeros (HNSW); a column can store up to 16,000 dims, so wider vectors need halfvec, truncation or no index; Postgres 13+; filters apply after ANN scan unless iterative scan (0.8.0+) is enabled
sqlite-vec SQLite extension flat KNN (no ANN graph) metadata columns in WHERE no partition-key columns small/medium; per-file MIT / Apache-2.0 pre-v1; float[N] max 8,192 dims; best for prototypes and edge
DuckDB VSS DuckDB extension HNSW (experimental) SQL WHERE DuckDB FTS separately you build it analytical/batch workloads MIT experimental; in-memory only unless experimental persistence flag
Chroma embedded + server + cloud HNSW (self-hosted single node); SPANN (distributed/Cloud) where/where_document metadata filters Cloud: sparse vectors, FTS, RRF hybrid, GroupBy; self-hosted: FTS/regex collections single-node sweet spot; Cloud for scale Apache-2.0 Cloud configuration index params ignored (SPANN fixed); distances are lower-is-better
LanceDB embedded + enterprise IVF_PQ (default), IVF_RQ (high compression, dims divisible by 8), IVF_HNSW_SQ, IVF_FLAT (binary/Hamming); the embedded library builds a few more variants (LanceDB docs, November 2026); the distance metric is fixed at index build time SQL WHERE FTS + hybrid + reranking namespaces/tables embedded: millions comfortably; Enterprise for petabyte lakehouse claims Apache-2.0 columnar "multimodal lakehouse" on the Lance format; a different mental model from a document DB
Qdrant server + embedded local mode + cloud HNSW (default), quantization (scalar/product/binary/TurboQuant), on-disk quantized configs rich Filter DSL, payload indexes, is_tenant shards sparse vectors, BM25/full-text, hybrid prefetch+fusion, multivectors/MaxSim, rerankers collections, payload-partition, user-defined sharding, tiered multitenancy millions→billions; Qdrant Cloud limits a cluster to 1,000 collections by default (Qdrant multitenancy docs, November 2026) Apache-2.0 :memory: and path= local modes; Query API since server v1.10.0
Pinecone cloud-only proprietary ANN (serverless indexes) metadata filters document indexes: dense + sparse + BM25 full-text in one index; integrated embedding models namespaces (+ aliases) serverless, very large proprietary SaaS sparse limits (2,048 non-zeros/vector, 10 upserts/s, 100 QPS, top_k 10k); namespace count varies by plan (100 Starter → 1M Enterprise); no self-host
Elasticsearch server + Elastic Cloud HNSW + quantized variants (index_options types hnsw, int8_hnsw, int4_hnsw, bbq_hnsw, the *_flat variants and bbq_disk; the default for float vectors depends on version and dimensions: int8_hnsw in 9.0, bbq_hnsw from 9.1 for 384+ dims, see 06.4, 4.6), dims up to 4,096 full query DSL, runtime fields knn + rank_features, RRF retriever, semantic rerank index-per-tenant or routing large; memory-hungry for vectors Elastic License 2.0 on the official downloads; source also offered under SSPL or AGPLv3 (AGPLv3 option added in 2024 — verify what you actually download before relying on it) vectors excluded from _source by default now; vector index build is expensive
OpenSearch server + managed (AWS) k-NN via Faiss/NMSLIB/Lucene engines, HNSW method (m, ef_construction), exact via script full query DSL hybrid query + search pipelines (score normalization or RRF ranker) index-per-tenant or ISM large Apache-2.0 knn_vector dim ≤ 16,000; k-NN plugin historically separate, now integrated
Redis server + Redis Cloud FLAT (<1M vectors), HNSW (>1M), SVS-VAMANA; FLOAT32/16/64, BFLOAT16, INT8, UINT8 RediSearch filters on hashes/JSON hybrid queries, vector range queries index per tenant in-memory, large RSALv2 / SSPLv1 / AGPLv3 (choice, from Redis 8) memory-bound; query syntax is RediSearch dialect, not a document API
AWS S3 Vectors managed cloud (AWS) proprietary object-storage ANN up to 50 metadata keys per vector in total (filterable metadata is capped at 2 KB per vector; at most 10 keys per index can be non-filterable) metadata filters; pair with OpenSearch for hybrid vector indexes in buckets GA Dec 2025: 2B vectors/index, 10k indexes/bucket, ~100 ms frequent / <1 s infrequent queries proprietary service object-store economics over latency; no self-host; write throughput ~1,000 PUT/s streaming

2.2 How to read this table#

  • "Type" predicts your ops bill. lib and embedded cost you engineering time; server costs you a cluster; managed/cloud-only costs money and lock-in. There is no free lunch, only different currencies.
  • Index types are the engine's business; the store's business is everything around them. Two databases can share HNSW and still differ completely on filtering, tenancy and hybrid.
  • Filtering is where document DBs and vector DBs diverge most. Postgres gives you arbitrary SQL; Qdrant gives you a typed filter DSL with payload indexes; Chroma gives you a simple where document. The strategy (pre-filter vs post-filter vs in-graph) is 06.6's subject.
  • Hybrid support is table stakes in 2026 for the dedicated engines — but "supports hybrid" ranges from "one API call does RRF for you" (Qdrant prefetch+fusion, Elasticsearch RRF retriever, OpenSearch hybrid query, Pinecone document indexes) to "you combine two result sets yourself" (pgvector + Postgres FTS, Chroma self-hosted).
  • Licence matters if you self-host or embed. Apache-2.0/MIT/BSD/PostgreSQL are permissive. SSPL/Elastic License/RSALv2/AGPLv3 have copyleft or source-available strings that your legal team will want to read — especially AGPLv3 if you modify and serve it, and SSPL if you offer it as a service. Redis and Elasticsearch are the two stores in this lesson where that reading matters most.

2.3 The decision flow#

flowchart TD
    A["Need vector search"] --> B{"Do you already run<br/>Postgres / Elasticsearch /<br/>OpenSearch / Redis?"}
    B -->|"Yes, and the corpus fits"| C["Use its vector support<br/>(pgvector, dense_vector kNN,<br/>knn_vector, Redis vector index)"]
    B -->|"No"| D{"Prototype or<br/>single-node production?"}
    D -->|"Prototype / tests / edge"| E["Embedded: Chroma, LanceDB,<br/>sqlite-vec, DuckDB VSS, or<br/>a library (NumPy, FAISS, hnswlib)"]
    D -->|"Real production service"| F{"What matters most?"}
    F -->|"Rich filtering + hybrid +<br/>multi-tenancy, self-host or cloud"| G["Qdrant"]
    F -->|"Zero ops, pay per use,<br/>low latency"| I["Pinecone"]
    F -->|"Huge cold corpus on AWS,<br/>cost over latency"| H["AWS S3 Vectors"]
    F -->|"Regulated data, must self-host"| J["Qdrant / pgvector /<br/>OpenSearch (Apache-2.0)"]
    C --> K{"Corpus outgrows it?"}
    K -->|"Yes"| F
    E --> L{"Outgrow embedded?"}
    L -->|"Yes"| F

2.4 The decision table: which store when#

Scenario Start here Why
Prototype, notebook, CI tests NumPy store (7.2) → Chroma ephemeral or Qdrant :memory: Zero infrastructure; the VectorStore interface means you don't rewrite later
Small production app, one node, < ~1M chunks pgvector if you have Postgres; otherwise Chroma PersistentClient, LanceDB or Qdrant path= One backup story, one connection pool, no new service
Local-first, desktop, mobile or edge app sqlite-vec One SQLite file, exact search, no server
Analytics, evaluation sets, data exploration with embeddings DuckDB VSS (or LanceDB) Vectors next to Parquet and dataframes; experimental, so keep source data exportable
Data-pipeline / multimodal workloads, vectors in object storage LanceDB Columnar Lance format, embedded, durable, versioned
Serious retrieval product, hybrid + filters + tenants Qdrant self-hosted or Qdrant Cloud Best-documented filter DSL, payload indexes, tenant sharding, sparse+multivector support
Fully managed, tenants map to namespaces, minimal ops Pinecone Nothing to run; namespaces for tenants; cost is usage-based and lock-in is real
Already paying for Elasticsearch/OpenSearch dense_vector/knn or knn_vector + hybrid Reuses infra, excellent hybrid story, but vectors are memory-hungry
Already on Redis, or needing sub-millisecond semantic cache Redis vector index Only if data is already there; memory-bound
AWS shop, huge or cold corpus, cost-optimized and latency-tolerant S3 Vectors Object-storage economics; pay in latency; AWS-only
Regulated/air-gapped Qdrant, pgvector, OpenSearch or Elasticsearch self-hosted Permissive licences (check Elastic's), full control, no external calls

Part 3: The same corpus, three stores#

To compare the tools line by line, every store (Parts 4 to 8) gets the same ten chunks from the module's running corpus (the fictional company handbook/help-centre material from Module 05). For readability the vectors are tiny hand-made 3-D vectors — enough to see geometry — standing in for real 768–1,536-dim embeddings. In production the numbers come from lesson 06.1's embedder; the store doesn't care about the dimension count.

python
# corpus.py — shared by every sample in this lesson
"""A tiny slice of the module's running corpus, with toy 3-D vectors.

The vectors are hand-made so the geometry is visible: chunks about the same
topic sit near each other. Real embeddings come from an embedding API or a
local model (lesson 06.1); the stores below don't care about the dimension.

`Chunk` is the store-facing record: the fields Module 05's pipeline puts on
a chunk (the 05.6 `Chunk` dataclass, stored as `ChunkMeta` in 05.8), trimmed
to what a vector store needs. `chunk_id` and `doc_id` are real deterministic
ids in 05.8's scheme — `chk_<24 hex>` from `make_chunk_id` and
`doc_<24 hex>` from `make_doc_id` (chunker_version "markdown-v1", occurrence
0). `section_path` is flattened to a " > "-joined breadcrumb string because
payload/metadata values are scalars in most stores; `meta` carries the
filterable attributes. A production record also has token_count, char/page
offsets, prev/next ids and lineage — see 05.8.
"""
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Chunk:
    chunk_id: str            # chk_<24 hex> — deterministic content id (05.8)
    doc_id: str              # doc_<24 hex> — source document id (05.8)
    index: int               # position of the chunk within its document
    section_path: str        # breadcrumb, e.g. "Leave > Vacation"
    text: str                # the chunk text itself
    meta: dict = field(default_factory=dict)
    vector: tuple[float, ...] = ()


CHUNKS = [
    Chunk(
        chunk_id="chk_2e1f324932df6bacc8135ba2",
        doc_id="doc_36bfeaa08f1cf2c901d93292", index=0,
        section_path="Leave > Vacation",
        text="Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
        meta={"tenant": "acme", "kind": "policy", "lang": "en"},
        vector=(0.9, 0.1, 0.0),
    ),
    Chunk(
        chunk_id="chk_b17014422e53553a0a9f4500",
        doc_id="doc_36bfeaa08f1cf2c901d93292", index=1,
        section_path="Leave > Sick Leave",
        text="Sick leave is separate from vacation: 10 days per year, no accrual cap.",
        meta={"tenant": "acme", "kind": "policy", "lang": "en"},
        vector=(0.85, 0.15, 0.05),
    ),
    Chunk(
        chunk_id="chk_4068dfbbce40432fbd9be309",
        doc_id="doc_36bfeaa08f1cf2c901d93292", index=2,
        section_path="Expenses > Per Diem",
        text="Domestic travel per diem is $75 per day; meals are reimbursed with receipts over $25.",
        meta={"tenant": "acme", "kind": "policy", "lang": "en"},
        vector=(0.1, 0.9, 0.0),
    ),
    Chunk(
        chunk_id="chk_4304720e8484b69ae205d9ef",
        doc_id="doc_36bfeaa08f1cf2c901d93292", index=3,
        section_path="Expenses > Report Review",
        text="Expense reports are reviewed by your manager within 5 business days.",
        meta={"tenant": "acme", "kind": "policy", "lang": "en"},
        vector=(0.15, 0.85, 0.05),
    ),
    Chunk(
        chunk_id="chk_9a4d475298b483deacc23e91",
        doc_id="doc_7b8a6c17630bcb98602b2470", index=0,
        section_path="VPN > Setup",
        text="Install the VPN client, sign in with your SSO account, and pick the nearest region.",
        meta={"tenant": "acme", "kind": "howto", "lang": "en"},
        vector=(0.0, 0.1, 0.9),
    ),
    Chunk(
        chunk_id="chk_ca00a2616e677f7e6fae7c1c",
        doc_id="doc_7b8a6c17630bcb98602b2470", index=1,
        section_path="VPN > Troubleshooting",
        text="If the VPN drops, reconnect; if it keeps failing, flush the DNS cache and retry.",
        meta={"tenant": "acme", "kind": "howto", "lang": "en"},
        vector=(0.05, 0.15, 0.85),
    ),
    Chunk(
        chunk_id="chk_83b7e53871a027452232e7ee",
        doc_id="doc_679493f1c87df8d0a2617bb4", index=0,
        section_path="Billing > October 2026",
        text="Customer asked why the October invoice shows two VPN seat charges.",
        meta={"tenant": "globex", "kind": "ticket", "lang": "en"},
        vector=(0.2, 0.2, 0.8),
    ),
    Chunk(
        chunk_id="chk_409185f79a2ec13bc441ef67",
        doc_id="doc_679493f1c87df8d0a2617bb4", index=1,
        section_path="Billing > October 2026",
        text="Duplicate seat charge traced to a provisioning race; refund issued.",
        meta={"tenant": "globex", "kind": "ticket", "lang": "en"},
        vector=(0.25, 0.15, 0.75),
    ),
    Chunk(
        chunk_id="chk_7abd249642d32ee4707c6a39",
        doc_id="doc_0f15c94a611e3aae16d392a9", index=0,
        section_path="MSA > 2025 Terms",
        text="Master service agreement: payment terms net-30, liability cap 12 months of fees.",
        meta={"tenant": "initech", "kind": "contract", "lang": "en"},
        vector=(0.0, 0.2, 0.1),
    ),
    Chunk(
        chunk_id="chk_200891ae5d7f44af83d5a5fa",
        doc_id="doc_0f15c94a611e3aae16d392a9", index=1,
        section_path="MSA > 2025 Terms",
        text="Renewal notice must be given 60 days before the term ends or it auto-renews.",
        meta={"tenant": "initech", "kind": "contract", "lang": "en"},
        vector=(0.05, 0.25, 0.05),
    ),
]

# A question vector in the same toy space: "how much vacation do I get?"
QUERY_VACATION = (0.95, 0.05, 0.0)
QUERY_VPN = (0.0, 0.05, 0.95)
QUERY_BILLING = (0.2, 0.1, 0.85)

Part 4: pgvector — vectors inside Postgres#

pgvector is an open-source Postgres extension (PostgreSQL licence, Postgres 13+, latest release v0.8.7 as of November 2026) that adds a vector type plus distance operators and two index types. Its pitch is the pitch of this whole lesson in miniature: your vectors live in the same ACID database as everything else — same backups, same transactions, same JOINs, same row-level security.

4.1 Setup: extension and table#

sql
-- once per database
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE handbook_chunks (
    id          text PRIMARY KEY,
    doc_id      text NOT NULL,
    section     text NOT NULL,
    content     text NOT NULL,
    tenant      text NOT NULL,
    kind        text NOT NULL,
    lang        text NOT NULL,
    embedding   vector(3) NOT NULL,      -- real models: 768/1024/1536/... dims
    created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX handbook_chunks_tenant_idx ON handbook_chunks (tenant);

Insert with ordinary SQL — vectors are just text literals:

sql
INSERT INTO handbook_chunks (id, doc_id, section, content, tenant, kind, lang, embedding)
VALUES
  ('chk_2e1f324932df6bacc8135ba2', 'doc_36bfeaa08f1cf2c901d93292', 'Leave > Vacation',
   'Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.',
   'acme', 'policy', 'en', '[0.9, 0.1, 0.0]'),
  ('chk_b17014422e53553a0a9f4500', 'doc_36bfeaa08f1cf2c901d93292', 'Leave > Sick Leave',
   'Sick leave is separate from vacation: 10 days per year, no accrual cap.',
   'acme', 'policy', 'en', '[0.85, 0.15, 0.05]'),
  ('chk_4068dfbbce40432fbd9be309', 'doc_36bfeaa08f1cf2c901d93292', 'Expenses > Per Diem',
   'Domestic travel per diem is $75 per day; meals are reimbursed with receipts over $25.',
   'acme', 'policy', 'en', '[0.1, 0.9, 0.0]');

4.2 Distance operators — the pgvector cheat sheet#

Operator Distance Notes
<-> L2 (Euclidean) works on vector, halfvec, sparsevec
<#> negative inner product Postgres only scans ASC, so it returns the negation — multiply by -1 for the real IP
<=> cosine distance 1 - cosine_similarity; use 1 - (a <=> b) for similarity
<+> L1 (Manhattan)
<~> Hamming bit vectors only
<%> Jaccard bit vectors only

Which operator matches your model? The rule from 02.3, 4.5 and 06.3: cosine distance for normalized embeddings (most embedding APIs return unit-length vectors), L2 for un-normalized, inner product only when the model was trained for it. The index operator class must match the query operator — an index on vector_ip_ops does nothing for a <=> query.

4.3 Exact vs approximate: what an index changes#

Without an index, ORDER BY embedding <-> query LIMIT k is an exact scan — perfect recall, O(N) per query. With an ANN index, Postgres walks the approximate structure and you get nearly the nearest neighbours, much faster. Results can change after you add the index — that's expected, not a bug.

sql
-- HNSW: better recall/speed trade-off, no training step, more memory, slower build
CREATE INDEX handbook_chunks_embedding_hnsw
    ON handbook_chunks USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

-- IVFFlat: faster build, less memory, needs data present first (it trains k-means lists)
CREATE INDEX handbook_chunks_embedding_ivf
    ON handbook_chunks USING ivfflat (embedding vector_cosine_ops)
    WITH (lists = 100);

HNSW knobs (defaults in parentheses): m (16) — graph connectivity per layer; ef_construction (64) — build-time candidate list. Query-time: hnsw.ef_search (40) — the recall knob, set per session or per transaction:

sql
SET hnsw.ef_search = 100;          -- session-wide
-- or inside a transaction for one query:
BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT ...;
COMMIT;

IVFFlat knobs: lists at build time (start with rows/1000 up to ~1M rows, sqrt(rows) beyond), ivfflat.probes at query time (default 1; start around sqrt(lists)). Tuning methodology is 06.4's subject; the operational point here is that these are the same knobs every store exposes under different names (ef_search, hnsw_ef, ef).

4.4 The query, with metadata filtering#

sql
SELECT id, section, content,
       1 - (embedding <=> :query_vec) AS cosine_similarity
FROM handbook_chunks
WHERE tenant = :tenant_id
  AND kind = 'policy'
ORDER BY embedding <=> :query_vec
LIMIT 5;
sql
-- 1) Iterative index scans: keep scanning until enough rows survive the filter
SET hnsw.iterative_scan = strict_order;    -- or relaxed_order (better recall, slight reordering)
SET hnsw.max_scan_tuples = 20000;          -- cap the extra work (default 20,000)
-- ivfflat equivalent: SET ivfflat.iterative_scan = relaxed_order; SET ivfflat.max_probes = 100;

-- 2) Partial or partitioned indexes when the filter is structural (tenant, date)
CREATE INDEX handbook_chunks_acme_hnsw
    ON handbook_chunks USING hnsw (embedding vector_cosine_ops)
    WHERE tenant = 'acme';

The deep version of this problem — pre-filter vs post-filter vs in-graph, selectivity thresholds, ACL filters — is lesson 06.6. For now, internalize: on pgvector, a selective WHERE can silently shrink your LIMIT.

4.5 Verify the index is actually used#

sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM handbook_chunks
ORDER BY embedding <=> '[0.95, 0.05, 0.0]' LIMIT 5;
Example output · illustrative6 lines
 Limit  (cost=... rows=5) (actual time=0.42..0.45 rows=5 loops=1)
   ->  Index Scan using handbook_chunks_embedding_hnsw on handbook_chunks
         Order By: (embedding <=> '[0.95,0.05,0]'::vector)
         Index Searches: 1
 Planning Time: 0.8 ms
 Execution Time: 0.6 ms

If you see Seq Scan on a large table, the index isn't being picked — usually because the operator class doesn't match the distance operator, the column type differs (vector vs halfvec), or the planner estimates the table is small enough that a seq scan wins (which is correct for tiny tables).

4.6 From Python: psycopg + pgvector-python#

The pgvector Python package (0.5.1, MIT) registers the type adapters so vector columns round-trip as pgvector.Vector objects (or numpy arrays — a plain list is not adapted).

python
# pgvector_store.py
"""A minimal pgvector store: schema setup, upsert, filtered KNN, delete."""
import os
from collections.abc import Sequence

import psycopg
import pgvector.psycopg
from dotenv import load_dotenv
from pgvector import Vector

from corpus import CHUNKS, Chunk

load_dotenv()
DATABASE_URL = os.environ["DATABASE_URL"]

# psycopg3 uses server-side binding: parameters are only legal in
# SELECT/DML, never in DDL or SET. The dimension is therefore interpolated
# into the DDL string after validation — it is an int, not user text.
DDL_TEMPLATE = """
CREATE TABLE IF NOT EXISTS handbook_chunks (
    id         text PRIMARY KEY,
    doc_id     text NOT NULL,
    section    text NOT NULL,
    content    text NOT NULL,
    tenant     text NOT NULL,
    kind       text NOT NULL,
    lang       text NOT NULL,
    embedding  vector({dim}) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
"""


def connect() -> psycopg.Connection:
    conn = psycopg.connect(DATABASE_URL, autocommit=True)
    conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
    pgvector.psycopg.register_vector(conn)
    return conn


def ensure_schema(conn: psycopg.Connection, dim: int = 3) -> None:
    dim = int(dim)
    if dim < 1:
        raise ValueError("dim must be a positive integer")
    conn.execute(DDL_TEMPLATE.format(dim=dim))
    # HNSW on cosine distance; one index per distance function you query with.
    # Note: CREATE TABLE IF NOT EXISTS will NOT alter an existing table —
    # if the dimension changes (new embedding model), use a new table or
    # ALTER COLUMN ... TYPE vector(new_dim) and rebuild the index.
    conn.execute(
        """CREATE INDEX IF NOT EXISTS handbook_chunks_embedding_hnsw
           ON handbook_chunks USING hnsw (embedding vector_cosine_ops)"""
    )


def upsert_chunks(conn: psycopg.Connection, chunks: Sequence[Chunk]) -> None:
    """Idempotent write: re-running inserts the same ids as updates."""
    with conn.transaction():
        for c in chunks:
            conn.execute(
                """INSERT INTO handbook_chunks
                       (id, doc_id, section, content, tenant, kind, lang, embedding)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                   ON CONFLICT (id) DO UPDATE SET
                       content = EXCLUDED.content,
                       embedding = EXCLUDED.embedding,
                       tenant = EXCLUDED.tenant,
                       kind = EXCLUDED.kind,
                       lang = EXCLUDED.lang""",
                (c.chunk_id, c.doc_id, c.section_path, c.text,
                 c.meta["tenant"], c.meta["kind"], c.meta["lang"],
                 Vector(list(c.vector))),
            )


def search(conn: psycopg.Connection, query_vec: Sequence[float],
           *, top_k: int = 5, tenant: str | None = None,
           ef_search: int | None = None) -> list[dict]:
    """KNN with optional tenant filter. ef_search is set transaction-locally
    so one slow-recall query doesn't change the session for everyone."""
    sql = """
        SELECT id, section, content,
               1 - (embedding <=> %s) AS similarity
        FROM handbook_chunks
        WHERE (%s::text IS NULL OR tenant = %s)
        ORDER BY embedding <=> %s
        LIMIT %s
    """
    # register_vector adapts pgvector.Vector (and numpy arrays) — a plain
    # list would be sent as a Postgres array literal, not a vector literal.
    qvec = Vector(list(query_vec))
    params = [qvec, tenant, tenant, qvec, top_k]
    if ef_search is not None:
        with conn.transaction():
            # SET doesn't accept bind parameters; set_config(..., is_local)
            # is the transaction-local equivalent of SET LOCAL.
            conn.execute(
                "SELECT set_config('hnsw.ef_search', %s, true)",
                (str(ef_search),),
            )
            rows = conn.execute(sql, params).fetchall()
    else:
        rows = conn.execute(sql, params).fetchall()
    return [{"id": r[0], "section": r[1], "content": r[2], "similarity": r[3]}
            for r in rows]


def delete_chunks(conn: psycopg.Connection, ids: Sequence[str]) -> None:
    conn.execute("DELETE FROM handbook_chunks WHERE id = ANY(%s)", (list(ids),))


if __name__ == "__main__":
    from corpus import QUERY_VACATION

    with connect() as conn:
        ensure_schema(conn)
        upsert_chunks(conn, CHUNKS)
        for hit in search(conn, QUERY_VACATION, tenant="acme", ef_search=100):
            print(f"{hit['similarity']:.3f}  {hit['id']}  {hit['content'][:60]}")
Example output · illustrative2 lines
0.998  chk_2e1f324932df6bacc8135ba2  Full-time employees accrue 1.5 days of paid vacation...
0.991  chk_b17014422e53553a0a9f4500  Sick leave is separate from vacation: 10 days per year...

4.7 Deletes, updates and maintenance#

Deletes are ordinary DELETEs — but remember that an ANN index doesn't remove vectors instantly in the way a B-tree does; dead tuples are cleaned by Postgres's normal VACUUM. For heavy delete/rewrite workloads, plan VACUUM/VACUUM ANALYZE into maintenance (autovacuum usually suffices). The pgvector README's maintenance note is narrower than the folklore: it warns that vacuuming HNSW indexes is slow and recommends REINDEX INDEX CONCURRENTLY before VACUUM to speed the vacuum up. As engineering advice on top of that: after large churn (bulk deletes or re-embedding), periodically rebuilding the HNSW index is also a reasonable way to shed graph entries that point at dead tuples — measure recall before and after (06.10) rather than rebuilding on a schedule you can't justify. Link forward: index lifecycle and reindex operations get a full treatment in lesson 06.4 for index internals and Module 05's ingestion lessons for the pipeline side.

4.8 Storage dtypes and quantized indexes#

sql
-- halfvec: half the storage, up to 4,000 dims; cast at query time or store as halfvec
CREATE TABLE handbook_chunks_half (
    id text PRIMARY KEY,
    embedding halfvec(3) NOT NULL
);
-- index the cast so the HNSW graph works on halfvec distances
CREATE INDEX ON handbook_chunks_half
    USING hnsw ((embedding::halfvec(3)) halfvec_cosine_ops);

-- binary quantization as an expression index: small index, rescore with real vectors
CREATE INDEX handbook_chunks_bq
    ON handbook_chunks
    USING hnsw ((binary_quantize(embedding)::bit(3)) bit_hamming_ops);

-- the two-stage query: coarse Hamming candidates, then exact cosine rescore
SELECT * FROM (
    SELECT id, embedding FROM handbook_chunks
    ORDER BY binary_quantize(embedding)::bit(3) <~> binary_quantize('[0.95,0.05,0.0]'::vector)
    LIMIT 20
) candidates
ORDER BY embedding <=> '[0.95,0.05,0.0]'::vector
LIMIT 5;

binary_quantize turns each float into its sign bit; bit_hamming_ops counts differing bits. It's the cheapest possible index — and the reason you keep the original vector column around for rescoring. Quantization trade-offs are 06.4's subject; the operational point is that pgvector gives you the storage/index dtype ladder without leaving SQL.

4.9 When pgvector is the right answer — and when it isn't#

Right answer when: you already run Postgres; the corpus is in the low-millions of vectors per node; you want transactions, joins, RLS and one backup story; your filtering is SQL-shaped. Neon, Supabase, RDS/Aurora, Cloud SQL and most managed Postgres offer pgvector as an extension — check your provider's docs for the supported version.

Not the answer when: you need features Postgres doesn't have — native sparse-vector hybrid search, multivector/MaxSim, per-tenant shard isolation at thousands of tenants, or billion-scale sharding. Those point to the dedicated engines in Part 2. If the only thing outgrowing pgvector is HNSW's RAM appetite and you want to stay in Postgres, the add-on pgvectorscale (a disk-based StreamingDiskANN index plus Statistical Binary Quantization) is the intermediate step — 06.4, 7.7; check that your managed-Postgres host allows it.

Pros / Cons / Choose it when / Avoid it when

  • Pros: vectors, metadata and business data in one ACID database; full SQL filters, joins and row-level security; one backup, replication and monitoring story; HNSW and IVFFlat plus halfvec/bit quantization; available on nearly every managed Postgres.
  • Cons: HNSW is memory-hungry and builds are slow on big tables; filters apply after the ANN scan unless iterative scan is on; no native multivector or sparse-hybrid engine; vector queries compete with your OLTP workload for the same CPU and RAM.
  • Choose it when: you already run Postgres, the corpus is in the low millions of vectors per node, and you want transactional consistency between chunks and the rest of your data.
  • Avoid it when: vectors would dominate a shared production database, you need billion-scale sharding, per-tenant shard isolation at thousands of tenants, or native hybrid and multivector search.

Part 5: Qdrant — a dedicated vector database#

Qdrant (Apache-2.0; qdrant-client 1.20.0 as of November 2026) is a Rust vector database with a first-class filtering/payload model, named vectors, sparse vectors and snapshots. It runs as a single server (docker run -p 6333:6333 -p 6334:6334 qdrant/qdrant — REST on 6333, gRPC on 6334, dashboard at /dashboard), as a managed cloud, or embedded in your process via local mode — which is why it's the dedicated-DB path this lesson teaches.

5.1 Concepts: collection, point, payload, vector#

  • A collection is a namespace of points. All points share the same vector configuration (size + distance), or several named vectors each with their own.
  • A point is an ID + one or more vectors + an optional payload (arbitrary JSON metadata).
  • Distance is chosen at collection creation: COSINE, DOT, EUCLID, MANHATTAN. Cosine is implemented as dot-product over auto-normalized vectors — Qdrant normalizes on upload, so you don't.
  • Payload indexes are separate, optional indexes on payload fields you filter by — the difference between "filter works" and "filter is fast" (deep dive in 06.6).

5.2 Local mode vs server mode — same code#

python
# qdrant_store.py
"""Qdrant store: local mode for dev/tests, server mode for real deployments."""
import os
from collections.abc import Sequence

from dotenv import load_dotenv
from qdrant_client import QdrantClient, models

from corpus import CHUNKS, Chunk

load_dotenv()


def make_client() -> QdrantClient:
    """Local mode needs no server; server mode is one env var away."""
    url = os.environ.get("QDRANT_URL")
    if url:
        return QdrantClient(url=url, api_key=os.environ.get("QDRANT_API_KEY"))
    return QdrantClient(":memory:")          # or QdrantClient(path="./qdrant_db")


def ensure_collection(client: QdrantClient, name: str = "handbook_chunks",
                      dim: int = 3) -> None:
    names = [c.name for c in client.get_collections().collections]
    if name in names:
        return
    client.create_collection(
        collection_name=name,
        vectors_config=models.VectorParams(size=dim, distance=models.Distance.COSINE),
    )
    # Index the field we filter on most; is_tenant marks it for tenant-aware placement
    client.create_payload_index(
        collection_name=name,
        field_name="tenant",
        field_schema=models.KeywordIndexParams(
            type=models.KeywordIndexType.KEYWORD, is_tenant=True
        ),
    )


def upsert_chunks(client: QdrantClient, chunks: Sequence[Chunk],
                  collection: str = "handbook_chunks") -> None:
    points = [
        models.PointStruct(
            id=c.chunk_id if _is_uuid(c.chunk_id) else _stable_id(c.chunk_id),
            vector=list(c.vector),
            payload={
                # chunk_id keeps the human-readable id recoverable from a hit;
                # the point id itself is the derived UUID.
                "chunk_id": c.chunk_id,
                "doc_id": c.doc_id, "section_path": c.section_path,
                "text": c.text, **c.meta,
            },
        )
        for c in chunks
    ]
    client.upsert(collection_name=collection, points=points, wait=True)


def _is_uuid(s: str) -> bool:
    import uuid
    try:
        uuid.UUID(s)
        return True
    except ValueError:
        return False


def _stable_id(text: str) -> str:
    """Qdrant point ids are unsigned ints or UUIDs; derive a stable UUID5
    from the chunk id so re-ingestion is idempotent."""
    import uuid
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"chunk:{text}"))


def search(client: QdrantClient, query_vec: Sequence[float], *, top_k: int = 5,
           tenant: str | None = None, collection: str = "handbook_chunks",
           hnsw_ef: int | None = None) -> list[dict]:
    flt = None
    if tenant is not None:
        flt = models.Filter(must=[
            models.FieldCondition(key="tenant", match=models.MatchValue(value=tenant))
        ])
    params = models.SearchParams(hnsw_ef=hnsw_ef) if hnsw_ef else None
    hits = client.query_points(
        collection_name=collection,
        query=list(query_vec),
        query_filter=flt,
        search_params=params,
        with_payload=True,
        limit=top_k,
    ).points
    return [{"id": str(h.id), "chunk_id": h.payload.get("chunk_id"),
             "score": h.score,
             "text": h.payload.get("text"), "section": h.payload.get("section_path")}
            for h in hits]


def delete_chunks(client: QdrantClient, chunk_ids: Sequence[str],
                  collection: str = "handbook_chunks") -> None:
    ids = [i if _is_uuid(i) else _stable_id(i) for i in chunk_ids]
    client.delete(collection_name=collection,
                  points_selector=models.PointIdsList(points=ids), wait=True)


if __name__ == "__main__":
    from corpus import QUERY_VACATION

    client = make_client()
    ensure_collection(client)
    upsert_chunks(client, CHUNKS)
    for hit in search(client, QUERY_VACATION, tenant="acme"):
        print(f"{hit['score']:.3f}  {hit['chunk_id']}  {hit['text'][:60]}")
Example output · illustrative2 lines
0.998  chk_2e1f324932df6bacc8135ba2  Full-time employees accrue 1.5 days of paid vacation...
0.991  chk_b17014422e53553a0a9f4500  Sick leave is separate from vacation: 10 days per year...

5.3 The knobs that matter on day one#

Knob Where What it does
hnsw_ef SearchParams(hnsw_ef=...) per query HNSW candidate-list size — the recall/latency knob (default is server-side; raise for recall)
exact=True SearchParams(exact=True) Bypass ANN, full scan — ground truth for recall tests (06.10)
quantization collection config / SearchParams scalar/product/binary/TurboQuant rescore trade-offs
with_vectors / with_payload query args don't pay to return vectors you won't use
wait=True write args synchronous durability acknowledgement
scroll / limit+offset client.scroll iterate all points for export/backfill

5.4 Named vectors, sparse vectors, snapshots#

python
# Multiple vectors per point: a "title" vector and a "body" vector, each
# with its own size/distance — useful when title and body want different models.
client.create_collection(
    collection_name="multi",
    vectors_config={
        "title": models.VectorParams(size=3, distance=models.Distance.COSINE),
        "body":  models.VectorParams(size=3, distance=models.Distance.COSINE),
    },
)
# then query a specific one: client.query_points(..., using="body")

# Snapshots: point-in-time collection backups, restorable later.
snap = client.create_snapshot(collection_name="handbook_chunks")
# client.list_snapshots(collection_name="handbook_chunks")
# client.recover_snapshot(collection_name="handbook_chunks", location="snapshots/...")

Sparse vectors (learned-sparse / SPLADE-style, {indices: [...], values: [...]}) and multivectors (ColBERT-style MaxSim via MultiVectorConfig) are first-class in Qdrant — relevant to 06.7 and 06.9. Qdrant also offers quantization at four levels — TurboQuant (4–32×), scalar (4×), binary (≤32×), product (≤64×) — configured per collection; details in its docs and 06.4.

5.5 Async client#

AsyncQdrantClient mirrors the sync API with await on every call — use it when embedding+search runs inside an async web app (link 03.9 for the concurrency mechanics). Same methods, same models; the only change is async/await and that you must await client.close().

5.6 When Qdrant is the right answer, and when it isn't#

  • Pros: a typed filter DSL with payload indexes and tenant-aware shards; named, sparse and multi vectors with fusion in one Query API; quantization options; the same client from :memory: to a distributed cluster; Apache-2.0 with a managed cloud when you want one.
  • Cons: another service to run, upgrade, back up and secure (self-hosted starts with no auth); more concepts than Chroma (collections, payload indexes, named vectors); it holds vectors and payload for search, not your source of truth; local mode is not a replacement for a server.
  • Choose it when: vector search is a core workload, filtering, multi-tenancy or hybrid retrieval matter, and you want to self-host or use a managed cloud without leaving an open-source engine.
  • Avoid it when: your corpus is small and already in Postgres (pgvector is simpler), you have no appetite for running a service and prefer an embedded store, or you need joins and transactions across vectors and business data.

Part 6: Chroma — the embedded option#

Chroma (Apache-2.0; chromadb 1.5.9 as of November 2026) is the "batteries-included" embedded database: it runs in your process (chromadb.Client() — ephemeral, in-memory; chromadb.PersistentClient(path=...) — survives restarts), as a client-server (chromadb.HttpClient / chroma run), or as Chroma Cloud (chromadb.CloudClient). Its model is documents + metadata + embeddings, closer to a document store than to Qdrant's points-and-payload.

6.1 Collections and embedding functions#

python
import chromadb

# Ephemeral: everything in RAM, gone when the process exits — perfect for tests.
client = chromadb.Client()
# Persistent: files under ./chroma_db, loaded on start.
# client = chromadb.PersistentClient(path="./chroma_db")

collection = client.get_or_create_collection(
    name="handbook-chunks",
    configuration={
        "hnsw": {
            "space": "cosine",          # l2 (squared L2), cosine, or ip
            "ef_construction": 200,     # build-time recall (default 100)
            # ef_search is a query-time param, changeable via collection.modify
        }
    },
)

6.2 Adding and querying#

python
# chroma_store.py
"""Chroma store: ephemeral or persistent client, upsert, filtered query."""
import chromadb
from corpus import CHUNKS


def get_collection(client=None, name: str = "handbook-chunks"):
    client = client or chromadb.Client()
    return client.get_or_create_collection(
        name=name,
        configuration={"hnsw": {"space": "cosine"}},
        embedding_function=None,       # we supply embeddings; Chroma won't embed
    )


def upsert_chunks(collection, chunks=CHUNKS) -> None:
    collection.upsert(
        ids=[c.chunk_id for c in chunks],
        documents=[c.text for c in chunks],
        embeddings=[list(c.vector) for c in chunks],
        metadatas=[dict(c.meta, doc_id=c.doc_id, section_path=c.section_path)
                   for c in chunks],
    )


def search(collection, query_vec, *, top_k: int = 5, tenant: str | None = None):
    where = {"tenant": tenant} if tenant else None
    res = collection.query(
        query_embeddings=[list(query_vec)],
        n_results=top_k,
        where=where,
        include=["documents", "metadatas", "distances"],
    )
    # Results are column-major: one list per query, fields parallel to ids.
    return [
        {"id": rid, "distance": dist,
         "similarity": 1.0 - dist,          # cosine distance -> similarity
         "text": doc, "metadata": meta}
        for rid, dist, doc, meta in zip(
            res["ids"][0], res["distances"][0],
            res["documents"][0], res["metadatas"][0],
        )
    ]
Example output · illustrative2 lines
0.998  chk_2e1f324932df6bacc8135ba2  Full-time employees accrue 1.5 days of paid vacation...
0.991  chk_b17014422e53553a0a9f4500  Sick leave is separate from vacation: 10 days per year...

6.3 The where filter language#

Chroma's metadata filter is a JSON-ish dict — deliberately small:

python
# equality / ranges / sets / logic
collection.query(query_embeddings=[q], where={"tenant": "acme"})
collection.query(query_embeddings=[q], where={"page": {"$gte": 5, "$lte": 10}})
collection.query(query_embeddings=[q], where={"kind": {"$in": ["policy", "howto"]}})
collection.query(query_embeddings=[q], where={
    "$and": [{"tenant": "acme"}, {"kind": {"$ne": "ticket"}}]
})
collection.query(query_embeddings=[q], where={
    "$or": [{"lang": "en"}, {"lang": "es"}]
})
# full-text side: where_document matches against the stored document text
collection.query(query_embeddings=[q], where_document={"$contains": "vacation"})

Operators: $eq (or a bare value), $ne, $gt, $gte, $lt, $lte, $in, $nin, $and, $or, plus $contains / $not_contains for array-valued metadata (the metadata-filtering docs page, November 2026, documents $eq, $gt, $gte, $lte, $and, $or, $in, $nin and the array operators; a $not operator is not documented, so don't rely on one). Metadata values can be string/int/float/bool or same-type arrays (no empty or nested arrays). This is intentionally less expressive than Postgres WHERE or Qdrant's Filter — which is exactly why 06.6 exists.

6.4 What Chroma is and isn't, honestly#

  • Is: a friendly embedded store with a document-centric API, good for prototypes, single-node apps, tests, and "I want vector search without running a server". PersistentClient gives you a real on-disk DB.
  • Isn't: a distributed engine. Chroma Cloud exists (SPANN index, RRF hybrid, sparse vectors, GroupBy) but self-hosted single-node Chroma tops out well below dedicated-engine territory (Qdrant, Pinecone) — treat it as the "start simple" rung, not the scale answer. Telemetry is on by default for some clients; check docs.trychroma.com/docs/overview/oss for the opt-out if that matters to you.
  • API notes: add ignores existing IDs (use upsert for idempotent writes); update requires existing IDs; delete(ids=...); get(ids=..., where=...) retrieves without ranking; collection.modify(...) adjusts query-time index params such as ef_search; collection names are 3–512 chars, lowercase/digit start and end. Query results are column-major — res["ids"][0] is the id list for query 0 — and distances are lower-is-better (it's a distance, not a similarity), which is why the adapter converts to 1 - d for cosine.

6.5 When Chroma is the right answer, and when it isn't#

  • Pros: the friendliest API in the lesson (documents, metadata, embeddings in one call); runs in your process with a real persistent mode; optional embedding functions; client-server and Cloud options when you outgrow the local one.
  • Cons: a deliberately small where grammar; self-hosted is single-node HNSW (no replication, limited tenancy at scale); collection-per-tenant stops scaling past hundreds; a sizable dependency tree for an embedded database.
  • Choose it when: prototypes, notebooks, tests, single-node apps, and teams that want vector search without learning a server or a schema.
  • Avoid it when: you need rich filtering, replicas, high write concurrency or thousands of tenants. Move to pgvector or Qdrant.

Part 7: One interface: the VectorStore protocol#

The whole point of learning three stores is that your application shouldn't care which one it talks to. Define a small protocol — the seam where retrieval meets your code — and write adapters. This is the same instinct as lesson 03.11's provider client: one interface, swappable backends, a fake for tests.

7.1 The record and the protocol#

python
# vector_store.py
"""The VectorStore seam: what retrieval code is allowed to assume.

score semantics: adapters return `similarity` — higher is better — regardless
of the store's native convention (distance vs score). The store owns converting.
"""
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, Protocol


@dataclass(frozen=True)
class VectorRecord:
    id: str
    vector: tuple[float, ...]
    text: str = ""
    metadata: Mapping[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class ScoredRecord:
    record: VectorRecord
    similarity: float          # higher = more similar; cosine in [-1, 1] for cosine stores


class VectorStore(Protocol):
    """Minimal contract every adapter must satisfy. Filters are deliberately
    simple equality/range maps — the full filter language is lesson 06.6's job,
    and each adapter translates what it can."""

    def upsert(self, records: Sequence[VectorRecord]) -> None: ...

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]: ...

    def get(self, record_id: str) -> VectorRecord | None: ...

    def delete(self, record_ids: Sequence[str]) -> None: ...

7.2 The in-memory NumPy store — your test double and your floor#

This is the store you reach for when there is no server: tests, notebooks, tiny corpora, and the baseline every other adapter must beat on correctness. It is exact k-NN by definition, which makes it perfect ground truth for recall tests in 06.10.

python
# numpy_store.py
"""Brute-force cosine k-NN in NumPy. Exact, in-memory, zero dependencies
beyond numpy — the VectorStore implementation you use in tests and for
corpora small enough that exact search is fast enough."""
import numpy as np
from collections.abc import Sequence

from vector_store import ScoredRecord, VectorRecord


def _cosine_similarity(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
    """Cosine similarity of `query` against each row of `matrix`.
    Returns zeros for zero-norm vectors instead of NaN."""
    q = query.astype(np.float32)
    m = matrix.astype(np.float32)
    qn = np.linalg.norm(q)
    mn = np.linalg.norm(m, axis=1)
    denom = np.where(qn * mn == 0, 1.0, qn * mn)   # avoid div-by-zero; result -> 0 anyway
    return (m @ q) / denom


def _same(got: object, want: object) -> bool:
    """Equality that keeps True apart from 1 (Python says True == 1)."""
    return got == want and isinstance(got, bool) == isinstance(want, bool)


def _matches(meta: dict, filters: dict | None) -> bool:
    """Equality + simple range filters: {"tenant": "acme"} or
    {"score": {"$gte": 3}}. Deliberately minimal — see lesson 06.6.
    Strict on purpose, because tenant isolation rides on this function: an empty
    operator dict, an unknown operator or an $in that is not a list raises
    instead of matching everything, and True never equals 1."""
    if not filters:
        return True
    for key, want in filters.items():
        got = meta.get(key)
        if isinstance(want, dict):
            if not want:
                raise ValueError(f"empty filter for {key!r} would match every record")
            for op, v in want.items():
                if op == "$gte":   ok = got is not None and got >= v
                elif op == "$gt":  ok = got is not None and got > v
                elif op == "$lte": ok = got is not None and got <= v
                elif op == "$lt":  ok = got is not None and got < v
                elif op == "$in":
                    if not isinstance(v, (list, tuple, set, frozenset)):
                        # a string here would test "is got a substring of v?"
                        raise ValueError("$in needs a list of values")
                    ok = any(_same(got, x) for x in v)
                elif op == "$ne":  ok = not _same(got, v)
                else:              # never fail open: an unknown operator is an error
                    raise ValueError(f"unsupported filter operator {op!r}")
                if not ok:
                    return False
        elif not _same(got, want):
            return False
    return True


class NumpyVectorStore:
    """Exact cosine k-NN. Good to ~100k vectors on one node; beyond that use
    an ANN store (lesson 06.4 covers the approximate side)."""

    def __init__(self, dim: int | None = None):
        self._dim = dim
        self._records: dict[str, VectorRecord] = {}

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for r in records:
            if self._dim is None:
                self._dim = len(r.vector)
            if len(r.vector) != self._dim:
                raise ValueError(
                    f"dimension mismatch: store is {self._dim}, got {len(r.vector)}")
            self._records[r.id] = r

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: dict | None = None) -> list[ScoredRecord]:
        if self._dim is None:
            return []
        if len(vector) != self._dim:
            raise ValueError(f"query dim {len(vector)} != store dim {self._dim}")
        candidates = [(rid, r) for rid, r in self._records.items()
                      if _matches(r.metadata, filters)]
        if not candidates:
            return []
        ids = [rid for rid, _ in candidates]
        matrix = np.array([r.vector for _, r in candidates], dtype=np.float32)
        sims = _cosine_similarity(np.asarray(vector, dtype=np.float32), matrix)
        # argpartition for top_k, then sort just those — O(N) not O(N log N)
        k = min(top_k, len(ids))
        top = np.argpartition(-sims, k - 1)[:k]
        top = top[np.argsort(-sims[top])]
        return [ScoredRecord(record=candidates[i][1], similarity=float(sims[i]))
                for i in top]

    def get(self, record_id: str) -> VectorRecord | None:
        return self._records.get(record_id)

    def delete(self, record_ids: Sequence[str]) -> None:
        for rid in record_ids:
            self._records.pop(rid, None)

    def __len__(self) -> int:
        return len(self._records)

Run it for real — this is pure local NumPy, no server:

python
# demo_numpy_store.py
import numpy as np
from corpus import CHUNKS, QUERY_VACATION
from numpy_store import NumpyVectorStore
from vector_store import VectorRecord

store = NumpyVectorStore(dim=3)
store.upsert([VectorRecord(id=c.chunk_id, vector=c.vector, text=c.text,
                           metadata=dict(c.meta, doc_id=c.doc_id,
                                         section_path=c.section_path))
              for c in CHUNKS])

print("all tenants:")
for hit in store.query(QUERY_VACATION, top_k=3):
    print(f"  {hit.similarity:.3f}  {hit.record.id}")

print("tenant=acme only:")
for hit in store.query(QUERY_VACATION, top_k=3, filters={"tenant": "acme"}):
    print(f"  {hit.similarity:.3f}  {hit.record.id}")
Output · pure NumPy — deterministic, no server needed8 lines
all tenants:
  0.998  chk_2e1f324932df6bacc8135ba2
  0.991  chk_b17014422e53553a0a9f4500
  0.320  chk_409185f79a2ec13bc441ef67
tenant=acme only:
  0.998  chk_2e1f324932df6bacc8135ba2
  0.991  chk_b17014422e53553a0a9f4500
  0.225  chk_4304720e8484b69ae205d9ef

7.3 Adapters: the same ten chunks, three ways (more in Part 8)#

Each adapter translates VectorRecord ↔ the store's native shape and converts the native score to similarity (higher = better). VectorRecord.metadata carries the full filterable payload (meta fields plus doc_id/section_path). Two conventions to note: the pgvector and Chroma adapters assume the schema/collection already exists (call pgvector_store.ensure_schema / qdrant_store.ensure_collection / chroma_store.get_collection first), and hits are pointer records — VectorRecord.vector comes back empty (()) because a search result doesn't need the vector; fetch it explicitly if you do.

python
# adapters_pgvector.py
"""VectorStore adapter over pgvector (psycopg).

Assumes handbook_chunks exists (pgvector_store.ensure_schema). Returns
pointer records — `vector` is empty on hits and `get` results.
"""
from collections.abc import Mapping, Sequence
from typing import Any

import psycopg
from pgvector import Vector

from vector_store import ScoredRecord, VectorRecord

_META_COLS = ("tenant", "kind", "lang")


class PgVectorStore:
    def __init__(self, conn: psycopg.Connection, table: str = "handbook_chunks"):
        if not table.replace("_", "").isalnum():
            raise ValueError("table name must be a plain identifier")
        self._conn = conn
        self._table = table

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for r in records:
            m = dict(r.metadata)
            self._conn.execute(
                f"""INSERT INTO {self._table}
                    (id, doc_id, section, content, tenant, kind, lang, embedding)
                    VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
                    ON CONFLICT (id) DO UPDATE SET
                        content=EXCLUDED.content, embedding=EXCLUDED.embedding,
                        tenant=EXCLUDED.tenant, kind=EXCLUDED.kind, lang=EXCLUDED.lang""",
                (r.id, m.get("doc_id", ""), m.get("section_path", ""), r.text,
                 m.get("tenant", ""), m.get("kind", ""), m.get("lang", ""),
                 Vector(list(r.vector))),
            )

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        # Minimal filter translation: equality on tenant/kind/lang only. A key this
        # adapter cannot translate (a typo such as "tennant", or "doc_id") must
        # raise: skipping it would run the query with NO tenant filter at all.
        unsupported = set(filters or {}) - set(_META_COLS)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        qvec = Vector(list(vector))
        clauses: list[str] = []
        params: list[Any] = [qvec]                     # similarity expr first
        for col in _META_COLS:
            if filters and col in filters:
                clauses.append(f"{col} = %s")
                params.append(filters[col])
        where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
        params += [qvec, top_k]                        # ORDER BY, then LIMIT
        rows = self._conn.execute(
            f"""SELECT id, content, tenant, kind, lang, section, doc_id,
                       1 - (embedding <=> %s) AS sim
                FROM {self._table} {where}
                ORDER BY embedding <=> %s LIMIT %s""",
            params).fetchall()
        return [ScoredRecord(
            record=self._record(r[0], r[1], r[2], r[3], r[4], r[5], r[6]),
            similarity=float(r[7])) for r in rows]

    def get(self, record_id: str) -> VectorRecord | None:
        row = self._conn.execute(
            f"""SELECT id, content, tenant, kind, lang, section, doc_id
                FROM {self._table} WHERE id=%s""",
            (record_id,)).fetchone()
        if not row:
            return None
        return self._record(*row)

    @staticmethod
    def _record(rid, content, tenant, kind, lang, section, doc_id) -> VectorRecord:
        return VectorRecord(
            id=rid, vector=(), text=content,
            metadata={"tenant": tenant, "kind": kind, "lang": lang,
                      "section_path": section, "doc_id": doc_id})

    def delete(self, record_ids: Sequence[str]) -> None:
        self._conn.execute(f"DELETE FROM {self._table} WHERE id = ANY(%s)",
                           (list(record_ids),))
python
# adapters_qdrant.py
"""VectorStore adapter over Qdrant.

Create the collection first with qdrant_store.ensure_collection(client, dim=...).
Point ids use the same UUID5 derivation as qdrant_store; the payload's
chunk_id preserves the original record id. Returns pointer records.
"""
from collections.abc import Mapping, Sequence
from typing import Any

from qdrant_client import QdrantClient, models

from qdrant_store import _is_uuid, _stable_id
from vector_store import ScoredRecord, VectorRecord


def _point_id(record_id: str) -> str:
    return record_id if _is_uuid(record_id) else _stable_id(record_id)


def _to_filter(filters: Mapping[str, Any] | None) -> models.Filter | None:
    """Equality + range filters -> Qdrant Filter. Deliberately minimal —
    the full filter DSL is lesson 06.6's job."""
    if not filters:
        return None
    conditions = []
    for key, want in filters.items():
        if isinstance(want, dict):
            # Qdrant's Range fields are gt/gte/lt/lte — no `$` prefix, unlike
            # Chroma's `where` grammar which keeps it.
            unsupported = set(want) - {"$gt", "$gte", "$lt", "$lte"}
            if not want or unsupported:   # never silently drop a filter: that widens the search
                raise ValueError(f"unsupported filter operators for {key!r}: {sorted(unsupported)}")
            rng = {op.lstrip("$"): v for op, v in want.items()}
            conditions.append(models.FieldCondition(
                key=key, range=models.Range(**rng)))
        else:
            conditions.append(models.FieldCondition(
                key=key, match=models.MatchValue(value=want)))
    return models.Filter(must=conditions) if conditions else None


def _record_from_payload(payload: dict, fallback_id: str) -> VectorRecord:
    p = payload or {}
    return VectorRecord(
        id=p.get("chunk_id", fallback_id), vector=(),
        text=p.get("text", ""),
        metadata={k: v for k, v in p.items() if k not in ("chunk_id", "text")})


class QdrantVectorStore:
    def __init__(self, client: QdrantClient, collection: str = "handbook_chunks"):
        self._client = client
        self._collection = collection

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        points = [
            models.PointStruct(
                id=_point_id(r.id),
                vector=list(r.vector),
                payload={**dict(r.metadata), "chunk_id": r.id, "text": r.text},
            )
            for r in records
        ]
        self._client.upsert(collection_name=self._collection,
                            points=points, wait=True)

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        hits = self._client.query_points(
            collection_name=self._collection,
            query=list(vector),
            query_filter=_to_filter(filters),
            with_payload=True,
            limit=top_k,
        ).points
        # Qdrant's `score` is already similarity (higher = better) for
        # COSINE/DOT distances — no conversion needed.
        return [ScoredRecord(
            record=_record_from_payload(h.payload, str(h.id)),
            similarity=float(h.score)) for h in hits]

    def get(self, record_id: str) -> VectorRecord | None:
        points = self._client.retrieve(
            collection_name=self._collection,
            ids=[_point_id(record_id)],
            with_payload=True,
        )
        if not points:
            return None
        return _record_from_payload(points[0].payload, record_id)

    def delete(self, record_ids: Sequence[str]) -> None:
        self._client.delete(
            collection_name=self._collection,
            points_selector=models.PointIdsList(
                points=[_point_id(i) for i in record_ids]),
            wait=True)
python
# adapters_chroma.py
"""VectorStore adapter over Chroma.

Takes a Collection created with embedding_function=None (we supply vectors —
see chroma_store.get_collection). Returns pointer records — `vector` is
empty on hits.
"""
from collections.abc import Mapping, Sequence
from typing import Any

from vector_store import ScoredRecord, VectorRecord

_WHERE_OPS = ("$gt", "$gte", "$lt", "$lte", "$in", "$nin", "$ne")


def _to_where(filters: Mapping[str, Any] | None) -> dict | None:
    """Equality + range filters -> Chroma `where` dict. Minimal — the full
    grammar ($and/$or/$not/...) is lesson 06.6's job."""
    if not filters:
        return None
    where = {}
    for key, want in filters.items():
        if isinstance(want, dict):
            unsupported = set(want) - set(_WHERE_OPS)
            if not want or unsupported:   # never silently drop a filter: that widens the search
                raise ValueError(f"unsupported filter operators for {key!r}: {sorted(unsupported)}")
            where[key] = dict(want)
        else:
            where[key] = want
    return where or None


class ChromaVectorStore:
    def __init__(self, collection: Any):
        self._col = collection

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        self._col.upsert(
            ids=[r.id for r in records],
            documents=[r.text for r in records],
            embeddings=[list(r.vector) for r in records],
            metadatas=[dict(r.metadata) for r in records],
        )

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        res = self._col.query(
            query_embeddings=[list(vector)],
            n_results=top_k,
            where=_to_where(filters),
            include=["documents", "metadatas", "distances"],
        )
        # Results are column-major: res["ids"][0] is the hit list for query 0.
        # Chroma returns a distance (lower = better); the contract wants
        # similarity, so cosine converts as 1 - distance.
        return [
            ScoredRecord(
                record=VectorRecord(id=rid, vector=(), text=doc,
                                    metadata=meta or {}),
                similarity=1.0 - float(dist))
            for rid, dist, doc, meta in zip(
                res["ids"][0], res["distances"][0],
                res["documents"][0], res["metadatas"][0])
        ]

    def get(self, record_id: str) -> VectorRecord | None:
        res = self._col.get(ids=[record_id], include=["documents", "metadatas"])
        if not res["ids"]:
            return None
        return VectorRecord(
            id=res["ids"][0], vector=(),
            text=(res["documents"] or [""])[0],
            metadata=(res["metadatas"] or [{}])[0] or {})

    def delete(self, record_ids: Sequence[str]) -> None:
        self._col.delete(ids=list(record_ids))

7.4 Contract tests: one suite, every store#

The payoff of the interface: write the test suite once against VectorStore, run it against NumpyVectorStore in CI (no services), and against real stores when you want integration coverage. Lesson 03.10 owns the general testing machinery; the vector-store-specific version is:

python
# tests/test_vector_store_contract.py
"""Contract test: any VectorStore must pass this."""
import pytest
from corpus import CHUNKS
from vector_store import VectorRecord


def records():
    return [VectorRecord(id=c.chunk_id, vector=c.vector, text=c.text,
                         metadata=dict(c.meta, doc_id=c.doc_id,
                                       section_path=c.section_path))
            for c in CHUNKS]


def test_upsert_query_get_delete(store):           # `store` fixture = any VectorStore
    store.upsert(records())
    hits = store.query((0.95, 0.05, 0.0), top_k=3, filters={"tenant": "acme"})
    assert hits and hits[0].record.id == "chk_2e1f324932df6bacc8135ba2"
    assert all(h.similarity >= h2.similarity for h, h2 in zip(hits, hits[1:]))
    assert store.get("chk_2e1f324932df6bacc8135ba2") is not None
    store.delete(["chk_2e1f324932df6bacc8135ba2"])
    assert store.get("chk_2e1f324932df6bacc8135ba2") is None


def test_a_bad_filter_never_widens_the_search(store):
    """A typo'd key, an empty operator dict or a string `$in` must raise or match
    less than everything. It must never quietly return other tenants' rows."""
    store.upsert(records())
    everything = len(store.query((0.95, 0.05, 0.0), top_k=100))
    for bad in ({"tennant": "acme"}, {"tenant": {}}, {"tenant": {"$in": "acme"}}):
        try:
            hits = store.query((0.95, 0.05, 0.0), top_k=100, filters=bad)
        except ValueError:
            continue
        assert len(hits) < everything, bad

In CI, store is NumpyVectorStore. For integration, parametrize the fixture over PgVectorStore/QdrantVectorStore/ChromaVectorStore (and any Part 8 adapter you adopt) behind a marker so they only run when the service is up. Determinism matters: use fixed vectors (as above), not random ones, or scores won't be reproducible.


Part 8: The other options, end to end#

Reference

Parts 4 to 6 went deep on three stores. This part covers every other store in the Part 2 table, each with the same shape: what it is and its mental model, install and setup, a runnable-looking adapter that implements the VectorStore protocol (create index/collection, upsert with metadata, filtered query, delete), a persistence note, honest pros and cons, Choose it when, Avoid it when, and gotchas.

The NumPy store from 7.2 is the first member of the "library" family; 8.1 adds FAISS and hnswlib, and every other adapter in this part should pass the same contract test as 7.4.

8.1 FAISS and hnswlib: vector libraries#

What they are. FAISS (Meta, MIT) and hnswlib (Apache-2.0) are in-process index libraries, not databases. Mental model: a very fast array that answers "which rows are nearest?" You hand them float matrices; they hand back integer positions or integer ids. Strings, metadata, filters, durability and concurrency control are yours to build. That is why the adapter below keeps a dictionary next to the index. Index internals (flat, HNSW, IVF, PQ) belong to 06.4.

Install

bash
pip install faiss-cpu hnswlib numpy
# GPU builds of FAISS exist (conda-forge, faiss-gpu packages); check the FAISS install docs for your platform

FAISS adapter (exact cosine via inner product on unit-length vectors, with integer ids so deletes work):

python
# adapters_faiss.py
"""VectorStore over FAISS: IndexIDMap2(IndexFlatIP). Cosine = inner product of
unit vectors. Metadata lives in a Python dict beside the index (FAISS stores
none). Persistence: faiss.write_index + a JSON sidecar for metadata."""
import hashlib
import json
from collections.abc import Mapping, Sequence
from typing import Any

import faiss
import numpy as np

from numpy_store import _matches            # the strict filter from 7.2
from vector_store import ScoredRecord, VectorRecord


def _int_id(record_id: str) -> int:
    """FAISS ids are int64: derive a stable 63-bit id from the string id.
    (A collision is astronomically unlikely, but a real system should store
    the int->string map explicitly and check for collisions.)"""
    digest = hashlib.blake2b(record_id.encode(), digest_size=8).digest()
    return int.from_bytes(digest, "big") >> 1


def _unit(v: Sequence[float]) -> np.ndarray:
    a = np.asarray(v, dtype=np.float32)
    n = np.linalg.norm(a)
    return a / n if n else a


class FaissVectorStore:
    def __init__(self, dim: int):
        self._dim = dim
        # IndexIDMap2 = your own int ids + remove_ids/reconstruct support.
        self._index = faiss.IndexIDMap2(faiss.IndexFlatIP(dim))
        self._records: dict[int, VectorRecord] = {}

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        ids = np.array([_int_id(r.id) for r in records], dtype=np.int64)
        old = np.array([i for i in ids.tolist() if i in self._records], dtype=np.int64)
        if old.size:
            self._index.remove_ids(old)               # FAISS has no in-place update
        matrix = np.stack([_unit(r.vector) for r in records])
        self._index.add_with_ids(matrix, ids)
        for i, r in zip(ids.tolist(), records):
            self._records[i] = r

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        params = None
        if filters:
            allowed = np.array([i for i, r in self._records.items()
                                if _matches(dict(r.metadata), dict(filters))],
                               dtype=np.int64)
            if allowed.size == 0:
                return []
            params = faiss.SearchParameters()
            params.sel = faiss.IDSelectorBatch(allowed)   # search only these ids
        scores, ids = self._index.search(_unit(vector)[None, :], top_k, params=params)
        return [ScoredRecord(record=self._records[int(i)], similarity=float(s))
                for s, i in zip(scores[0], ids[0]) if i != -1]

    def get(self, record_id: str) -> VectorRecord | None:
        return self._records.get(_int_id(record_id))

    def delete(self, record_ids: Sequence[str]) -> None:
        ids = np.array([_int_id(i) for i in record_ids if _int_id(i) in self._records],
                       dtype=np.int64)
        if ids.size:
            self._index.remove_ids(ids)
        for i in ids.tolist():
            self._records.pop(i, None)

    # --- persistence: FAISS saves the index only; the metadata is yours ---
    def save(self, path: str) -> None:
        faiss.write_index(self._index, f"{path}.faiss")
        with open(f"{path}.json", "w") as f:
            json.dump({str(i): {"id": r.id, "text": r.text, "vector": list(r.vector),
                                "metadata": dict(r.metadata)}
                       for i, r in self._records.items()}, f)

    @classmethod
    def load(cls, path: str, dim: int) -> "FaissVectorStore":
        store = cls(dim)
        store._index = faiss.read_index(f"{path}.faiss")
        with open(f"{path}.json") as f:
            for i, d in json.load(f).items():
                store._records[int(i)] = VectorRecord(
                    id=d["id"], vector=tuple(d["vector"]), text=d["text"],
                    metadata=d["metadata"])
        return store

Switching to approximate search is a one-line change at construction, with one trade-off:

python
# HNSW graph over inner product (unit vectors). Set efConstruction BEFORE adding data.
hnsw = faiss.IndexHNSWFlat(dim, 32, faiss.METRIC_INNER_PRODUCT)   # M = 32
hnsw.hnsw.efConstruction = 200
hnsw.hnsw.efSearch = 64                                            # query-time recall knob
# Caveat: HNSW indexes in FAISS do not support remove_ids. To delete, rebuild the index
# or use a flat/IVF index; check the FAISS docs for which index types support which operations.

hnswlib is the smaller, HNSW-only sibling: one index class, integer labels, a Python filter callback and an explicit save/load.

python
import hnswlib
import numpy as np

index = hnswlib.Index(space="cosine", dim=3)                # "l2", "ip" and "cosine"
index.init_index(max_elements=10_000, ef_construction=200, M=16,
                 allow_replace_deleted=True)                # lets deleted slots be reused
index.add_items(np.array([c.vector for c in CHUNKS], dtype=np.float32),
                ids=np.arange(len(CHUNKS)), replace_deleted=True)   # upsert: same id overwrites
index.set_ef(64)                                            # query-time recall knob

acme = {i for i, c in enumerate(CHUNKS) if c.meta["tenant"] == "acme"}
labels, distances = index.knn_query(np.array([QUERY_VACATION], dtype=np.float32),
                                    k=3, filter=lambda label: label in acme)
similarities = 1.0 - distances[0]                           # cosine *distance* -> similarity

index.mark_deleted(0)                                       # soft delete: skipped by queries
index.save_index("handbook.hnsw")                           # graph only; metadata is yours
# later: index = hnswlib.Index(space="cosine", dim=3)
#        index.load_index("handbook.hnsw", max_elements=10_000, allow_replace_deleted=True)

Persistence: neither library gives you a database. You serialize the index (faiss.write_index, save_index) and your own metadata, and you handle crashes, concurrent writers and versioning.

Pros

  • Fastest path to a working ANN index; no server, no network hop, tiny dependency surface.
  • FAISS offers the widest index menu (flat, IVF, PQ, HNSW, GPU) and is the reference for 06.4 experiments; hnswlib is a small, well-understood HNSW.
  • Ideal as ground truth (IndexFlat*) for recall tests (06.10).

Cons

  • No metadata, no durability, no CRUD semantics, no auth, no replication: you are writing a database one workaround at a time.
  • Filtering is a callback or ID-selector you build and maintain; selective filters on ANN graphs can return fewer than k hits.
  • Deletes are awkward (FAISS HNSW cannot remove; hnswlib only marks deleted); updates mean rebuilds or id reuse.

Choose it when: a batch job, an offline evaluation, a component inside a larger system, a corpus under ~100k vectors in one process, or a research notebook, and nobody else needs to write to it concurrently.

Avoid it when: several services or users write concurrently, you need per-tenant filtering that must never leak, or you need persistence and backups without building them. At that point you want pgvector, Qdrant or another store from this lesson.

Gotchas

  • Cosine similarity in FAISS means normalize, then use inner product (IndexFlatIP); forgetting to normalize silently gives you dot-product ranking.
  • hnswlib's max_elements is a capacity you must set up front (resize_index grows it) and knn_query with k larger than the number of live elements raises.
  • Index and metadata dictionary must be saved together; a stale sidecar file produces hits whose text does not match the vector.

8.2 sqlite-vec: vectors in a SQLite file#

What it is. sqlite-vec (MIT/Apache-2.0, by Alex Garcia, pre-v1 as of November 2026) is a SQLite extension that adds a vec0 virtual table. Mental model: SQLite, but with a table whose rows you can order by vector distance. It is brute-force KNN (no ANN graph), so it is exact and simple, and it is practical up to a modest number of vectors (tens to low hundreds of thousands, depending on dimension and hardware; measure on your data).

Install and setup

bash
pip install sqlite-vec

The Python sqlite3 module must be built with extension loading enabled (python.org and many Linux builds are; some macOS system Pythons are not). If db.enable_load_extension is missing, use a Python build that supports it (for example one from uv python install).

python
# adapters_sqlite_vec.py
"""VectorStore over sqlite-vec. A vec0 virtual table holds the vectors and
filterable metadata; `+` auxiliary columns hold unindexed payload."""
import json
import sqlite3
from collections.abc import Mapping, Sequence
from typing import Any

import sqlite_vec

from vector_store import ScoredRecord, VectorRecord

_FILTERABLE = ("tenant", "kind")             # declared as metadata/partition columns


class SqliteVecStore:
    def __init__(self, path: str = "handbook.db", dim: int = 3):
        self._db = sqlite3.connect(path)       # a file: persistence is just SQLite
        self._db.enable_load_extension(True)
        sqlite_vec.load(self._db)
        self._db.enable_load_extension(False)
        self._db.execute(f"""
            CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING vec0(
                chunk_id  text primary key,
                tenant    text partition key,
                kind      text,
                embedding float[{int(dim)}] distance_metric=cosine,
                +content  text,
                +meta_json text
            )""")

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        with self._db:                          # one transaction
            for r in records:
                m = dict(r.metadata)
                # vec0 has no ON CONFLICT upsert: delete then insert.
                self._db.execute("DELETE FROM chunks WHERE chunk_id = ?", (r.id,))
                self._db.execute(
                    "INSERT INTO chunks(chunk_id, tenant, kind, embedding, content, meta_json)"
                    " VALUES (?, ?, ?, ?, ?, ?)",
                    (r.id, m.get("tenant", ""), m.get("kind", ""),
                     sqlite_vec.serialize_float32(list(r.vector)), r.text, json.dumps(m)))

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        unsupported = set(filters or {}) - set(_FILTERABLE)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        clauses = [f"AND {k} = ?" for k in (filters or {})]
        sql = ("SELECT chunk_id, distance, content, meta_json FROM chunks "
               "WHERE embedding MATCH ? AND k = ? " + " ".join(clauses) +
               " ORDER BY distance")
        rows = self._db.execute(
            sql, [sqlite_vec.serialize_float32(list(vector)), top_k,
                  *(filters or {}).values()]).fetchall()
        return [ScoredRecord(
            record=VectorRecord(id=r[0], vector=(), text=r[2], metadata=json.loads(r[3])),
            similarity=1.0 - float(r[1]))          # cosine distance -> similarity
            for r in rows]

    def get(self, record_id: str) -> VectorRecord | None:
        row = self._db.execute(
            "SELECT chunk_id, content, meta_json FROM chunks WHERE chunk_id = ?",
            (record_id,)).fetchone()
        return None if not row else VectorRecord(
            id=row[0], vector=(), text=row[1], metadata=json.loads(row[2]))

    def delete(self, record_ids: Sequence[str]) -> None:
        with self._db:
            for rid in record_ids:
                self._db.execute("DELETE FROM chunks WHERE chunk_id = ?", (rid,))

The same thing in plain SQL, which is what you would use from any SQLite client or language:

sql
SELECT chunk_id, distance
FROM chunks
WHERE embedding MATCH :query_vec AND k = 5 AND tenant = 'acme'
ORDER BY distance;

Persistence: the database is a normal SQLite file. Back it up like any SQLite database (the .backup command or VACUUM INTO; use WAL mode if you have concurrent readers).

Pros

  • One file, zero servers, runs anywhere SQLite runs (laptop, mobile, browser via WASM, edge devices).
  • You get transactions and SQL for everything else (joins to your relational tables, FTS5 for keyword search alongside).
  • Exact results, no index tuning, no recall surprises.

Cons

  • Pre-v1: expect API and storage-format changes between releases; pin your own lockfile (the lesson's install commands stay unpinned, your application should not).
  • Brute-force search: query time grows linearly with row count; there is no HNSW/IVF to rescue you at millions of vectors.
  • Single-writer SQLite concurrency, no replication, no auth: one process owns the file.
  • Metadata filtering is limited to the column types and operators the vec0 table supports; check the sqlite-vec docs for current limits before relying on a given operator or text length.

Choose it when: a local-first or edge application, a desktop/CLI tool, a small RAG feature in an app that already uses SQLite, or a prototype where one file you can email is a feature.

Avoid it when: you expect millions of vectors, many concurrent writers, or need an approximate index. Move to pgvector (same SQL mindset, real ANN) or Qdrant.

Gotchas

  • Vector columns are fixed-size (float[N], documented maximum 8,192 dimensions); the dimension is decided at table creation, like everywhere else.
  • Pass vectors as serialized bytes (serialize_float32), not a Python list.
  • INSERT of an existing primary key errors; the adapter deletes first. Wrap both in one transaction so a failure cannot lose the old row.

8.3 DuckDB VSS: vector search for analytical workloads#

What it is. DuckDB is an in-process analytical SQL database. Its vss core extension (MIT, experimental as of November 2026) adds an HNSW index over fixed-size FLOAT[N] array columns plus distance functions (array_distance, array_cosine_distance, array_inner_product). Mental model: a data-science notebook database where "nearest rows" is just another ORDER BY. Its sweet spot is analytical work where the same SQL joins Parquet files, dataframes and embeddings.

Install and setup

bash
pip install duckdb
python
# adapters_duckdb.py
"""VectorStore over DuckDB + the experimental vss HNSW index."""
import json
from collections.abc import Mapping, Sequence
from typing import Any

import duckdb

from vector_store import ScoredRecord, VectorRecord

_FILTERABLE = ("tenant", "kind", "lang")


class DuckDbVectorStore:
    def __init__(self, path: str = ":memory:", dim: int = 3):
        self._dim = int(dim)
        self._con = duckdb.connect(path)
        self._con.execute("INSTALL vss")
        self._con.execute("LOAD vss")
        # Required to build an HNSW index inside a database *file*. Experimental:
        # the index is not covered by write-ahead-log recovery, so a crash mid-write
        # can corrupt it. Keep the source rows exportable so you can rebuild.
        self._con.execute("SET hnsw_enable_experimental_persistence = true")
        self._con.execute(f"""
            CREATE TABLE IF NOT EXISTS chunks (
                id VARCHAR PRIMARY KEY, tenant VARCHAR, kind VARCHAR, lang VARCHAR,
                content VARCHAR, meta_json VARCHAR, embedding FLOAT[{self._dim}])""")
        self._con.execute(
            "CREATE INDEX IF NOT EXISTS chunks_hnsw ON chunks "
            "USING HNSW (embedding) WITH (metric = 'cosine')")

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for r in records:
            m = dict(r.metadata)
            # delete-then-insert avoids relying on ON CONFLICT with an indexed table
            self._con.execute("DELETE FROM chunks WHERE id = ?", [r.id])
            self._con.execute(
                "INSERT INTO chunks VALUES (?, ?, ?, ?, ?, ?, ?)",
                [r.id, m.get("tenant", ""), m.get("kind", ""), m.get("lang", ""),
                 r.text, json.dumps(m), list(r.vector)])

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        unsupported = set(filters or {}) - set(_FILTERABLE)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        where = " AND ".join(f"{k} = ?" for k in (filters or {}))
        # The index is used for ORDER BY <matching distance fn> ... LIMIT k.
        # The WHERE is applied around the index scan: a selective filter can
        # return fewer than top_k rows (the filter-shrinkage failure, Part 14 #4).
        rows = self._con.execute(
            f"""SELECT id, content, meta_json,
                       array_cosine_distance(embedding, ?::FLOAT[{self._dim}]) AS d
                FROM chunks {'WHERE ' + where if where else ''}
                ORDER BY d LIMIT ?""",
            [list(vector), *(filters or {}).values(), top_k]).fetchall()
        return [ScoredRecord(
            record=VectorRecord(id=r[0], vector=(), text=r[1], metadata=json.loads(r[2])),
            similarity=1.0 - float(r[3])) for r in rows]

    def get(self, record_id: str) -> VectorRecord | None:
        row = self._con.execute(
            "SELECT id, content, meta_json FROM chunks WHERE id = ?", [record_id]).fetchone()
        return None if not row else VectorRecord(
            id=row[0], vector=(), text=row[1], metadata=json.loads(row[2]))

    def delete(self, record_ids: Sequence[str]) -> None:
        for rid in record_ids:
            self._con.execute("DELETE FROM chunks WHERE id = ?", [rid])
        # Deleted rows linger in the HNSW graph until the index is compacted:
        self._con.execute("PRAGMA hnsw_compact_index('chunks_hnsw')")

Persistence: table data persists in the .duckdb file as normal. The HNSW index persists only with hnsw_enable_experimental_persistence = true; without it DuckDB refuses to create the index on a file-backed database (an in-memory database always works but vanishes on exit). The safe pattern for anything important: treat the index as rebuildable and keep the vectors in Parquet or the table.

Pros

  • Embeddings, Parquet files, dataframes and SQL aggregates in one engine; exact search by default, HNSW when you add the index.
  • Zero server, one pip install, excellent for offline analysis, evaluation sets and batch jobs.
  • Full SQL means joins and filters are as expressive as the engine, not as a vendor DSL.

Cons

  • The vector extension is experimental; persistence of the index is explicitly flagged as at-risk, and the surface may change.
  • Not a serving database: single-process, no replication, no auth, not built for many concurrent small writes.
  • Index deletes and updates need compaction; filtered ANN queries can shrink results like any scan-then-filter design.

Choose it when: analytical or batch work where embeddings sit next to tabular data (evaluation sets, dedup jobs, data exploration, a notebook that joins vectors to metadata in Parquet).

Avoid it when: an online service must survive crashes with a live index, has concurrent writers, or needs strong tenancy. Use pgvector or Qdrant instead.

Gotchas

  • Vectors must be fixed-size FLOAT[N] arrays (not variable FLOAT[] lists), and the query needs a matching cast (?::FLOAT[3]).
  • The index is only picked for the distance function matching the index metric (array_cosine_distance for 'cosine'); a different function falls back to a scan.
  • Cosine and the other metrics are distances: convert to similarity in the adapter.

8.4 LanceDB: an embedded, columnar vector database#

What it is. LanceDB (Apache-2.0 open-source library; managed Cloud and Enterprise exist) stores data in the Lance columnar format on local disk or object storage (S3, GCS and compatible endpoints). Mental model: a dataframe on disk (think Parquet-like, but random-access and versioned) that also has a vector index. Every write creates a new table version, tables hold vectors alongside any scalar columns (and even images or other binary data), and queries are search(vector).where(sql).

Install and setup

bash
pip install lancedb
python
# adapters_lancedb.py
"""VectorStore over LanceDB (embedded). One Lance table; scalar metadata as columns."""
from collections.abc import Mapping, Sequence
from typing import Any

import lancedb

from vector_store import ScoredRecord, VectorRecord

_COLUMNS = ("tenant", "kind", "lang", "doc_id", "section_path")


def _lit(value: Any) -> str:
    """SQL literal for the `where` string: escape quotes, never interpolate raw input."""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (int, float)):
        return repr(value)
    return "'" + str(value).replace("'", "''") + "'"


class LanceVectorStore:
    def __init__(self, uri: str = "./lancedb_data", table: str = "handbook_chunks"):
        # uri can also be "s3://bucket/path" (credentials via the standard AWS env vars)
        self._db = lancedb.connect(uri)
        self._name = table
        self._tbl = None
        if table in self._db.table_names():
            self._tbl = self._db.open_table(table)

    @staticmethod
    def _row(r: VectorRecord) -> dict:
        m = dict(r.metadata)
        return {"id": r.id, "vector": list(r.vector), "text": r.text,
                **{c: m.get(c, "") for c in _COLUMNS}}

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        rows = [self._row(r) for r in records]
        if self._tbl is None:
            self._tbl = self._db.create_table(self._name, data=rows)   # schema from rows
            return
        (self._tbl.merge_insert("id")                  # match on the id column
             .when_matched_update_all()
             .when_not_matched_insert_all()
             .execute(rows))

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        if self._tbl is None:
            return []
        unsupported = set(filters or {}) - set(_COLUMNS)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        q = self._tbl.search(list(vector)).metric("cosine")
        if filters:
            where = " AND ".join(f"{k} = {_lit(v)}" for k, v in filters.items())
            q = q.where(where, prefilter=True)         # filter first, then search
        rows = q.limit(top_k).to_list()
        return [ScoredRecord(
            record=VectorRecord(
                id=r["id"], vector=(), text=r["text"],
                metadata={c: r[c] for c in _COLUMNS}),
            similarity=1.0 - float(r["_distance"]))    # cosine distance -> similarity
            for r in rows]

    def get(self, record_id: str) -> VectorRecord | None:
        if self._tbl is None:
            return None
        rows = self._tbl.search().where(f"id = {_lit(record_id)}").limit(1).to_list()
        if not rows:
            return None
        r = rows[0]
        return VectorRecord(id=r["id"], vector=(), text=r["text"],
                            metadata={c: r[c] for c in _COLUMNS})

    def delete(self, record_ids: Sequence[str]) -> None:
        if self._tbl is not None and record_ids:
            self._tbl.delete("id IN (" + ", ".join(_lit(i) for i in record_ids) + ")")

Indexes are explicit and optional. Without one, LanceDB does an exact scan (fine for small tables); with enough data you add them:

python
tbl.create_index(metric="cosine")             # vector index; the default type is IVF_PQ
                                              # (needs enough rows to train; see the docs)
tbl.create_scalar_index("tenant")             # speeds up the `where` filter column

Persistence: the table is a directory of Lance files, durable by construction, versioned on every write (you can open older versions for time travel), and relocatable to object storage by changing the URI. Compact old versions periodically (tbl.optimize() in recent releases; check the docs for the current name).

Pros

  • Embedded and durable by default, with a clean upgrade path to object storage.
  • Columnar storage means multimodal data and scalar columns live next to vectors; strong for data-pipeline and lakehouse-style workflows.
  • Real filtering (SQL where), pre-filter option, FTS and hybrid search with reranking in the library.
  • Several index types (IVF_PQ, IVF_HNSW_SQ, IVF_FLAT, IVF_RQ) and a distance metric fixed at index build.

Cons

  • Different mental model from a document DB: schema comes from the first rows, schema changes need add_columns-style operations, and every write makes a version you must eventually clean up.
  • Embedded means no built-in replication or auth; scaling out is the Enterprise product or your own sharding.
  • The API and index menu evolve quickly; code samples age fast.

Choose it when: you want an embedded store that already persists, you are building around Parquet-style data pipelines or multimodal data, or you want to keep vectors in object storage with a library rather than a service.

Avoid it when: you need a multi-writer, networked serving layer with RBAC and replicas out of the box, or you want to run your search through SQL joins with transactional guarantees (pgvector).

Gotchas

  • Build the index with the same metric you query with; the metric is fixed at index build time.
  • where is a SQL string: escape values (the _lit helper above) and validate column names, or you have built an injection hole.
  • Many small appends create many small fragments; batch writes and compact periodically.

8.5 Elasticsearch: kNN inside the search engine you already run#

What it is. Elasticsearch is a distributed search engine (inverted index plus, since 8.x, HNSW vector search through the dense_vector field and the knn search option). Mental model: a JSON document store where one field is a vector and the search request has a knn clause. Its strength is that keyword relevance, filters, aggregations and vector search live in one request, which makes it a natural hybrid-search engine (06.7, 06.8).

Install and setup

bash
pip install elasticsearch
# Local reference only (do not run now): see Elastic's docs for a single-node Docker setup
bash
# .env additions
ELASTICSEARCH_URL=https://localhost:9200
ELASTICSEARCH_API_KEY=...      # an API key with create_index/read/write on the index
python
# adapters_elasticsearch.py
"""VectorStore over Elasticsearch dense_vector + knn search."""
import os
from collections.abc import Mapping, Sequence
from typing import Any

from elasticsearch import Elasticsearch, NotFoundError, helpers

from vector_store import ScoredRecord, VectorRecord

_KEYWORDS = ("tenant", "kind", "lang", "doc_id", "section_path")


class ElasticsearchVectorStore:
    def __init__(self, es: Elasticsearch | None = None,
                 index: str = "handbook-chunks", dim: int = 3):
        self._es = es or Elasticsearch(os.environ["ELASTICSEARCH_URL"],
                                       api_key=os.environ["ELASTICSEARCH_API_KEY"])
        self._index = index
        if not self._es.indices.exists(index=index):
            self._es.indices.create(index=index, mappings={"properties": {
                "text": {"type": "text"},
                "metadata": {"properties": {k: {"type": "keyword"} for k in _KEYWORDS}},
                "embedding": {
                    "type": "dense_vector", "dims": dim,
                    "index": True, "similarity": "cosine",
                    # optional: "index_options": {"type": "hnsw", "m": 16, "ef_construction": 100}
                },
            }})

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        helpers.bulk(self._es, (
            {"_op_type": "index", "_index": self._index, "_id": r.id,   # same _id overwrites
             "_source": {"text": r.text, "metadata": dict(r.metadata),
                         "embedding": list(r.vector)}}
            for r in records), refresh="wait_for")      # visible to search before returning

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        unsupported = set(filters or {}) - set(_KEYWORDS)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        knn = {"field": "embedding", "query_vector": list(vector), "k": top_k,
               "num_candidates": max(50, top_k * 10)}   # per-shard candidate pool: the recall knob
        if filters:
            # a filter *inside* knn is applied while searching (pre-filter), so k hits survive
            knn["filter"] = {"bool": {"filter": [
                {"term": {f"metadata.{k}": v}} for k, v in filters.items()]}}
        resp = self._es.search(index=self._index, knn=knn, size=top_k,
                               source_excludes=["embedding"])
        # With cosine similarity, Elasticsearch returns _score = (1 + cosine) / 2
        return [ScoredRecord(
            record=VectorRecord(id=h["_id"], vector=(), text=h["_source"]["text"],
                                metadata=h["_source"]["metadata"]),
            similarity=2.0 * h["_score"] - 1.0) for h in resp["hits"]["hits"]]

    def get(self, record_id: str) -> VectorRecord | None:
        try:
            d = self._es.get(index=self._index, id=record_id, source_excludes=["embedding"])
        except NotFoundError:
            return None
        return VectorRecord(id=d["_id"], vector=(), text=d["_source"]["text"],
                            metadata=d["_source"]["metadata"])

    def delete(self, record_ids: Sequence[str]) -> None:
        helpers.bulk(self._es, (
            {"_op_type": "delete", "_index": self._index, "_id": i} for i in record_ids),
            refresh="wait_for", raise_on_error=False)    # missing ids are not an error here

Hybrid in one request is where Elasticsearch earns its keep. The query and knn sections combine, or you fuse with the RRF retriever (check the docs for your version's exact syntax and licensing tier for each feature):

json
{
  "knn":   { "field": "embedding", "query_vector": [0.95, 0.05, 0.0], "k": 10, "num_candidates": 100,
             "filter": { "term": { "metadata.tenant": "acme" } } },
  "query": { "match": { "text": "vacation days" } }
}

Persistence: a normal Elasticsearch cluster: shards on disk, replicas, snapshots to a repository (S3, GCS, shared filesystem). Writes are near-real-time: a document is searchable after the next refresh (about 1 second by default), which is why the adapter asks for refresh="wait_for"; do not do that on every write in a bulk-loading job.

Pros

  • Best-in-class text search and hybrid fusion in the same engine; mature filters, aggregations, security and snapshot tooling.
  • HNSW with quantized variants (int8/int4/bbq options) to shrink memory; filters inside knn are applied during the search.
  • If your company already runs it, vector search is a mapping change, not a new system.

Cons

  • Heavy: a JVM cluster to size, patch and pay for; vectors are memory-hungry and index builds are expensive.
  • Near-real-time, not immediately consistent; updates re-index whole documents.
  • Licensing: the official downloads are under Elastic License 2.0 (source also offered under SSPL or AGPLv3, see 2.1), which matters if you want a permissive licence.
  • Query DSL is verbose, and the vector-specific options (index_options types, defaults by version) change between releases.

Choose it when: you already operate Elasticsearch (or Elastic Cloud) for search or logs, or hybrid keyword-plus-vector relevance with rich filtering is the core of the product.

Avoid it when: you have no existing Elastic investment and only need vectors, you need a permissive open-source licence, or you want a small simple footprint. Use pgvector, Qdrant or an embedded store.

Gotchas

  • dims and similarity are fixed at mapping creation. Changing the model means a new index and a reindex.
  • Vectors are excluded from _source in newer versions by default; ask for them explicitly if you need them back, and use source_excludes to avoid paying to return them.
  • num_candidates is per shard; with several shards the effective pool is larger and latency grows with it.

8.6 OpenSearch: the open-source fork, with a k-NN plugin#

What it is. OpenSearch (Apache-2.0, forked from Elasticsearch 7.10; AWS-managed as Amazon OpenSearch Service and Serverless) provides vector search through the k-NN feature and a knn_vector field type. Mental model: the same search-engine-with-a-vector-field idea as Elasticsearch, with an explicit choice of k-NN engine (Lucene, Faiss, NMSLIB) and a knn query clause. The hybrid query plus search pipelines handle score normalization or RRF for hybrid search.

Install and setup

bash
pip install opensearch-py
bash
# .env additions
OPENSEARCH_HOST=localhost
OPENSEARCH_USER=admin
OPENSEARCH_PASSWORD=...        # never hard-code; managed services typically use IAM/SigV4 instead
python
# adapters_opensearch.py
"""VectorStore over OpenSearch k-NN (Lucene engine, HNSW)."""
import os
from collections.abc import Mapping, Sequence
from typing import Any

from opensearchpy import NotFoundError, OpenSearch, helpers

from vector_store import ScoredRecord, VectorRecord

_KEYWORDS = ("tenant", "kind", "lang", "doc_id", "section_path")


class OpenSearchVectorStore:
    def __init__(self, client: OpenSearch | None = None,
                 index: str = "handbook-chunks", dim: int = 3):
        self._os = client or OpenSearch(
            hosts=[{"host": os.environ["OPENSEARCH_HOST"], "port": 9200}],
            http_auth=(os.environ["OPENSEARCH_USER"], os.environ["OPENSEARCH_PASSWORD"]),
            use_ssl=True, verify_certs=True)
        self._index = index
        if not self._os.indices.exists(index=index):
            self._os.indices.create(index=index, body={
                "settings": {"index": {"knn": True}},          # turn on k-NN for this index
                "mappings": {"properties": {
                    "text": {"type": "text"},
                    "metadata": {"properties": {k: {"type": "keyword"} for k in _KEYWORDS}},
                    "embedding": {
                        "type": "knn_vector", "dimension": dim,
                        "method": {"name": "hnsw", "space_type": "cosinesimil",
                                   "engine": "lucene",
                                   "parameters": {"m": 16, "ef_construction": 128}},
                    },
                }},
            })

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        helpers.bulk(self._os, (
            {"_op_type": "index", "_index": self._index, "_id": r.id,
             "_source": {"text": r.text, "metadata": dict(r.metadata),
                         "embedding": list(r.vector)}}
            for r in records), refresh="wait_for")

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        unsupported = set(filters or {}) - set(_KEYWORDS)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        knn: dict[str, Any] = {"vector": list(vector), "k": top_k}
        if filters:
            # filter *inside* the knn clause = efficient filtering (Lucene/Faiss engines)
            knn["filter"] = {"bool": {"filter": [
                {"term": {f"metadata.{k}": v}} for k, v in filters.items()]}}
        resp = self._os.search(index=self._index, body={
            "size": top_k, "_source": {"excludes": ["embedding"]},
            "query": {"knn": {"embedding": knn}}})
        # Lucene-engine cosinesimil scores are (1 + cosine) / 2 in the k-NN docs'
        # score translation; verify the formula for your engine and version.
        return [ScoredRecord(
            record=VectorRecord(id=h["_id"], vector=(), text=h["_source"]["text"],
                                metadata=h["_source"]["metadata"]),
            similarity=2.0 * h["_score"] - 1.0) for h in resp["hits"]["hits"]]

    def get(self, record_id: str) -> VectorRecord | None:
        try:
            d = self._os.get(index=self._index, id=record_id,
                             _source_excludes=["embedding"])
        except NotFoundError:
            return None
        return VectorRecord(id=d["_id"], vector=(), text=d["_source"]["text"],
                            metadata=d["_source"]["metadata"])

    def delete(self, record_ids: Sequence[str]) -> None:
        helpers.bulk(self._os, (
            {"_op_type": "delete", "_index": self._index, "_id": i} for i in record_ids),
            refresh="wait_for", raise_on_error=False)

Persistence: same family as Elasticsearch: shards on disk, replicas, snapshot repositories. Amazon OpenSearch Serverless has vector-search collections where AWS manages capacity. Writes are near-real-time (refresh interval).

Pros

  • Permissive Apache-2.0 licence with an AWS-managed option, so it suits teams that want the search-engine model without Elastic licensing.
  • Choice of engine and method (Lucene, Faiss, NMSLIB; HNSW and IVF in the Faiss engine), exact k-NN via script scoring, and in-query filtering on the Lucene and Faiss engines.
  • Native hybrid query with score normalization or RRF in search pipelines; strong operational tooling and AWS integration.

Cons

  • Same weight as any search cluster: heap, shards, memory for graphs; an expensive thing to run for a small corpus.
  • More knobs than other stores: engine, space_type, method parameters, and which feature works with which engine all matter; copying a tutorial's mapping for a different engine is a common mistake.
  • Near-real-time indexing; mapping changes (dimension, method) require a reindex.

Choose it when: you already run OpenSearch or Amazon OpenSearch Service, you want search-engine hybrid relevance with an open-source licence, or an AWS-native managed search tier is your default.

Avoid it when: you are not already in that ecosystem and just need vector search; the operational surface is larger than pgvector, Qdrant or an embedded store.

Gotchas

  • Set "index.knn": true in the index settings before adding knn_vector fields; without it you get an ordinary field and no ANN index.
  • space_type must match your metric (cosinesimil, l2, innerproduct), and the supported combinations differ per engine; check the k-NN docs for your version.
  • Do not interpret raw scores as cosine values. They are a monotone transform that depends on engine and space type; rely on ordering unless you have verified the formula.

8.7 Redis: vector search over an in-memory data store#

What it is. Redis ships a query engine (RediSearch, built into Redis 8 and available as the Redis Query Engine in Redis Cloud and Redis Stack) that indexes hash or JSON keys and supports VECTOR fields with FLAT, HNSW or SVS-VAMANA indexes. Mental model: a very fast in-memory key-value store that can also run FT.SEARCH over the keys that match a prefix. The index is created once with FT.CREATE; every HSET under that prefix is indexed automatically.

Install and setup

bash
pip install redis numpy
# Local reference only (do not run now): docker run -p 6379:6379 redis:8
bash
# .env additions
REDIS_URL=redis://localhost:6379      # or rediss://:password@host:port for Redis Cloud
python
# adapters_redis.py
"""VectorStore over Redis hashes + an HNSW vector index (FT.CREATE / FT.SEARCH)."""
import json
import os
import re
from collections.abc import Mapping, Sequence
from typing import Any

import numpy as np
import redis
from redis.commands.search.field import TagField, TextField, VectorField
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import Query

from vector_store import ScoredRecord, VectorRecord

_TAGS = ("tenant", "kind", "lang")
_PREFIX = "chunk:"


def _esc(value: str) -> str:
    """Tag values need punctuation escaped in a query string."""
    return re.sub(r"([^\w])", r"\\\1", str(value))


class RedisVectorStore:
    def __init__(self, client: redis.Redis | None = None,
                 index: str = "idx:chunks", dim: int = 3):
        # decode_responses must stay False: vectors are stored as raw bytes
        self._r = client or redis.Redis.from_url(os.environ["REDIS_URL"])
        self._index = index
        try:
            self._r.ft(index).info()                     # exists already?
        except redis.exceptions.ResponseError:
            self._r.ft(index).create_index(
                [TextField("text"),
                 *(TagField(t) for t in _TAGS),
                 VectorField("embedding", "HNSW", {
                     "TYPE": "FLOAT32", "DIM": dim,
                     "DISTANCE_METRIC": "COSINE", "M": 16, "EF_CONSTRUCTION": 200})],
                definition=IndexDefinition(prefix=[_PREFIX], index_type=IndexType.HASH))

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        pipe = self._r.pipeline()
        for r in records:
            m = dict(r.metadata)
            pipe.hset(f"{_PREFIX}{r.id}", mapping={          # HSET overwrites = upsert
                "text": r.text,
                "meta_json": json.dumps(m),
                **{t: str(m.get(t, "")) for t in _TAGS},
                "embedding": np.asarray(r.vector, dtype=np.float32).tobytes()})
        pipe.execute()

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        unsupported = set(filters or {}) - set(_TAGS)
        if unsupported or any(isinstance(v, dict) for v in (filters or {}).values()):
            raise ValueError(f"filters this adapter cannot apply: {sorted(unsupported) or 'operators'}")
        pre = " ".join(f"@{k}:{{{_esc(v)}}}" for k, v in (filters or {}).items()) or "*"
        q = (Query(f"({pre})=>[KNN {int(top_k)} @embedding $vec AS dist]")
             .sort_by("dist")
             .return_fields("text", "meta_json", "dist")
             .dialect(2))
        res = self._r.ft(self._index).search(
            q, query_params={"vec": np.asarray(vector, dtype=np.float32).tobytes()})
        return [ScoredRecord(
            record=VectorRecord(id=d.id.removeprefix(_PREFIX), vector=(), text=d.text,
                                metadata=json.loads(d.meta_json)),
            similarity=1.0 - float(d.dist))               # COSINE returns a distance
            for d in res.docs]

    def get(self, record_id: str) -> VectorRecord | None:
        h = self._r.hgetall(f"{_PREFIX}{record_id}")
        if not h:
            return None
        return VectorRecord(id=record_id, vector=(), text=h[b"text"].decode(),
                            metadata=json.loads(h[b"meta_json"]))

    def delete(self, record_ids: Sequence[str]) -> None:
        if record_ids:
            self._r.delete(*(f"{_PREFIX}{i}" for i in record_ids))

Persistence: Redis is memory-first. Durability comes from RDB snapshots and/or the append-only file (AOF), configured per deployment; managed services add replication and snapshots. The index definition is stored with the data and rebuilds on load. If data loss is unacceptable, make the vectors reproducible from a source of truth.

Pros

  • Very low query latency; sub-millisecond reads are normal for the data already in memory, and the same system serves caches, queues, sessions and vectors.
  • Hybrid filtering with tags, numerics, text and geo in the same query; vector range queries.
  • Multiple index types (FLAT for small sets, HNSW for larger, SVS-VAMANA) and several numeric types including quantized options to save RAM.

Cons

  • Memory-bound: every vector costs RAM, which is the most expensive storage tier (see 10.2).
  • The query language is the RediSearch dialect (FT.SEARCH, KNN ... AS, dialect 2), not a document API; escaping tag values is easy to get wrong.
  • Licensing is mixed (RSALv2, SSPLv1 or AGPLv3 from Redis 8, see 2.1); read it if you embed or resell.
  • Persistence and consistency are tuned for speed first; not where you want your only copy of data.

Choose it when: the application already runs on Redis, you want sub-millisecond semantic caching, session or recommendation features, or a hot small-to-medium vector set next to data you already keep there.

Avoid it when: the corpus is large relative to affordable RAM, you need strong durability guarantees for the vectors themselves, or Redis is not already in your stack.

Gotchas

  • Vector bytes must be little-endian float32 matching DIM exactly; a wrong length makes the document fail to index silently (check FT.INFO hash_indexing_failures).
  • Create the index before or after loading data; either works, but only keys matching the prefix are indexed, so a prefix typo gives an index with zero documents.
  • Do not use decode_responses=True on the client that handles vector bytes.

8.8 Pinecone: the fully managed serverless service#

What it is. Pinecone is a cloud-only managed vector database. There is nothing to deploy: you create an index (dense, serverless), choose a dimension and metric, and call a REST/SDK API. Mental model: a hosted dictionary of id -> (vector, metadata), partitioned into namespaces, billed by storage and operations. Namespaces are the primary multi-tenancy tool: each tenant's data lives in its own namespace and queries do not cross them.

Install and setup

bash
pip install pinecone
bash
# .env additions
PINECONE_API_KEY=...        # from the Pinecone console; keep it out of source control
python
# adapters_pinecone.py
"""VectorStore over Pinecone (classic dense serverless index)."""
import os
import time
from collections.abc import Mapping, Sequence
from typing import Any

from pinecone import Pinecone, ServerlessSpec

from vector_store import ScoredRecord, VectorRecord

_BATCH = 100


def _to_filter(filters: Mapping[str, Any] | None) -> dict | None:
    """Equality and $-operator filters -> Pinecone metadata filter."""
    if not filters:
        return None
    allowed = {"$eq", "$ne", "$gt", "$gte", "$lt", "$lte", "$in", "$nin"}
    out: dict[str, Any] = {}
    for key, want in filters.items():
        if isinstance(want, dict):
            if not want or set(want) - allowed:             # never silently widen
                raise ValueError(f"unsupported filter operators for {key!r}")
            out[key] = dict(want)
        else:
            out[key] = {"$eq": want}
    return out


class PineconeVectorStore:
    def __init__(self, name: str = "handbook-chunks", dim: int = 3,
                 namespace: str = "", pc: Pinecone | None = None):
        self._pc = pc or Pinecone(api_key=os.environ["PINECONE_API_KEY"])
        if not self._pc.has_index(name):
            self._pc.create_index(
                name=name, dimension=dim, metric="cosine",
                spec=ServerlessSpec(cloud="aws", region="us-east-1"))
        while not self._pc.describe_index(name).status["ready"]:   # index builds async
            time.sleep(1)
        self._index = self._pc.Index(name)
        self._ns = namespace       # e.g. one namespace per tenant for hard isolation

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for i in range(0, len(records), _BATCH):
            self._index.upsert(namespace=self._ns, vectors=[
                {"id": r.id, "values": list(r.vector),
                 # metadata is flat scalars; text goes here only because chunks are
                 # small. Per-record metadata is capped (~40 KB): keep big text elsewhere.
                 "metadata": {**dict(r.metadata), "text": r.text}}
                for r in records[i:i + _BATCH]])

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        res = self._index.query(
            namespace=self._ns, vector=list(vector), top_k=top_k,
            filter=_to_filter(filters), include_metadata=True)
        return [ScoredRecord(
            record=VectorRecord(
                id=m.id, vector=(), text=(m.metadata or {}).get("text", ""),
                metadata={k: v for k, v in (m.metadata or {}).items() if k != "text"}),
            similarity=float(m.score))        # cosine index: score is similarity, higher = better
            for m in res.matches]

    def get(self, record_id: str) -> VectorRecord | None:
        res = self._index.fetch(ids=[record_id], namespace=self._ns)
        v = res.vectors.get(record_id)
        if v is None:
            return None
        md = dict(v.metadata or {})
        return VectorRecord(id=record_id, vector=(), text=md.pop("text", ""), metadata=md)

    def delete(self, record_ids: Sequence[str]) -> None:
        self._index.delete(ids=list(record_ids), namespace=self._ns)

Illustrative first-query behaviour: a freshly upserted record can take a moment to become visible (Pinecone indexes are eventually consistent), so a test that upserts then queries immediately may need a short wait or a retry.

Persistence: fully managed. Pinecone owns durability, replication and scaling; you read its backup/collection and retention docs for your plan. There is no self-hosted option, so exportability (fetch/list by namespace into your own store) is your exit strategy (10.4).

Pros

  • Zero infrastructure: no sizing, no patching, no index tuning; scales from a prototype to very large indexes.
  • Namespaces make multi-tenancy simple and fast; metadata filtering is built in.
  • Integrated options (sparse/hybrid, integrated embedding and reranking models) reduce glue code if you choose to use them.

Cons

  • Cloud-only and proprietary: vendor lock-in, data leaves your network, no air-gapped or self-hosted path.
  • Usage-based pricing can surprise you at high read volumes; plan limits (namespaces per index, request rates, metadata size) apply.
  • Less control over the index than a self-managed engine; eventual consistency; the product surface (index types, SDK) changes often.

Choose it when: you want a managed service with minimal ops, tenants map naturally to namespaces, and the team's time is more expensive than the bill.

Avoid it when: you must self-host or keep data in your own VPC/country, you are very cost-sensitive at high QPS, or you want to avoid proprietary dependencies.

Gotchas

  • Dimension and metric are fixed at index creation; a new embedding model means a new index.
  • A query only sees one namespace; the default namespace is not "all namespaces", so a tenant bug is usually a wrong or missing namespace=.
  • Metadata values are flat (string, number, boolean, list of strings); nested JSON is not supported, and large per-record metadata is capped.

8.9 AWS S3 Vectors: vectors as object storage#

What it is. S3 Vectors (generally available since December 2025) adds vector buckets and vector indexes to Amazon S3. Mental model: S3 with a query_vectors call. Vectors and their metadata are stored durably in object storage, queries return approximate nearest neighbours in roughly sub-second latency, and you pay object-storage-style prices for storage plus per-request charges. There is no cluster, no instance sizing and no self-hosted version. For hybrid search AWS pairs it with OpenSearch.

Install and setup

bash
pip install boto3

Credentials come from the standard AWS chain (environment variables, shared config, IAM role), not from code. The IAM principal needs s3vectors:* actions on the bucket and index you use.

bash
# .env additions (or use an IAM role / AWS_PROFILE)
AWS_REGION=us-east-1
AWS_PROFILE=...            # or AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY for local dev only
python
# adapters_s3_vectors.py
"""VectorStore over Amazon S3 Vectors (boto3 'S3 Vectors' client)."""
import os
from collections.abc import Mapping, Sequence
from typing import Any

import boto3

from vector_store import ScoredRecord, VectorRecord

_PUT_BATCH = 100


def _to_filter(filters: Mapping[str, Any] | None) -> dict | None:
    if not filters:
        return None
    ops = {"$eq", "$ne", "$gt", "$gte", "$lt", "$lte", "$in", "$nin"}
    clauses = []
    for key, want in filters.items():
        if isinstance(want, dict):
            if not want or set(want) - ops:
                raise ValueError(f"unsupported filter operators for {key!r}")
            clauses.append({key: dict(want)})
        else:
            clauses.append({key: {"$eq": want}})
    return clauses[0] if len(clauses) == 1 else {"$and": clauses}


class S3VectorsStore:
    def __init__(self, bucket: str = "handbook-vectors", index: str = "chunks",
                 dim: int = 3, client=None):
        self._c = client or boto3.client("s3vectors", region_name=os.environ["AWS_REGION"])
        self._bucket, self._index = bucket, index
        for create in (
            lambda: self._c.create_vector_bucket(vectorBucketName=bucket),
            lambda: self._c.create_index(
                vectorBucketName=bucket, indexName=index,
                dataType="float32", dimension=dim, distanceMetric="cosine",
                # keep the large text out of the filterable-metadata budget
                metadataConfiguration={"nonFilterableMetadataKeys": ["text"]}),
        ):
            try:
                create()
            except self._c.exceptions.ConflictException:
                pass                                   # already exists

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for i in range(0, len(records), _PUT_BATCH):
            self._c.put_vectors(                       # same key overwrites = upsert
                vectorBucketName=self._bucket, indexName=self._index,
                vectors=[{"key": r.id, "data": {"float32": [float(x) for x in r.vector]},
                          "metadata": {**dict(r.metadata), "text": r.text}}
                         for r in records[i:i + _PUT_BATCH]])

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]:
        kwargs: dict[str, Any] = dict(
            vectorBucketName=self._bucket, indexName=self._index,
            queryVector={"float32": [float(x) for x in vector]},
            topK=top_k, returnMetadata=True, returnDistance=True)
        flt = _to_filter(filters)
        if flt:
            kwargs["filter"] = flt
        resp = self._c.query_vectors(**kwargs)
        out = []
        for v in resp["vectors"]:
            md = dict(v.get("metadata", {}))
            out.append(ScoredRecord(
                record=VectorRecord(id=v["key"], vector=(), text=md.pop("text", ""),
                                    metadata=md),
                similarity=1.0 - float(v["distance"])))  # cosine distance -> similarity
        return out

    def get(self, record_id: str) -> VectorRecord | None:
        resp = self._c.get_vectors(
            vectorBucketName=self._bucket, indexName=self._index,
            keys=[record_id], returnMetadata=True)
        if not resp["vectors"]:
            return None
        md = dict(resp["vectors"][0].get("metadata", {}))
        return VectorRecord(id=record_id, vector=(), text=md.pop("text", ""), metadata=md)

    def delete(self, record_ids: Sequence[str]) -> None:
        self._c.delete_vectors(vectorBucketName=self._bucket, indexName=self._index,
                               keys=list(record_ids))

Persistence: durable by design (it is S3). Encryption is configurable per bucket/index (SSE-S3 or SSE-KMS); access control is IAM and bucket policies; deletes remove vectors from the index, though be aware of how long deleted data can persist and what your compliance obligations are before relying on it (Part 11).

Pros

  • Object-storage economics: far cheaper than keeping an in-memory index for large, cold or infrequently queried corpora.
  • Nothing to operate: no cluster, no sizing, scales to very large indexes (billions of vectors per index in the GA announcement) with durability from S3.
  • Native AWS integration (IAM, KMS, CloudTrail, VPC endpoints) and a documented path to OpenSearch for hybrid or low-latency tiers.

Cons

  • Latency is object-store latency (around 100 ms for frequent queries, up to roughly a second for infrequent ones per AWS's GA numbers); wrong for interactive per-keystroke search.
  • Query features are narrower than a full engine: ANN plus metadata filters, with tight limits on filterable metadata size and write throughput.
  • AWS-only and proprietary, with no self-host path; feature set and limits are still evolving, so re-check the docs.

Choose it when: you are on AWS, the corpus is large or mostly cold, cost matters more than the last 50 ms of latency (archives, long-tail knowledge bases, batch RAG, multi-tenant "one index per customer" at low QPS).

Avoid it when: you need single-digit-millisecond latency, rich hybrid search in one call, or you are not on AWS or must self-host.

Gotchas

  • Dimension, data type and distance metric are fixed per index.
  • Filterable metadata has a small per-vector size budget; mark large text keys as non-filterable at index creation (you cannot change this later) or keep text elsewhere and store a pointer.
  • Writes and queries have per-request and per-second limits; batch put_vectors calls and plan around the documented limits instead of looping one vector at a time.

8.10 Which one when: the final summary#

Every store in this lesson, with the honest trade in one row. Use it after the decision flow: the flow narrows the family, this table breaks the tie.

Store Main pros Main cons Choose it when
NumPy store (7.2) Exact, deterministic, zero dependencies; perfect test double In-memory, O(N) per query, nothing durable Tests, notebooks, corpora under ~100k
FAISS / hnswlib (8.1) Fastest to start; widest index menu (FAISS); no server No metadata, durability, CRUD or auth; you build the database Batch jobs, evaluation, one process, one writer
pgvector (Part 4) Same ACID database, SQL filters, joins, one backup story HNSW is RAM-hungry; filters apply after the scan unless iterative scan; no native sparse hybrid You already run Postgres and the corpus is low millions
sqlite-vec (8.2) One file, runs anywhere SQLite does, exact Pre-v1; brute force; single writer Local-first, edge and small embedded apps
DuckDB VSS (8.3) Vectors next to Parquet/dataframes; full SQL Experimental; fragile index persistence; not a serving DB Analytical and batch work with embeddings
Chroma (Part 6) Friendliest embedded API; persistent client; Cloud available Small filter language; self-hosted is single node Prototypes and single-node apps
LanceDB (8.4) Embedded and durable, columnar and multimodal, object-storage path Versioned-table mental model; embedded scale-out is Enterprise Data-pipeline and lakehouse-style workloads
Qdrant (Part 5) Rich filters and payload indexes, hybrid and multivector, local mode to cluster You operate it (or pay for Cloud); more concepts than Chroma A retrieval product where filtering and hybrid matter
Elasticsearch (8.5) Best-in-class text search plus vectors in one request Heavy cluster; near-real-time; licensing You already run Elastic, or hybrid relevance is the product
OpenSearch (8.6) Apache-2.0, engine choice, hybrid pipelines, AWS-managed Many knobs; heavy cluster; reindex for mapping changes You already run OpenSearch or Amazon OpenSearch Service
Redis (8.7) Very low latency, one system for cache and vectors Memory-bound; RediSearch dialect; mixed licences Redis is already your hot store
Pinecone (8.8) Zero ops, namespaces for tenants, scales far Cloud-only, proprietary, usage-priced, eventual consistency You want managed and your budget allows it
AWS S3 Vectors (8.9) Object-storage cost, durable, no cluster, AWS-native Object-store latency; narrower query features; AWS-only Large, cold, cost-sensitive corpora on AWS

Seven rules of thumb, in the order you should ask them:

  1. Is it under ~100k vectors with one process? Use the NumPy store or FAISS. Do not deploy anything.
  2. Do you already run Postgres? Use pgvector. Same for Elasticsearch, OpenSearch or Redis if that is already where the data lives.
  3. Do you want zero servers in a real app? Chroma, LanceDB or sqlite-vec; DuckDB VSS for analytical work.
  4. Is filtering, tenancy or hybrid search central? Qdrant, or Elasticsearch/OpenSearch if keyword relevance leads.
  5. Do you want someone else to run it? Pinecone (fast, low latency, usage-priced) or S3 Vectors (cheap, latency-tolerant, AWS-only).
  6. Must you self-host or keep data inside your network? Qdrant, pgvector, OpenSearch or Elasticsearch, FAISS/embedded stores.
  7. Whatever you pick, put it behind VectorStore. The adapters in Parts 7 and 8 are the proof that switching is one class, not a rewrite.

Part 9: Data modelling#

9.1 What a record is#

Across every store, a searchable record has four parts:

Part Example Notes
ID chk_2e1f3249… deterministic, stable, unique — chk_<24 hex> content ids from 05.8; Qdrant needs int/UUID so derive a stable UUID5 and keep the original in the payload
Vector(s) [0.9, 0.1, 0.0] one or more per record; dtype float32/float16/int8/binary; dimension fixed per collection/index
Payload / metadata {tenant, kind, lang, section} filterable attributes; keep it flat-ish and typed
Text the chunk itself for display, citation, re-ranking, debugging

9.2 Where does the text live?#

Option Pros Cons
Text in the vector DB (payload/document field) one read path: search → hit → text in one call; simple duplicates storage; payload size limits (Qdrant warns about large payloads; Chroma documents are meant for this); harder to JOIN or version
Text in your own store (Postgres/files/S3), vector DB holds ID+vector+filter fields single source of truth; cheap payloads; text versioning independent of vectors two reads per result (vector search → fetch text); must keep the two in sync on delete/update
Hybrid hot metadata+snippet in payload, full text elsewhere most moving parts

9.3 Namespaces/collections vs one big collection with filters#

  • One collection + filter field (the default): simplest; works until tenant count or filter selectivity hurts (06.6).
  • Namespace/collection per tenant: hard isolation, independent scaling; but thousands of collections is an anti-pattern (Qdrant Cloud caps a cluster at 1,000 collections by default; Pinecone namespace counts range from 100 on Starter to 1,000,000 on Enterprise per serverless index, per its docs, November 2026; Chroma collection-per-tenant doesn't scale past hundreds). Rule of thumb: per-tenant partition/shard (Qdrant is_tenant, sqlite-vec partition key, Postgres table partition) or a Pinecone namespace beats per-tenant collection at SaaS scale.
  • Collection per kind of data (handbook vs tickets vs contracts): reasonable — different schemas, retention, or embedding models justify separate collections even for one tenant.

9.4 Multiple vectors per record#

Title vs body embeddings, summary vs chunk, dense + sparse, or late-interaction multivectors all fit "one record, several vectors". Qdrant named vectors support it natively, Elasticsearch/OpenSearch accept several vector fields per document, LanceDB can hold several vector columns per table; pgvector wants separate columns or tables; Chroma's self-hosted path is single-vector per record (Cloud adds sparse). The modelling rule: one record per retrievable unit, vectors as attributes of it — don't create a record per vector unless vectors outlive their text.

9.5 Schema evolution and the dimension trap#

  • Dimension mismatch is the #1 day-one bug. A vector(3) column rejects a 768-dim embedding; Chroma raises on mismatched dims; Qdrant collections are fixed-size. Decide the dimension when you create the collection — it comes from the embedding model, not from you.
  • Changing embedding models = new vectors, not updated ones. Old and new vectors are incomparable (02.3, 7.5). The migration is a re-embed + dual-write/shadow-read exercise (06.1 for the model versioning, Module 05's ingestion lessons for the pipeline). Store model, model_version, dimensions, dtype, task_type, preprocessing_hash as payload fields so you can audit and filter by embedding generation.
  • Adding a payload field is cheap in every store; renaming/removing one is a migration. Design metadata in 05.8 first.

Part 10: Operations#

Deep-dive

10.1 Persistence and backups#

Store Persistence story
pgvector Postgres backups/PITR — vectors ride along
Qdrant snapshots (create_snapshot/recover_snapshot), or disk persistence in path= local mode
Chroma PersistentClient files; client.reset() is destructive — snapshot the directory for backups
FAISS / hnswlib write_index/save_index plus your own metadata file; you own consistency
sqlite-vec the SQLite file; .backup or VACUUM INTO
DuckDB VSS table data in the .duckdb file; HNSW index persistence is experimental, rebuild if in doubt
LanceDB Lance files (local or object storage), versioned on every write
Elasticsearch / OpenSearch shard replicas plus snapshot repositories
Redis RDB snapshots and/or AOF; memory-first
Pinecone / S3 Vectors provider-managed durability; read retention and export options
Managed services (general) provider snapshots/PITR; read the retention windows

10.2 Capacity planning#

Vector memory is arithmetic, not guessing:

text
vectors bytes   = N × dims × bytes_per_dim          (float32=4, float16=2, int8=1, binary=1/8)
hnsw links      ≈ N × M × 2 × 4 B × 1.2       (≈154 B/vector at M=16: a few % at 1,536 dims, ~30% at 128 dims)
payload         = N × avg payload bytes × ~1.5 (storage-engine overhead)
headroom        ≈ +20% on the total            (page cache, optimiser temp segments, runtime)
working set     ≈ vectors + index + hot payload, all in RAM for HNSW-class indexes

Worked example: 1M chunks × 1,536 dims × 4 B = 6.1 GB of raw vectors. The HNSW graph links themselves add only about 0.15 GB here (06.4, 4.7 — links are cheap next to high-dimensional vectors), and with ~20% headroom for the optimiser's temporary segments and runtime the vectors-plus-index budget is about 7.5 GB before payload. Those factors are the ones Qdrant's capacity-planning guide uses (as of November 2026: HNSW m × 2 × 4 B × 1.2, payload ×1.5, then ~20% headroom); other engines differ, so measure; int8/halfvec quantization cuts it 2–4×. This is why "will it fit in RAM" is the first capacity question for HNSW stores, and why disk-based indexes (pgvector on disk, DiskANN, Qdrant quantized-on-disk, S3 Vectors) exist for the rest. Always compute for your dims and N — never trust a vendor's "millions of vectors" headline without the dimension.

10.3 Replication, sharding, upgrades, monitoring#

  • Replication/sharding is a server-mode concern: Qdrant, Elasticsearch and OpenSearch replicate shards and scale horizontally; pgvector inherits Postgres streaming replication/partitioning; embedded tools (Chroma local, LanceDB, sqlite-vec, DuckDB) don't — you shard at the application level (tenant → shard → file/collection).
  • Upgrades: managed services hide them; self-hosted means reading release notes for index-format changes (Qdrant/Chroma have had snapshot-compatible upgrades, but verify per version).
  • Monitoring: watch query latency p50/p99, index build progress/state, memory vs capacity, payload index hit rates, and a recall proxy (periodic exact=True comparisons on a sample — 06.10). Qdrant exposes Prometheus metrics; pgvector shows pg_stat_progress_create_index during builds.
  • Managed cost drivers (structure, not prices — check current pricing): memory-bound billing (Qdrant Cloud, Pinecone serverless charges by stored GB + operations; Elasticsearch charges by node), read/write units (DynamoDB-style stores), per-request and per-GB charges (S3 Vectors). The pattern: you pay for what stays hot — RAM-resident vectors cost more than object-storage vectors.

10.4 Migration and avoiding lock-in#

The exit strategy is the VectorStore interface plus discipline:

  1. Keep vectors and text in exportable form — every store here can dump IDs+vectors+payloads (Qdrant scroll/snapshots, Chroma get, pgvector COPY, Pinecone export, S3 Vectors export API). If you can't export, don't store there.
  2. Dual-write or shadow-read during migration: write to old+new, compare result sets on logged queries, cut over, keep the old as rollback. Pattern level — the same blue/green re-embedding shape Module 05's ingestion lessons cover.
  3. The interface is the contract — VectorStore (Part 7) means swapping stores is an adapter, not a rewrite. The cost of lock-in is proportional to how much store-specific logic leaked into application code.

Part 11: Security#

Deep-dive
  • Credentials: Qdrant/Chroma Cloud and managed services use API keys — env vars, never in code, never logged (03.10's redaction rules apply). Self-hosted Qdrant starts with no auth — the docs say so explicitly; put it behind network isolation or enable API keys before exposing it.
  • Network isolation: bind to localhost/LAN, TLS in front, private endpoints for cloud services. The vector DB holds your most sensitive derived data — embeddings can leak information about source text (02.3, 10.7).
  • Encryption: at-rest encryption is table stakes on managed services; verify per provider. S3 Vectors offers SSE-KMS per index.
  • Tenant isolation: the query-time filter must be built server-side from the authenticated principal, never from client input — and for hard isolation prefer partition/shard/namespace over a shared collection (06.6 owns the ACL-filter pattern; Postgres row-level security is the relational equivalent).
  • Deletion guarantees: "delete" semantics differ — hard delete vs soft-delete/tombstones vs snapshot retention. If you have erasure obligations (GDPR-style), know whether deleted vectors persist in snapshots/backups and for how long; pgvector deletes are real DELETEs but PITR backups retain history by design.
  • Audit: who queried what is a compliance question on managed services (audit logs) and an application-logging question on self-hosted ones.

Part 12: Local and embedded options — and when to skip a database entirely#

For prototypes, tests, notebooks, edge and small single-node apps, you don't need a server at all:

Option Persistence Notes
NumPy store (Part 7) none (in-memory) exact, zero deps beyond numpy; the test double
Chroma Client() / PersistentClient RAM / local files friendliest embedded API; HNSW self-hosted
Qdrant :memory: / path= RAM / local files same API as server mode — best "grow into" path
FAISS / hnswlib you serialize it in-process index libraries (8.1)
LanceDB local files / object storage columnar, multimodal, SQL+vector (8.4)
sqlite-vec the SQLite file vec0 virtual table, float[N] ≤ 8,192 dims, metadata/partition columns; pre-v1 (8.2)
DuckDB VSS in-memory (experimental persistence flag) CREATE INDEX ... USING HNSW; analytical workloads (8.3)

Part 13: Testing vector-store code#

Deep-dive

Lesson 03.10 owns the general machinery (fakes, contract tests, markers, CI without keys). Vector stores add three specifics:

  1. Test against NumpyVectorStore by default. It's exact, deterministic and needs no service — your unit tests and CI run anywhere. Use fixed vectors so scores are reproducible.
  2. Contract-test the real adapters behind a marker that only runs when the service is up (pytest -m integration). Same assertions, different store fixture — Part 7's test_vector_store_contract.py is the template.
  3. Beware nondeterminism sources: ANN recall varies with index params and data order; filter edge cases (empty result, missing payload key, wrong type); dimension mismatches must raise, not silently truncate. Assert on ranks and sets, not exact float scores, for ANN stores; the NumPy store can assert exact similarities.

Reference

Every failure mode below has already happened to someone running vectors in production. The pattern is always the same: the store did what it was told — the telling was wrong. Learn to recognise the symptom, find the row, apply the fix.

(For choosing a store rather than operating one, 2.4 is the decision table; for filter-depth failures — ACL leaks, selectivity, partition strategy — 06.6 goes deeper.)

# Failure What you see Root cause Fix
1 Dimension mismatch Insert/query raises (expected 3 dimensions, not 768; Chroma dimension error; Qdrant vector-size error) Collection/column dim is fixed at creation and comes from the embedding model, not from you Decide dim before creating the store; store model/dimensions/dtype in payload (9.5); a model change means a new collection + re-embed, never an in-place swap
2 Wrong distance metric Results look plausible but subtly wrong; <#> returns negative scores Index operator class / distance config doesn't match the model's training metric; cosine vs dot vs L2 confusion Match the metric to the model (cosine for normalised embeddings); verify ordering on known-similar pairs; remember <#> is negative inner product (4.2)
3 Forgotten/missing index Queries fine on 10k rows, crawl at 1M; EXPLAIN shows Seq Scan pgvector indexes are explicit CREATE INDEX; Qdrant/Chroma build theirs automatically — the failure is skipping schema creation or building the index before bulk load on IVFFlat Create the index after loading data; verify with EXPLAIN (ANALYZE) (4.5); watch index-build state in monitoring (10.3)
4 Filter shrinkage Filtered LIMIT 10 returns 2–4 rows, sometimes zero ANN scan-then-filter: the WHERE applies after the candidate list is cut (4.4) hnsw.iterative_scan/ivfflat.iterative_scan (pgvector), filter inside the query with payload indexes (Qdrant/Chroma), raise ef_search/hnsw_ef, or partition/partial indexes for structural filters — deep dive in 06.6
5 Orphan vectors Deleted documents still appear in search results Two-write problem: text store deleted, vector store not — or delete used the wrong id (UUID vs chunk_id) Delete by the stable record id in the same pipeline step as the text delete; reconcile manifest↔store (05.9); the contract test's delete path catches adapters that silently no-op
6 Text/vector out of sync Hit returns stale text, or fetch-by-id 404s Re-embed updated the vector but not the text (or vice versa); two stores drifted One write path per record; content-hash ids surface drift (05.8); periodic reconciliation job
7 Cold-start latency First queries after deploy/restart are 10–100× slower, then speed up HNSW graph / index files loading into RAM or being paged in; Qdrant loading segments; Chroma loading its index Warm-up queries on deploy (a canned query per collection); keep index files on fast local disk; size memory for the hot set (10.2)
8 Memory wall OOM kills, index refuses to build, node thrashing Vectors + graph live in RAM: N × dims × 4 B plus HNSW links and ~20% headroom (10.2) Quantize (halfvec/int8/binary/product), use disk-based indexes, shrink dims, shard, or a bigger node — compute first, then choose
9 Silent recall decay Quality degrades gradually; nothing errors ef_search/hnsw_ef defaults sized for a small corpus; data grew, knob didn't Raise the query-time knob per workload; compare against exact=True ground truth periodically (06.10)
10 Duplicate/stale records Same chunk twice in results, or old text after re-ingest Chroma add doesn't update existing ids (use upsert); non-idempotent writes Idempotent upserts keyed by stable id everywhere; content-hash ids make re-runs no-ops
11 Qdrant rejects your ids Upsert fails: point id must be unsigned int or UUID chk_<hex> ids aren't valid point ids Derive a stable UUID5 (_stable_id) and keep the original id in the payload (chunk_id) — Part 5/7.3 show the pattern
12 Score-direction confusion "Most similar" returns least similar; similarities > 1 or negative Chroma/pgvector return distances (lower = better); Qdrant returns scores (higher = better) The VectorStore contract fixes direction: adapters convert to similarity. Check each store's convention before writing raw queries
13 Unindexed filter field Filtered queries fine in dev, slow in prod Payload/metadata field has no secondary index (Qdrant create_payload_index, Postgres CREATE INDEX, Chroma has none — it scans) Index every field you filter on; Chroma's small where grammar is the trade-off for simplicity (6.3, 06.6)
14 Tenant leak Tenant A's query returns tenant B's chunks Filter built from client input, forgotten, or applied post-retrieval client-side Build the tenant predicate server-side from the authenticated principal; never trust client-supplied filters (Part 11, 06.6)
15 "Deleted" data still recoverable Erasure request, but vectors persist in snapshots/backups Snapshots, PITR backups and eventually-consistent indexes retain copies by design Know each store's retention story (Part 11); deletion jobs must cover every copy, including backup windows

Common misconceptions#

Misconception Reality
"A vector database is just a faster way to compute cosine similarity." The index is one layer. The database adds persistence, CRUD, filtering, tenancy, replication, backups and auth — that's what you're actually choosing.
"If it has HNSW it's as good as every other HNSW." Same algorithm, different everything else: filter strategy, update behaviour, memory model, multi-tenancy, hybrid features, ops model.
"Adding an index can't change results." ANN indexes return approximately nearest neighbours — results legitimately differ from exact search, and pgvector's docs say so plainly.
"Filter first, then search, always." Post-filtering can return fewer than k or zero results; pre-filtering can wreck ANN recall. The right strategy depends on selectivity — 06.6.
"I'll store the text in the vector DB because it's convenient." Convenient until payload limits, versioning and sync problems bite. ID+vector+filter fields in the DB, text in your store, is the durable default.
"Managed means I don't have to think about it." You still own schema, recall tuning, filter correctness, cost and exit strategy.
"Chroma/Qdrant local mode is just for demos." :memory:/path= and PersistentClient are legitimate production shapes for single-node apps — know their limits (no replication, single writer-ish).
"I need a dedicated vector DB for anything beyond a toy." pgvector inside your existing Postgres, or an embedded store, covers a large middle ground. Choose by workload, not fashion.
"Deleting a vector deletes it everywhere." Snapshots, backups and eventually-consistent indexes retain copies; erasure has a retention story you must design.

Key takeaways#

  • A vector database = vectors + index + store + service. Libraries give you the index; databases give you the rest.
  • Four shapes dominate: libraries (NumPy, FAISS, hnswlib), in-database (pgvector, Elasticsearch dense_vector, OpenSearch knn_vector, Redis vector index), dedicated or managed (Qdrant, Pinecone, AWS S3 Vectors), embedded (Chroma, LanceDB, sqlite-vec, DuckDB VSS).
  • pgvector: vector/halfvec/bit/sparsevec types, <->/<#>/<=>/<+>/<~>/<%> operators, HNSW (m, ef_construction, hnsw.ef_search) and IVFFlat (lists, ivfflat.probes), filters post-scan unless iterative scan, binary_quantize expression indexes, psycopg + register_vector.
  • Qdrant: collections of points with payload, COSINE/DOT/EUCLID/MANHATTAN, query_points + Filter/FieldCondition, SearchParams(hnsw_ef, exact), payload indexes incl. is_tenant, named/sparse/multivectors, snapshots, :memory:/path= local modes, AsyncQdrantClient.
  • Chroma: Client()/PersistentClient/CloudClient, get_or_create_collection + configuration={"hnsw": ...}, add/upsert/update/delete, query(query_embeddings, where, where_document) column-major results, where filter DSL, distances are lower-is-better.
  • The other options (Part 8): FAISS/hnswlib = fast index, you build the database; sqlite-vec = one file, exact, pre-v1; DuckDB VSS = analytical and experimental; LanceDB = embedded columnar and durable; Elasticsearch/OpenSearch = hybrid search engines with a kNN clause and near-real-time writes; Redis = in-memory, low latency, memory-bound; Pinecone = managed with namespaces; S3 Vectors = object-storage cost with object-storage latency.
  • The VectorStore protocol + NumpyVectorStore gives you a testable seam and a migration path; adapters absorb score-direction, ID-type and filter-dialect differences.
  • Model the record as ID + vector(s) + payload + text-pointer; store embedding provenance (model, version, dims, dtype) with every vector.
  • Capacity = N × dims × bytes plus index overhead; filters are the hardest correctness problem (→ 06.6); deletion has a retention story.
  • Start simple: NumPy → embedded → single-node → dedicated → managed. Don't deploy a cluster for 20k chunks.

Terms introduced in this lesson#

Term One-line definition
Vector database A store combining vector persistence, ANN indexing, metadata filtering and operational features
Vector library An in-process ANN index (FAISS, hnswlib) with no persistence/CRUD/service layer
pgvector Postgres extension adding vector types, distance operators and HNSW/IVFFlat indexes
halfvec / bit / sparsevec pgvector's float16 / binary / sparse vector column types
Distance operator pgvector's <->, <#>, <=>, <+>, <~>, <%> comparison operators
hnsw.ef_search / hnsw_ef / ef The query-time candidate-list size knob, named differently per store
Iterative index scan pgvector ≥0.8 feature that keeps scanning the ANN index until enough rows pass the filter
Qdrant collection / point / payload Its namespace / ID+vector(s) / JSON metadata record
Named vector Multiple independently-configured vectors per record/point
Payload index A secondary index on filterable metadata fields (Qdrant create_payload_index)
is_tenant shard Qdrant's tenant-aware shard placement for payload-partitioned multitenancy
Chroma collection / embedding function Its record namespace / pluggable text→vector component
where / where_document Chroma's metadata-filter and full-text-filter query arguments
Column-major results Chroma's result shape: field-per-list rather than record-per-object
VectorStore protocol The adapter interface this lesson defines so app code is store-agnostic
NumpyVectorStore The exact brute-force in-memory VectorStore used for tests and small corpora
Contract test One test suite run unchanged against every VectorStore implementation
Vector bucket / vector index (S3 Vectors) AWS's object-storage vector container and its searchable partition
knn_vector / dense_vector OpenSearch and Elasticsearch field types for vectors
RediSearch vector index Redis's FT.CREATE ... VECTOR index over hash/JSON fields (FLAT/HNSW/SVS-VAMANA)
SPANN / DiskANN Alternative ANN index families: SPANN in Chroma Cloud, DiskANN-style disk indexes in pgvectorscale
IndexIDMap2 / IDSelectorBatch FAISS wrapper that adds your own int64 ids and removal, and the selector that restricts a search to given ids
vec0 virtual table sqlite-vec's table type holding vectors, metadata, partition-key and auxiliary columns
Lance table LanceDB's versioned columnar table on local disk or object storage
Pinecone namespace A partition inside a Pinecone index; queries see one namespace at a time
Near-real-time search Elasticsearch/OpenSearch behaviour: a write becomes searchable after the next refresh

Exercises#

  1. pgvector: create the handbook_chunks table, load CHUNKS, add the HNSW index, and run the filtered query with tenant='acme'. Then run EXPLAIN (ANALYZE) with and without the index and compare plans.
  2. pgvector filters: set hnsw.ef_search = 10, insert 200 extra rows for a second tenant, and show how the filtered query returns fewer than LIMIT results. Fix it with SET hnsw.iterative_scan = relaxed_order and re-run.
  3. Qdrant: run the :memory: client, upsert CHUNKS, query with a tenant filter, then create the payload index and repeat. Time both — on a tiny corpus the difference is noise, but note where the index matters at scale.
  4. Chroma: do the same with PersistentClient(path="./chroma_db"), then delete the directory and re-run to see persistence vs ephemeral behaviour.
  5. Interface: the three adapters ship in Part 7.3 — wire the contract test to run against all four VectorStore implementations (NumpyVectorStore in CI; the other three behind the integration marker), then extend each adapter's filter translation to handle $in sets and $or/$and logic.
  6. Capacity: compute raw vector bytes, estimated index size and payload size for 5M chunks at 768 and 1,536 dims in float32 vs int8. Which fits in 16 GB RAM?
  7. Modeling: add a title named vector to the Qdrant collection and a second collection for kind='ticket'; explain when you'd query each.
  8. Part 8 adapter: choose one store from Part 8 that you can run locally (FAISS, sqlite-vec, DuckDB or LanceDB need no server), load CHUNKS through its adapter, and make it pass the contract test from 7.4. Note which test it fails first and why.
  9. Choose: for each of these, name the store and one reason from the 8.10 table: (a) a desktop notes app, (b) a 20M-chunk archive queried a few times a day on AWS, (c) a SaaS product with 3,000 tenants and strict isolation, (d) an Elasticsearch shop adding semantic search, (e) a notebook joining embeddings to Parquet.
Hints and what you should see

(Exercises 1 to 4 need a running Postgres, Qdrant or Chroma, so their hints say what to expect rather than showing pasted output. The filter function in exercise 5 and the arithmetic in exercise 6 were checked with plain Python.)

  1. Expect the filtered query to return the acme chunks, with the vacation-accrual chunk chk_2e1f324932df6bacc8135ba2 first for the query vector (0.95, 0.05, 0.0) (the same top hit the contract test in 7.4 asserts). In EXPLAIN (ANALYZE) the plan without the HNSW index is Seq Scan on handbook_chunks followed by a Sort on the distance expression. With the index you should see Index Scan using handbook_chunks_embedding_hnsw ... Order By: (embedding <=> ...), but on ten rows the planner will often keep choosing the seq scan, which is the correct decision for a tiny table (4.5 says so). To see the index plan for the exercise, run SET enable_seqscan = off; in the session first (an experiment setting, never a production one), or load a few thousand rows.

  2. Expected shape: with hnsw.ef_search = 10 the index returns about 10 candidates, the second tenant's 200 rows crowd them out, and the WHERE tenant = 'acme' is applied afterwards, so LIMIT 5 returns fewer than five rows (often 0 to 2). Use SET enable_seqscan = off here as well, otherwise the planner scans the table and you see no shrinkage. After SET hnsw.iterative_scan = relaxed_order; the same query returns all five, because the scan continues until enough rows pass the filter (capped by hnsw.max_scan_tuples, default 20,000). relaxed_order may return results slightly out of distance order; strict_order keeps the order. Both need pgvector 0.8.0 or later.

  3. With QdrantClient(":memory:") both queries return the same hits, because with ten points the difference is noise. Expect the client to tell you that payload indexes have no effect in local mode (wording varies by client version): in local mode a payload index changes nothing, and the difference appears on a server. On a server the unindexed filter still works on a small collection, but on a large one it forces a scan of payloads (and in Qdrant Cloud's strict mode, an unindexed filter field is rejected outright, as 06.6 notes). So "note where it matters at scale" means: the larger the collection and the more selective the filter, the more the index matters.

  4. First run with PersistentClient(path="./chroma_db"): creates the directory, upsert stores the ten chunks, the query returns hits. Second run without the upsert: the collection already exists and the query still returns hits, which is what persistence means. Delete ./chroma_db and re-run the query only: get_or_create_collection makes a fresh, empty collection, so the query returns no results (and may raise if you ask for more n_results than exist, depending on version); you must upsert again. With the ephemeral chromadb.Client(), everything is gone the moment the process exits, which is why it is for tests.

  5. For the contract test, parametrize the store fixture over the four classes and mark the three service-backed ones, e.g. @pytest.fixture(params=["numpy", pytest.param("pgvector", marks=pytest.mark.integration), ...]). For the filters, extend the same convention everywhere: {"tenant": {"$in": [...]}}, {"$or": [...]}, {"$and": [...]}. The NumpyVectorStore version, checked in plain Python against a record with tenant=acme, kind=policy, year=2025:

    python
    def _matches(meta: dict, filters: dict | None) -> bool:
        if not filters:
            return True
        for key, want in filters.items():
            if key == "$and":
                if not all(_matches(meta, sub) for sub in want): return False
            elif key == "$or":
                if not any(_matches(meta, sub) for sub in want): return False
            else:
                got = meta.get(key)
                if isinstance(want, dict):
                    for op, v in want.items():
                        ...  # the operator chain from 7.2, unchanged, ending in `else: raise ValueError`
                elif got != want:
                    return False
        return True

    {"tenant": {"$in": ["acme", "globex"]}} matches, {"tenant": {"$in": ["globex"]}} does not, {"$or": [{"kind": "ticket"}, {"year": {"$gte": 2025}}]} matches, and {"$and": [{"tenant": "acme"}, {"$or": [{"kind": "policy"}, {"kind": "howto"}]}]} matches. Decide what an empty $or means (here it matches nothing; say so in the docstring). For the other adapters: Qdrant $in is models.FieldCondition(key=..., match=models.MatchAny(any=[...])), $or is a nested models.Filter(should=[...]) and $and a nested models.Filter(must=[...]); Chroma accepts $in, $or and $and natively (one operator per dict, so keep the nesting as in 6.3); pgvector needs col = ANY(%s) and parenthesised (a OR b) with bound parameters, never string-built values. The contract test should run the same four filter cases against all four stores.

  6. Arithmetic (ran): raw vector bytes = N × dims × bytes; HNSW links at M=16 add N × 16 × 2 × 4 B × 1.2 ≈ 0.7 GiB for 5M points; then ~20% headroom (10.2). Payload: assume 1 KB per chunk (4.7 GiB raw for 5M chunks, about 8.4 GiB in RAM after the ×1.5 storage factor and headroom; yours will differ).

    Dims dtype Raw vectors Vectors + links + 20% headroom Fits in 16 GB?
    768 float32 15.36 GB (14B.2 GiB) about 18.0 GiB No
    768 int8 3.84 GB (3.6 GiB) about 5.2 GiB Yes, even with payload in RAM (about 13A.6 GiB in total)
    1,536 float32 30.72 GB (28.6 GiB) about 35.2 GiB No
    1,536 int8 7.68 GB (7.2 GiB) about 9.4 GiB Only with payload on disk (about 17.8 GiB with it in RAM); tight, do not plan on it

    The answer to "which fits": 768-dim int8 comfortably, 1,536-dim int8 marginally, neither float32 case. Note the assumptions you made (payload size, headroom, whether payload and rescoring vectors live on disk), because every real answer is a range. The headroom is the soft spot: 06.4, 4.7 estimates HNSW graph links at only a few percent of float32 vector bytes at these dimensions; the 20% headroom is what covers the engine's own overheads (temporary segments during optimisation, page cache, runtime), so say which factors you used.

  7. A title named vector means each point has two vectors (body and title) searched independently: in Qdrant create the collection with vectors_config={"body": VectorParams(...), "title": VectorParams(...)} and pass using="title" or using="body" to query_points. Use title when the query looks like a heading lookup ("expense policy"), body for question-style queries, or fuse both with a prefetch. A separate kind='ticket' collection is worth it when tickets have a different schema, embedding model, retention or access policy, or would dominate nearest neighbours of policy queries; if you only need to exclude tickets, a payload filter on one collection is simpler and cheaper (9.3).

  8. Expect the contract test's test_a_bad_filter_never_widens_the_search to be the first to fail on a naive adapter: filters are the part that differs most between stores. The adapters in Part 8 raise ValueError for unknown keys and operator dicts they cannot translate, which satisfies that test; sqlite-vec, DuckDB and LanceDB additionally need the id column handled consistently so get and delete agree.

  9. Reasonable answers: (a) sqlite-vec (one local file, exact search); (b) AWS S3 Vectors (cold and cost-sensitive, latency-tolerant); (c) Qdrant with payload-partitioned tenants (is_tenant) or Pinecone with a namespace per tenant, not a collection per tenant; (d) Elasticsearch dense_vector plus its existing query DSL and RRF; (e) DuckDB VSS or LanceDB. Your reasons matter more than the exact pick, as long as they name the trade (latency, ops, licence, isolation).


Check yourself#

  1. What four layers make up a vector search system, and which does a "vector library" not provide?
  2. Name three ways to get vector search without deploying a dedicated vector database.
  3. In pgvector, what does <#> return and why is it surprising?
  4. Why must the pgvector index operator class match the query operator?
  5. What happens to a LIMIT 10 filtered query on an HNSW index when the filter matches 10% of rows, and what's the pgvector fix?
  6. What are Qdrant's four distance options, and what does COSINE do to your vectors on upload?
  7. Why do Qdrant point IDs need uuid5 derivation for string chunk IDs?
  8. What's the difference between add and upsert in Chroma?
  9. Why are Chroma distances converted with 1 - d in the adapter?
  10. What does is_tenant=True on a Qdrant payload index actually do?
  11. Where should chunk text live, and what's the durable default?
  12. Give the capacity formula for 2M chunks at 1,024 dims in float32, and estimate with HNSW overhead.
  13. What are the four Qdrant quantization families and their rough compression ratios?
  14. Why is exact=True/exact search useful even in production?
  15. What must be true before you can safely swap vector stores, and what does the VectorStore protocol buy you?
  16. Why do you normalize vectors before using FAISS IndexFlatIP for cosine similarity, and what does FAISS not store for you?
  17. Name two things that make Elasticsearch and OpenSearch writes differ from a Postgres insert from the reader's point of view.
  18. Which Part 8 stores trade latency for cost, and which trade RAM for latency?

Further resources#


← 06.4 — Vector Indexes: HNSW, IVF, Quantization and Trade-offs | Module 06 overview | 06.6 — Filtering, Metadata and Multi-Tenant Search →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close