Database / pgvector basics Interview Questions
What are partial indexes in pgvector and when should you use them?
A partial index is a pgvector (or PostgreSQL) index that covers only a subset of rows, defined by a WHERE clause at index creation. This is useful for filtering common values efficiently or indexing only rows that have embeddings.
-- Partial index: only index documents in a specific category CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WHERE category = 'technical'; -- index only 'technical' rows -- Queries using the same filter benefit from the smaller index: SELECT id, content FROM documents WHERE category = 'technical' -- matches the partial index ORDER BY embedding <=> '[...]' LIMIT 5; -- uses the partial index -- Much faster: index is smaller and focused -- Partial index for published articles only: CREATE INDEX ON articles USING hnsw (embedding vector_cosine_ops) WHERE is_published = TRUE; -- Partial index to exclude NULL embeddings: CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WHERE embedding IS NOT NULL; -- Useful if some rows have no embedding yet -- Multiple partial indexes for different categories: CREATE INDEX idx_tech ON docs USING hnsw (embedding vector_cosine_ops) WHERE category = 'tech'; CREATE INDEX idx_legal ON docs USING hnsw (embedding vector_cosine_ops) WHERE category = 'legal'; -- Each index is smaller and faster for its category -- PostgreSQL uses a partial index only when the query WHERE clause -- includes the index's WHERE condition
More Related questions...