Database / pgvector basics Interview Questions
What is the IVFFlat index in pgvector and how does it compare to HNSW?
IVFFlat (Inverted File Flat) is pgvector's other index type. It clusters vectors into lists using k-means, then searches only the closest lists to the query vector. It was the original pgvector index type but is now generally considered secondary to HNSW for most workloads.
-- Create an IVFFlat index -- IMPORTANT: table must have data before creating the index -- (k-means clustering needs existing vectors to learn from) -- For L2 distance: CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100); -- number of clusters/lists -- For cosine distance: CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); -- Guideline for lists parameter: -- rows <= 1,000,000: lists = sqrt(rows) e.g. sqrt(100000) ~ 316 -- rows > 1,000,000: lists = rows / 1000 e.g. 2000000/1000 = 2000 -- Tune QUERY recall at query time: SET ivfflat.probes = 10; -- number of lists to search (default 1) -- Higher probes = better recall, slower queries -- probes = lists gives exact search (defeats purpose of index) SELECT id FROM items ORDER BY embedding <-> '[...]' LIMIT 5; RESET ivfflat.probes;
| Aspect | HNSW | IVFFlat |
|---|---|---|
| Build time | Slower (builds complex graph) | Faster (simpler k-means clustering) |
| Build memory | More memory required | Less memory required |
| Query speed | Generally faster | Generally slower at same recall |
| Recall | Better recall at same speed | Needs more probes to match HNSW recall |
| Requires data first | No (can build on empty table) | Yes (needs vectors to cluster) |
| Recommended for | Most workloads | Memory-constrained or faster build needed |
| Query tuning | hnsw.ef_search | ivfflat.probes |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
