Database / pgvector basics Interview Questions
How do you handle vector dimensionality mismatches in pgvector?
pgvector enforces dimension consistency within typed columns - you cannot insert a 1024-dimensional vector into a VECTOR(1536) column. Understanding how to handle this prevents common insertion and query errors.
-- FIXED-dimension column (recommended when all vectors have same size) CREATE TABLE docs (embedding VECTOR(1536)); -- enforces exactly 1536 dims -- ERROR: dimension mismatch INSERT INTO docs (embedding) VALUES ('[1,2,3]'); -- ERROR: expected 1536 dims INSERT INTO docs (embedding) VALUES (ARRAY_FILL(0.0::float4, ARRAY[1024])::vector); -- ERROR: expected 1536 dimensions, got 1024 -- VARIABLE-dimension column (no constraint) CREATE TABLE docs_flex (embedding VECTOR); -- accepts any dimension INSERT INTO docs_flex VALUES ('[1,2,3]'); -- OK: 3 dims INSERT INTO docs_flex VALUES ('[1,2,3,4,5]');-- OK: 5 dims -- CAVEAT: you cannot create a standard index on variable-dim columns! -- Because all rows in the index must have the same dimensionality -- Use a PARTIAL INDEX or EXPRESSION INDEX on a specific dimension: CREATE INDEX ON docs_flex USING hnsw ((embedding::vector(1536)) vector_cosine_ops) WHERE vector_dims(embedding) = 1536; -- Check dimensions of a stored vector: SELECT vector_dims(embedding) FROM docs_flex LIMIT 5; -- Find rows with unexpected dimension count: SELECT id, vector_dims(embedding) AS dims FROM docs_flex WHERE vector_dims(embedding) != 1536;
More Related questions...