Sub topic 16
Smaller and sparse representations: halfvec, sparsevec, bit
This chapter assumes you can build and query a vector column, create HNSW and IVFFlat indexes, and match operator classes to operators. Here you will learn three other types that pgvector provides. They reduce storage and index size, or represent embeddings that are mostly zeros. The type names and operators below are for pgvector 0.7.0 or later.
Why other types exist
A vector column stores each dimension as a 4-byte float. A 1,536-dimension embedding takes about 6 KB per row, and an HNSW index over it adds more. At millions of rows, memory and disk become the main cost, because an index that no longer fits in RAM slows queries sharply.
pgvector offers three ways to shrink the data:
halfvecstores 2 bytes per dimension.bitstores 1 bit per dimension.sparsevecstores only the non-zero dimensions.
The table compares them with vector. n is the number of dimensions and nnz is the number of non-zero elements.
| Type | Storage per value | Max dimensions stored | Max indexed |
|---|---|---|---|
| `vector` | 4n + 8 bytes | 16,000 | 2,000 |
| `halfvec` | 2n + 8 bytes | 16,000 | 4,000 |
| `bit` | n/8 + 8 bytes (rounded up) | 64,000 | 64,000 |
| `sparsevec` | 8 × nnz + 16 bytes | 16,000 non-zero elements | 1,000 non-zero elements |
halfvec: half-precision floats
A halfvec keeps the same layout as a vector but stores each number in 16 bits. Most embedding models produce values where this loses little useful information, so rankings change only slightly. The storage and index size are roughly halved. You also get a higher index limit. A 3,072-dimension embedding cannot be indexed as a vector, but it can be indexed as a halfvec.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE half_items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding halfvec(3)
);
INSERT INTO half_items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4,5,6]'),
('c', '[1,1,1]');
CREATE INDEX half_items_hnsw
ON half_items USING hnsw (embedding halfvec_cosine_ops);
SELECT id, content
FROM half_items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The operators are the same as for vector. Only the operator class name changes: halfvec_l2_ops, halfvec_cosine_ops, halfvec_ip_ops, and halfvec_l1_ops.
Indexing an existing vector column as halfvec
You can keep full-precision vectors in the table and index a half-precision cast of them. This is an expression index. The index is smaller, and the table keeps the original values.
CREATE INDEX items_half_expr_hnsw
ON items USING hnsw ((embedding::halfvec(3)) halfvec_cosine_ops);
SELECT id, content
FROM items
ORDER BY embedding::halfvec(3) <=> '[3,1,2]'::halfvec(3)
LIMIT 5;The query must repeat the same expression, including the dimension in halfvec(3). If the expression differs, the planner cannot use the index, and you silently get a sequential scan.
sparsevec: mostly-zero vectors
Some models, such as learned sparse retrievers and bag-of-words encoders, produce vectors with tens of thousands of dimensions where almost every value is zero. Storing every zero wastes space. A sparsevec stores only the non-zero positions and values.
The text format is {index:value,index:value}/dimensions. Indexes start at 1, not 0.
CREATE TABLE sparse_items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding sparsevec(5)
);
INSERT INTO sparse_items (content, embedding) VALUES
('a', '{1:1,3:2,5:3}/5'),
('b', '{2:4,4:5}/5'),
('c', '{1:1,2:1}/5');
CREATE INDEX sparse_items_hnsw
ON sparse_items USING hnsw (embedding sparsevec_l2_ops);
SELECT id, content
FROM sparse_items
ORDER BY embedding <-> '{1:3,3:1,5:2}/5'
LIMIT 5;The vector a above has dimension 5 but only 3 stored elements. All distance operators work, with operator classes named sparsevec_l2_ops, sparsevec_cosine_ops, sparsevec_ip_ops, and sparsevec_l1_ops. The index limit counts non-zero elements, not total dimensions. A vector with 30,000 dimensions and 200 non-zero entries can be indexed.
bit: binary vectors and Hamming distance
A bit(n) column stores n bits. Distance between two bit strings is the number of positions that differ (Hamming distance), or a set-overlap measure (Jaccard distance).
| Operator | Meaning | HNSW operator class | IVFFlat operator class |
|---|---|---|---|
| `<~>` | Hamming distance | `bit_hamming_ops` | `bit_hamming_ops` |
| `<%>` | Jaccard distance | `bit_jaccard_ops` | not supported |
CREATE TABLE bit_items (
id bigserial PRIMARY KEY,
embedding bit(3)
);
INSERT INTO bit_items (embedding) VALUES ('000'), ('111'), ('101');
CREATE INDEX bit_items_hnsw
ON bit_items USING hnsw (embedding bit_hamming_ops);
SELECT id, embedding <~> '101' AS hamming
FROM bit_items
ORDER BY embedding <~> '101'
LIMIT 5;Binary quantization with re-ranking
The most common use of bit is to compress a float embedding. The function binary_quantize turns each dimension into 1 if it is positive and 0 otherwise. A 1,536-dimension vector becomes 192 bytes, about 32 times smaller than the original.
Quantization loses a lot of information, so the bit index only finds candidates. You then re-rank those candidates with the full-precision vectors.
CREATE INDEX items_bq_hnsw
ON items USING hnsw ((binary_quantize(embedding)::bit(3)) bit_hamming_ops);
SELECT id, content
FROM (
SELECT id, content, embedding
FROM items
ORDER BY binary_quantize(embedding)::bit(3)
<~> binary_quantize('[1,-2,3]'::vector)
LIMIT 20
) candidates
ORDER BY embedding <=> '[1,-2,3]'
LIMIT 5;The inner query fetches 20 candidates by Hamming distance using the index. The outer query sorts them by exact cosine distance and keeps 5. A larger inner LIMIT raises recall and costs more time. Binary quantization works best with high-dimensional embeddings, where the sign pattern still carries enough signal. With 3 dimensions, as in this example, it is only a demonstration.
Trade-offs and common errors
- Measure recall after every change. Use the exact-versus-indexed comparison from the recall chapter.
halfvecusually changes results very little.bitchanges them a lot unless you re-rank. - Do not mix types in one comparison. Comparing a
vectorcolumn with ahalfvecliteral raises an operator error. Cast one side explicitly. - Dimensions must match.
sparsevec(5)rejects a value that declares/6. Index positions beyond the declared dimension are also rejected. - Remember 1-based sparse indexes. An off-by-one error gives valid but wrong vectors, with no error message.
- Choose the operator class for the type.
vector_cosine_opsdoes not work on ahalfveccolumn. Usehalfvec_cosine_ops. - Check the limits. A
vector(3072)column can be stored but not indexed. Ahalfvec(3072)column can be indexed.
Exercise
Your table has a vector(3072) column, and CREATE INDEX ... USING hnsw (embedding vector_cosine_ops) fails because of the 2,000-dimension index limit. Write the index statement that works without changing the column type, and the matching ORDER BY clause for a query vector '[...]'.
Show answer
Index a half-precision cast: CREATE INDEX ON items USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);. The query must use the same expression: ORDER BY embedding::halfvec(3072) <=> '[...]'::halfvec(3072). Halfvec indexes allow up to 4,000 dimensions, and the table keeps the full-precision values.
Exercise
Why does a binary-quantization query use a subquery with a larger inner LIMIT and an outer re-ranking step?
Show answer
Binary quantization keeps only the sign of each dimension, so Hamming distance is a rough approximation of the true distance. The inner query uses the compact bit index to find a pool of candidates cheaply. The outer query re-sorts that pool by the full-precision distance, which recovers most of the recall lost to quantization.