Search, graph, time-series, vector: the specialist engines
Four workloads where a different index wins, what each engine does underneath, and how far Postgres gets before you bolt one on
You add a full-text GIN index on to_tsvector('english', name) to the products table and query it with websearch_to_tsquery('english', 'deluxe widget'): hundreds of matches. A customer types 'delux widgit'. How many products does the same full-text query return?
The engines in the previous chapters changed how data is stored: key-value and document stores dropped joins for predictable lookups, wide-column stores bet on LSM writes, columnar stores bet on scans. The four in this chapter keep ordinary storage and change the index. Search engines index words. Graph databases index adjacency. Time-series databases index time and compress it. Vector databases index geometry. Each index answers one kind of question much faster than a B-tree can, and Postgres has an extension for all four, so the real question is never “can Postgres do it” but “where does the extension stop being enough”.
Search: the inverted index
A B-tree on name answers “names starting with ‘Deluxe’”. It cannot answer “names containing ‘widget’”, because the word is not at the start of the key. A search engine builds an inverted index: for every term, the sorted list of documents that contain it, with positions and frequencies. A query for deluxe widget intersects or unions two lists and never reads a document that matches neither.
What makes it a search engine rather than a lookup table is everything around that list:
- Analysis. Text is tokenised, lowercased, stemmed, stripped of stop words, and optionally expanded with synonyms, both at index time and at query time. The analyser is per field, and choosing it is most of relevance tuning.
- Scoring. Lucene, under both Elasticsearch and OpenSearch, ranks with BM25 by default: a term counts more if it is rare in the corpus (inverse document frequency), counts more the more often it appears in the document but with diminishing returns (
k1, default 1.2), and counts less in long fields (b, default 0.75). Postgres’sts_rankuses term frequency and proximity but no corpus-wide IDF, so a common word weighs as much as a rare one. - Fuzziness. A
matchquery with"fuzziness": "AUTO"accepts terms within edit distance 1 or 2, depending on term length, using Levenshtein automata that walk the term dictionary instead of comparing every term. - Aggregations. Facet counts (products per category, price buckets) come from per-field columnar structures called doc values, computed over the matching set in the same request.
Under the index, Lucene is an LSM design like the ones in the LSM chapter. New documents go to an in-memory buffer and are written as immutable segments; background merges combine segments and purge deleted documents. A document becomes searchable when a refresh opens a new segment, every second by default (index.refresh_interval). Search is therefore near-real-time: a write acknowledged now is invisible to search for up to a second. An update is a delete plus a re-insert, so a catalogue that rewrites every product’s stock count each minute keeps the merge machinery permanently busy. Keep fast-changing fields out of the search index, or accept the cost.
OpenSearch and Elasticsearch shard an index by document id across nodes, and a query goes to one copy of every shard and merges the top results. That makes them good at what they are for and poor at what a database is for: no multi-document transactions, no joins, and a copy of your data that is always slightly behind.
Staying in Postgres goes further than most teams expect. tsvector with a GIN index gives stemming, ranking, phrase and prefix queries, and websearch_to_tsquery parses what users type. pg_trgm with a GIN or GiST index gives typo tolerance and fast ILIKE '%term%'. A GIN-indexed tsvector on tens of millions of rows answers selective queries in milliseconds. Where it runs out: relevance tuning as a product discipline (synonyms, per-field boosts, learning to rank), faceting over large match sets, many languages, and query loads that you do not want on the primary. Extensions such as ParadeDB’s pg_search bring a BM25 index into Postgres and move that line further; evaluate one before you add a cluster.
Graph: traversal as a primitive
“Customers who bought this also bought” is a two-hop question: from a product to its buyers, from those buyers to their other products. In SQL that is a self-join through order_items and orders, and the planner handles it well, because two hops is a fixed shape. The relational model struggles with variable-depth questions: every product within four hops of this one, the shortest chain of referrals between two customers, all accounts connected to a flagged card through any number of shared devices. SQL can express them with recursive CTEs (the aggregation chapter shows WITH RECURSIVE), but every hop is a join over an index, and the planner cannot estimate how many rows the fourth hop produces.
A native graph database such as Neo4j stores index-free adjacency: each node record points directly at its relationship records, and each relationship points at its neighbours. Following an edge is a pointer dereference, not an index lookup, so the cost of a traversal grows with the part of the graph it touches, not with the size of the whole graph. Queries are written as patterns in Cypher, whose ideas the ISO GQL standard (2024) adopted:
MATCH (p:Product {id: 42})<-[:BOUGHT]-(c:Customer)-[:BOUGHT]->(other:Product)
RETURN other.id, count(*) AS together ORDER BY together DESC LIMIT 5
Apache AGE brings Cypher into Postgres. A graph becomes a schema; each vertex label and edge label becomes a table with an agtype (JSON-like) properties column, and edges store start_id and end_id. A Cypher query is rewritten into SQL joins over those tables. So AGE gives you the query language and keeps one database, but not index-free adjacency: a hop is a join, and you must index start_id and end_id yourself. It is a good fit for graph-shaped queries on graph-shaped data of modest size, and for teams that want Cypher’s readability without a second system.
Two warnings before anyone buys a graph database for recommendations. First, raw co-occurrence counts recommend bestsellers: if 30% of customers bought product 1, product 1 is “also bought” with everything. The lab shows it on the shop. Useful scores normalise by popularity (lift, Jaccard, cosine over purchase vectors), and that is arithmetic, not traversal. Second, most production recommenders compute those scores offline, in batch over the whole purchase history, and serve them from a key-value lookup. A graph database earns its place when queries are interactive, multi-hop and shaped by the user: fraud rings, access-control graphs, network topology, knowledge graphs.
Time series: append, bucket, compress, expire
Metrics, sensor readings, prices and stock levels share a shape: rows arrive in time order and are almost never updated, queries ask for recent ranges grouped into buckets, old data is wanted at lower resolution, and the oldest is deleted. Each property has a matching technique:
| property | technique | in Postgres alone | in TimescaleDB |
|---|---|---|---|
| queries hit recent time ranges | partition by time | declarative partitioning, pg_partman |
hypertables: chunks created automatically on insert |
| old data is read rarely and never changed | columnar compression | none built in | compress_chunk, typically 10 to 20 times smaller |
| dashboards want hourly or daily rollups | incrementally maintained aggregates | materialised views, refreshed in full | continuous aggregates, refreshed incrementally |
| data expires | drop whole partitions | DROP TABLE on a partition |
drop_chunks, retention policies |
| range scans over time order | small, ordered index | BRIN on the time column | chunk exclusion plus per-chunk indexes |
TimescaleDB is that column filled in, as a Postgres extension. A hypertable looks like one table and is a set of chunks, each a time range (one day in the lab). Queries with a time predicate skip whole chunks, at plan time or at start-up for now()-relative ranges. Compression rewrites a chunk into a columnar layout: rows are grouped into batches of up to 1,000 per compress_segmentby value (a product, a device), each column of a batch is stored as one compressed array (delta-of-delta for timestamps, Gorilla-style XOR for floats, dictionary for repeated text), and min/max metadata lets queries skip batches. The segmentby column should be what your queries filter on; the orderby column, usually time descending, decides the order within a batch. Continuous aggregates materialise time_bucket rollups and refresh only the buckets whose raw data changed.
The alternatives each own a niche. Prometheus is a time-series database for operational metrics with a pull model and its own query language, and the Observability course covers it; it is not where business data lives. ClickHouse, from the columnar chapter, handles time series at billions of rows per day with the same compression ideas and none of Postgres’s transactional semantics. InfluxDB is a purpose-built option with its own ecosystem. Plain Postgres with monthly partitions and a BRIN index carries modest volumes, around tens of millions of rows a day, a long way. TimescaleDB is the step to take when you want compression and rollups without leaving SQL, joins and your existing backups.
Vector: nearest neighbours in high dimensions
An embedding model turns a product description, an image or a support ticket into a vector of a few hundred to a few thousand floats, placed so that similar things are close. The AI course’s embeddings chapter builds them on the shop with a local model and stores them in product_embeddings. The database question is the search: find the 10 vectors nearest to this one.
Exact search compares the query with every vector. For 100,000 vectors of 64 dimensions that is 6.4 million multiply-adds, tens of milliseconds; for 10 million vectors of 768 dimensions it is seconds. B-trees do not help, because no ordering of high-dimensional points keeps neighbours together. So vector indexes are approximate (ANN): they give up a little recall, the fraction of true nearest neighbours returned, for orders of magnitude in speed.
HNSW (Malkov and Yashunin, 2016) is the index most systems use. It builds a graph in which each vector links to about m near neighbours, and stacks sparser copies of the graph in layers: each vector appears in layer 0, and in each higher layer with exponentially falling probability. A search starts at the top layer, greedily walks towards the query, drops a layer, and repeats; at the bottom it keeps a candidate list of size ef_search and returns the best. Search cost grows roughly with the logarithm of the collection size. pgvector’s knobs and defaults: m = 16, ef_construction = 64 at build time, hnsw.ef_search = 40 at query time. Higher values raise recall and cost. The graph should fit in memory: build time collapses when it no longer fits in maintenance_work_mem, and query latency suffers when it does not fit in shared buffers and the page cache. IVFFlat, the other pgvector index, clusters vectors into lists and searches the probes nearest clusters; it builds faster and uses less memory, and its recall depends on having built it after the data was loaded.
The trap is filtering. WHERE category = 'software' ORDER BY embedding <-> $1 LIMIT 10 runs the ANN search first and filters afterwards. With ef_search = 40 and a filter that matches 2% of rows, about one candidate survives. Before pgvector 0.8.0 the query silently returned fewer rows than asked for. Since 0.8.0, hnsw.iterative_scan (strict_order or relaxed_order) keeps searching until enough rows pass the filter or hnsw.max_scan_tuples (20,000 by default) is reached. For a few distinct filter values, partial indexes per value work better; for many, partitioning by the filter column does.
Dedicated vector databases (Qdrant, Milvus, Weaviate, Pinecone) and the vector features of OpenSearch earn their place at the top end: hundreds of millions of vectors, quantisation to cut memory four to thirty-two times, filtering built into the graph search, and serving that scales independently of your transactional database. Below that, pgvector keeps the vectors next to the rows they describe, in the same transaction, with the same backups, and joins them with ordinary filters. The AI course’s vector indexes chapter, in module A3, measures recall against latency in depth.
When to bolt one on
Every specialist engine you add is a derived store: a copy of data whose source of truth is elsewhere. That has a fixed cost no benchmark shows:
- A sync path. Dual writes from the application lose updates when one write fails; the reliable patterns are change data capture or a transactional outbox, covered in module D4’s change data capture chapter. Either way there is now a pipeline to run.
- Lag and staleness. The copy is behind by the pipeline’s latency plus, for search, the refresh interval. A user who edits a product and searches for it may not find it. Monitor the lag as you would replication lag.
- A rebuild procedure. Mappings, analysers and index parameters change; the copy gets corrupted or drifts. You need to rebuild it from the source in hours, not weeks, and to have done it once before you need it.
- Another system to operate. Upgrades, capacity, backups (or a decision that the rebuild is the backup), security, on-call.
A useful rule: stay in Postgres while the extension meets the requirement at your volume with headroom, and the workload does not threaten the primary. Bolt on a specialist engine when one of three things is true: the extension cannot express the requirement (learning-to-rank relevance, billion-vector quantised search); the volume is past what one Postgres node handles for that workload; or the query load must be isolated from transactions and a read replica is not enough. Then add one engine at a time, for one workload, with the sync path designed before the first query is written.
| workload | in Postgres | bolt on when |
|---|---|---|
| keyword search | tsvector + GIN, pg_trgm, pg_search |
relevance is a product, facets over large result sets, many languages |
| graph | recursive CTEs, Apache AGE | deep interactive traversals over large graphs |
| time series | partitioning + BRIN, TimescaleDB | billions of rows a day, or metrics that belong in Prometheus |
| vector | pgvector HNSW / IVFFlat | hundreds of millions of vectors, heavy filtered ANN, independent scaling |
Search and graph run in their own containers and are loaded from the shop; time series runs in TimescaleDB with generated data; vectors run in the shop itself, whose image already ships pgvector 0.8.7. On Linux, OpenSearch needs sudo sysctl -w vm.max_map_count=262144 once; Docker Desktop already sets it.
1. Start the specialist stack. Create labs/databases/d3-specialist/compose.yaml:
# labs/databases/d3-specialist/compose.yaml — the specialist engines for databases/specialist-engines.
# docker compose -f d3-specialist/compose.yaml up -d (from labs/databases)
# Host ports: OpenSearch 9200, Apache AGE 5460, TimescaleDB 5461. About 2.5 GB of RAM.
name: atlas-specialist
x-pg-env: &pg-env
POSTGRES_USER: atlas
POSTGRES_PASSWORD: atlas
POSTGRES_DB: shop
services:
opensearch:
image: opensearchproject/opensearch:3.8.0
environment:
discovery.type: single-node
DISABLE_SECURITY_PLUGIN: "true" # lab only: plain HTTP, no users
DISABLE_INSTALL_DEMO_CONFIG: "true"
OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m"
ports: ["9200:9200"]
age:
image: apache/age:release_PG17_1.7.0 # Postgres 17 with AGE preloaded
environment: *pg-env
ports: ["5460:5432"]
volumes:
- ./age:/tmp/age:ro # AGE 1.7 loads CSV files only from /tmp/age
tsdb:
image: timescale/timescaledb:2.30.2-pg17
environment: *pg-env
ports: ["5461:5432"]mkdir -p d3-specialist/age
docker compose -f d3-specialist/compose.yaml up -d
until curl -s localhost:9200 >/dev/null; do sleep 2; done; curl -s localhost:9200 | grep '"number"'"number" : "3.8.0". The age and tsdb containers are ordinary Postgres 17 servers with one extension each.2. Search in Postgres first.
docker compose exec db psql -U atlas -d shopSELECT count(*) FROM products WHERE to_tsvector('english', name || ' ' || category) @@ websearch_to_tsquery('english', 'deluxe widget');
SELECT count(*) FROM products WHERE to_tsvector('english', name || ' ' || category) @@ websearch_to_tsquery('english', 'delux widgit');
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT id, name, round(similarity(name, 'delux widgit')::numeric, 2) AS sim
FROM products WHERE name % 'delux widgit' ORDER BY sim DESC LIMIT 3;0: the prediction above. The trigram query finds Deluxe Widget products with similarity around 0.4, above pg_trgm.similarity_threshold’s default of 0.3. Two different mechanisms, both in Postgres: stemmed lexemes for language, trigrams for spelling. Without an index both are sequential scans, which at 5,000 rows does not matter; a GIN index on each expression makes them fast at millions.3. Index the catalogue in OpenSearch. Create the index with an explicit mapping, then bulk-load it from Postgres as NDJSON, one action line and one document line per product:
curl -s -XPUT localhost:9200/products -H 'Content-Type: application/json' -d '{
"settings": { "number_of_shards": 1, "number_of_replicas": 0 },
"mappings": { "properties": {
"name": { "type": "text" }, "category": { "type": "keyword" },
"price_cents": { "type": "integer" }, "sku": { "type": "keyword" } } } }'
docker compose exec -T db psql -U atlas -d shop -Atc "
SELECT line FROM products p, LATERAL (VALUES
(1, json_build_object('index', json_build_object('_id', p.id))::text),
(2, json_build_object('name', p.name, 'category', p.category, 'price_cents', p.price_cents, 'sku', p.sku)::text)) v(n, line)
ORDER BY p.id, v.n" > d3-specialist/products.ndjson
head -2 d3-specialist/products.ndjson
curl -s -XPOST 'localhost:9200/products/_bulk?refresh=true' -H 'Content-Type: application/x-ndjson' \
--data-binary @d3-specialist/products.ndjson | head -c 60; echo
curl -s localhost:9200/products/_count{"acknowledged":true,...} for the index. The first two NDJSON lines are {"index" : {"_id" : 1}} and product 1’s document. The bulk response starts {"took":...,"errors":false, and _count reports 5000. Replicas are 0 because there is one node; a replica on the same node would protect nothing.4. Fuzzy search with facets, and the analyser behind it.
curl -s 'localhost:9200/products/_search?pretty' -H 'Content-Type: application/json' -d '{
"size": 3, "_source": ["name", "category"],
"query": { "match": { "name": { "query": "delux widgit", "fuzziness": "AUTO" } } },
"aggs": { "categories": { "terms": { "field": "category", "size": 3 } } } }'
curl -s 'localhost:9200/products/_analyze?pretty' -H 'Content-Type: application/json' \
-d '{ "field": "name", "text": "Heavy-Duty Widgets 42" }'hits.total.value is around 800: a match query ORs its terms, so every product with a term within edit distance of delux or widgit matches (Deluxe, Widget), and products that match both rank first, all named Deluxe Widget N, with a _score from BM25. aggregations.categories.buckets gives the top three categories among the matches with their counts: facets, computed in the same request. _analyze shows the standard analyser’s tokens: heavy, duty, widgets, 42. It lowercases and splits on the hyphen but does not stem; an english analyser on the field would turn widgets into widget. Choosing that per field is relevance work.5. Near-real-time. Index one document without forcing a refresh and search at once, then after a second:
curl -s -XPUT localhost:9200/products/_doc/900001 -H 'Content-Type: application/json' \
-d '{"name": "Quantum Toaster 900001", "category": "kitchen", "price_cents": 4999}' | head -c 80; echo
curl -s 'localhost:9200/products/_search?q=name:quantum' | grep -o '"total":{[^}]*}'
sleep 1.5
curl -s 'localhost:9200/products/_search?q=name:quantum' | grep -o '"total":{[^}]*}'"result":"created". The first search usually reports "value":0: the document is in Lucene’s buffer, not yet in a searchable segment. After the refresh interval it reports "value":1. If the first search already finds it, a refresh happened in between; run it again with a new id. A Postgres read after a commit never behaves like this.6. Load the purchase graph into Apache AGE. Export vertices and edges from the shop as CSV into the directory the container mounts at /tmp/age:
docker compose exec -T db psql -U atlas -d shop -c "\copy (SELECT id, name, category FROM products ORDER BY id) TO STDOUT WITH CSV HEADER" > d3-specialist/age/products.csv
docker compose exec -T db psql -U atlas -d shop -c "\copy (SELECT id FROM customers ORDER BY id) TO STDOUT WITH CSV HEADER" > d3-specialist/age/customers.csv
docker compose exec -T db psql -U atlas -d shop -c "\copy (SELECT DISTINCT o.customer_id AS start_id, 'Customer' AS start_vertex_type, i.product_id AS end_id, 'Product' AS end_vertex_type FROM order_items i JOIN orders o ON o.id = i.order_id ORDER BY 1, 3) TO STDOUT WITH CSV HEADER" > d3-specialist/age/bought.csv
wc -l d3-specialist/age/*.csv
docker compose -f d3-specialist/compose.yaml exec age psql -U atlas -d shopLOAD 'age';
SET search_path = ag_catalog, "$user", public;
SELECT create_graph('shop_graph');
SELECT load_labels_from_file('shop_graph', 'Product', 'products.csv', true, true);
SELECT load_labels_from_file('shop_graph', 'Customer', 'customers.csv', true, true);
SELECT create_elabel('shop_graph', 'BOUGHT');
SELECT load_edges_from_file('shop_graph', 'BOUGHT', 'bought.csv');
CREATE INDEX ON shop_graph."BOUGHT" (start_id);
CREATE INDEX ON shop_graph."BOUGHT" (end_id);
\d shop_graph."BOUGHT"true in each label load parses values as typed agtype, so id is a number, not a string. \d shows what a graph is in AGE: a table with id, start_id, end_id and properties, and the two indexes you added. A hop is a join on those columns.7. Customers who bought product 42 also bought. Still in the AGE session, then the same question in SQL on the shop:
\timing on
SELECT * FROM cypher('shop_graph', $$
MATCH (p:Product {id: 42})<-[:BOUGHT]-(:Customer)-[:BOUGHT]->(o:Product)
WHERE o.id <> 42
RETURN o.id, o.name, count(*) AS together
ORDER BY together DESC, o.id LIMIT 5
$$) AS (id agtype, name agtype, together agtype);docker compose exec db psql -U atlas -d shop -c "\timing on" -c "
SELECT i2.product_id, count(DISTINCT o1.customer_id) AS together
FROM order_items i1 JOIN orders o1 ON o1.id = i1.order_id
JOIN orders o2 ON o2.customer_id = o1.customer_id JOIN order_items i2 ON i2.order_id = o2.id
WHERE i1.product_id = 42 AND i2.product_id <> 42
GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 5"8. Time series in TimescaleDB.
docker compose -f d3-specialist/compose.yaml exec tsdb psql -U atlas -d shopCREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE stock_levels (ts timestamptz NOT NULL, product_id int NOT NULL, on_hand int NOT NULL);
SELECT create_hypertable('stock_levels', by_range('ts', INTERVAL '1 day'));
\timing on
INSERT INTO stock_levels
SELECT ts, p, greatest(0, 500 + (200 * sin(extract(epoch FROM ts) / 86400 * 2 * pi() + p))::int + (random() * 40)::int - 20)
FROM generate_series(now() - INTERVAL '14 days', now(), INTERVAL '1 minute') AS ts, generate_series(1, 100) AS p;
SELECT count(*) AS chunks FROM show_chunks('stock_levels');
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT time_bucket(INTERVAL '1 hour', ts) AS hour, avg(on_hand) FROM stock_levels
WHERE product_id = 7 AND ts > now() - INTERVAL '1 day' GROUP BY 1 ORDER BY 1;Chunks excluded during startup), because now() is only known when the query starts. This is partitioning from the partitioning chapter with the partitions created for you.9. Compress, roll up, expire.
SELECT pg_size_pretty(hypertable_size('stock_levels'));
ALTER TABLE stock_levels SET (timescaledb.compress, timescaledb.compress_segmentby = 'product_id', timescaledb.compress_orderby = 'ts DESC');
SELECT count(compress_chunk(c)) FROM show_chunks('stock_levels', older_than => INTERVAL '1 day') AS c;
SELECT pg_size_pretty(before_compression_total_bytes) AS before, pg_size_pretty(after_compression_total_bytes) AS after
FROM hypertable_compression_stats('stock_levels');
CREATE MATERIALIZED VIEW stock_hourly WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 hour', ts) AS hour, product_id, min(on_hand) AS lo, max(on_hand) AS hi, avg(on_hand) AS mean
FROM stock_levels GROUP BY 1, 2;
SELECT drop_chunks('stock_levels', older_than => INTERVAL '7 days');
SELECT (SELECT count(*) FROM stock_levels) AS raw_rows, (SELECT count(*) FROM stock_hourly) AS hourly_rows;before in the same range and an after of a few MB to around 20 MB: an order of magnitude or more, because a product’s readings form one batch in which timestamps are evenly spaced and values change slowly. The continuous aggregate materialises about 33,600 hourly rows. drop_chunks removes the chunks older than a week by dropping whole tables, and afterwards the raw table has about half its rows while the hourly rollup still covers all 14 days: downsample, then expire.10. Vectors in the shop with pgvector. Real embeddings come from the AI course; here you generate synthetic 64-dimensional vectors, clustered by category, so the index behaviour is visible without a model:
docker compose exec db psql -U atlas -d shopCREATE EXTENSION IF NOT EXISTS vector;
SELECT setseed(0.7);
CREATE TEMP TABLE centroids AS
SELECT c.category, array_agg((random() - 0.5)::real ORDER BY d) AS v
FROM (SELECT DISTINCT category FROM products ORDER BY 1) c, generate_series(1, 64) d
GROUP BY c.category;
CREATE TABLE product_vecs AS
SELECT row_number() OVER () AS id, p.id AS product_id, p.category,
(SELECT array_agg(c.v[d] + ((random() - 0.5) * 0.8)::real ORDER BY d) FROM generate_series(1, 64) d)::vector(64) AS embedding
FROM products p JOIN centroids c USING (category),
generate_series(1, greatest(1, 100000 / (SELECT count(*) FROM products))::int) AS copy;
ALTER TABLE product_vecs ADD PRIMARY KEY (id);
ANALYZE product_vecs;
\timing on
EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM product_vecs
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10;
SET maintenance_work_mem = '256MB';
CREATE INDEX product_vecs_hnsw ON product_vecs USING hnsw (embedding vector_l2_ops);
EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM product_vecs
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10;Seq Scan under a top-N Sort, tens of milliseconds: exact search. The HNSW build takes tens of seconds. The second plan is an Index Scan using product_vecs_hnsw and runs in about a millisecond. That is the trade you are about to measure.11. Measure recall, then break it with a filter.
CREATE TEMP TABLE approx AS SELECT id FROM product_vecs
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10;
SET enable_indexscan = off;
CREATE TEMP TABLE exact AS SELECT id FROM product_vecs
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10;
RESET enable_indexscan;
SELECT count(*) AS found_of_10 FROM approx JOIN exact USING (id);
SELECT category AS rare FROM products GROUP BY 1 ORDER BY count(*), 1 LIMIT 1 \gset
SELECT :'rare' AS rare, count(*) FROM product_vecs WHERE category = :'rare';
SET enable_seqscan = off;
SELECT count(*) FROM (SELECT id FROM product_vecs WHERE category = :'rare'
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10) t;
SET hnsw.iterative_scan = relaxed_order;
SELECT count(*) FROM (SELECT id FROM product_vecs WHERE category = :'rare'
ORDER BY embedding <-> (SELECT embedding FROM product_vecs WHERE id = 1) LIMIT 10) t;
RESET enable_seqscan; RESET hnsw.iterative_scan;ef_search of 40. The rarest category holds about 1% of the vectors, or less. With the index forced and no iterative scan, the filtered query returns far fewer than 10 rows, usually 0: the 40 candidates all sit in product 1’s own category cluster and the filter discards every one. With relaxed_order it returns 10, because the scan keeps walking the graph until enough rows pass. enable_seqscan = off is there because, left alone, the planner may choose an exact scan for a selective filter, which is the correct answer and hides the problem.old=$(docker compose exec -T db psql -U atlas -d shop -Atc "SELECT name FROM products WHERE id = 77"), then rename it: docker compose exec db psql -U atlas -d shop -c "UPDATE products SET name = 'Discontinued Item 77' WHERE id = 77". Then search OpenSearch for it: curl -s 'localhost:9200/products/_search?q=name:discontinued' | grep -o '"total":{[^}]*}' reports 0, and a search for product 77’s old name still finds it. Postgres committed; the search index is a copy that nothing updates. Every specialist engine in this lab now disagrees with the shop until something carries changes across, which is the sync path the chapter says to design first. Tear down with docker compose -f d3-specialist/compose.yaml down -v and, in the shop, put the name back and drop the vectors: docker compose exec db psql -U atlas -d shop -c "UPDATE products SET name = '$old' WHERE id = 77" -c "DROP TABLE product_vecs". The pg_trgm and vector extensions stay; they cost nothing unused, and the AI course enables vector anyway.The shop has 50,000 products and about 50 searches per second at peak on a Postgres primary at 30% CPU. Search today is ILIKE on the name. Product wants typo tolerance, facets by category and price, and a 'did you mean'. The merchandising team mentions it might want synonyms and boosting by sales 'later'. The team has no one who has run Elasticsearch or OpenSearch. What do you build?
- PAPER Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs Yu. A. Malkov, D. A. Yashunin, 2016
The HNSW paper. Explains why layered small-world graphs give logarithmic search, what M and efConstruction trade, and the neighbour-selection heuristic every implementation copies. Read: sections 1 to 4 (the algorithm and parameter choices); skip the comparisons in section 5 unless you are choosing between libraries.
- CODE pgvector README
The operators, HNSW and IVFFlat options with their defaults, iterative index scans for filtering, and the sections on build performance and memory. Read 'Filtering' and 'Iterative Index Scans' before you put a WHERE clause next to an ANN query.
- DOC PostgreSQL 17: Full Text Search
tsvector, tsquery, parsers, dictionaries and ranking, and the GIN and GiST index trade-offs in section 12.9. Enough to decide whether Postgres search covers your requirement before you add an engine.
- DOC OpenSearch documentation
Start with the sections on mappings, text analysis and the match and fuzzy queries, then aggregations. The install page for Docker covers the settings used in the lab; skip the plugins until you need one.
- DOC Apache AGE manual
How graphs map onto Postgres schemas and tables, the Cypher subset AGE supports, and the CSV loaders used in the lab. Read the 'Graphs' and 'MATCH' sections; the rest is reference.
- DOC Neo4j: Graph data modeling
How to decide what is a node, a relationship and a property, with worked examples. Useful even if you stay in Postgres, because it shows which questions a graph shape makes easy.
- CODE TimescaleDB source and README
Hypertables, compression and continuous aggregates from the source, with links to the current documentation. The SQL API files under sql/ are the authoritative list of functions and their arguments for the version you run.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.