Database / pgvector basics Interview Questions
What is halfvec and when should you use it to reduce storage costs?
halfvec is a pgvector data type that stores each vector dimension as a 16-bit (half-precision) float instead of the standard 32-bit float. This halves storage requirements at the cost of a small precision reduction.
-- Standard vector: 4 bytes per dimension -- halfvec: 2 bytes per dimension (50% storage reduction) -- Create table with halfvec column: CREATE TABLE documents_compact ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding HALFVEC(1536) ); -- For 1M documents at 1536 dimensions: -- vector(1536): 1,000,000 * 1536 * 4 bytes = ~6 GB -- halfvec(1536): 1,000,000 * 1536 * 2 bytes = ~3 GB -- Saving: ~3 GB per million documents -- Insert (same syntax as vector): INSERT INTO documents_compact (content, embedding) VALUES ('Example', '[0.1, 0.2, 0.3, ...]'); -- Values are automatically rounded to 16-bit precision -- HNSW index for halfvec: CREATE INDEX ON documents_compact USING hnsw (embedding halfvec_cosine_ops); -- note: halfvec_cosine_ops -- Convert from vector to halfvec: SELECT embedding::halfvec(1536) FROM documents WHERE id = 1; -- When to use halfvec: -- Storage cost is significant (millions of documents, high dimensions) -- Slight precision loss is acceptable (typically negligible for text) -- When to stick with vector: -- Highest accuracy required (scientific data, financial embeddings) -- Precision is critical
| Operator class | Distance |
|---|---|
| halfvec_l2_ops | L2 distance <-> |
| halfvec_cosine_ops | Cosine distance <=> |
| halfvec_ip_ops | Inner product <#> |
| halfvec_l1_ops | L1 distance <+> |
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...
