Otimização de buscas filtradas
Otimize consultas do pgvector que combinam similaridade vetorial com filtros de metadados usando estratégias de indexação parcial e composta.
Otimização de buscas filtradas é uma aula grátis de Vector Databases: Pinecone, Weaviate & pgvector no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Vector Databases: Pinecone, Weaviate & pgvector, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Vector Databases: Pinecone, Weaviate & pgvector inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
The Filtered Search Problem
Real queries often combine a vector search with a metadata WHERE filter. Naive combinations can defeat the vector index and become slow.
SELECT id FROM docs
WHERE category = 'news'
ORDER BY embedding <=> '[...]'::vector
LIMIT 10;Why Filters Hurt Recall
ANN indexes return approximate nearest neighbors before the filter applies. If most candidates are filtered out, you may get fewer than LIMIT results — this is over-filtering.
Increasing Search Scope
Raise hnsw.ef_search (or IVFFlat probes) so the index scans more candidates before filtering, improving recall on selective filters.
SET hnsw.ef_search = 100;Partial Indexes
For a common, low-cardinality filter value, build a partial index covering only those rows. The index then perfectly matches the filtered subset.
CREATE INDEX ON docs
USING hnsw (embedding vector_cosine_ops)
WHERE category = 'news';When Partial Indexes Win
Partial indexes shine when:
- Filter values are few and known
- Each subset is large enough to matter
- Queries almost always include that filter
B-tree Support Indexes
For high-cardinality filters, add a regular B-tree index on the metadata column. The planner can combine it with the vector scan.
CREATE INDEX ON docs (category);
CREATE INDEX ON docs (published_at);Iterative Index Scans
Newer pgvector supports iterative scans, which keep fetching from the index until enough rows pass the filter. Enable it to avoid under-filling results.
SET hnsw.iterative_scan = 'relaxed_order';Pre-filtering vs Post-filtering
Pre-filter: narrow rows first, then vector search (good for very selective filters). Post-filter: vector search first, then filter (good for broad filters). Test both.
Measuring with EXPLAIN
Always confirm the plan. Look for Index Scan using ... hnsw rather than a sequential scan.
EXPLAIN ANALYZE
SELECT id FROM docs
WHERE category = 'news'
ORDER BY embedding <=> '[...]'::vector
LIMIT 10;Combining Strategies
A robust setup often uses partial indexes for hot filters, B-tree indexes for the rest, and a tuned ef_search with iterative scans as a safety net.
Checklist
Before shipping a filtered vector query:
- Verify index usage with EXPLAIN
- Confirm you reliably get LIMIT results
- Benchmark latency at p95
Quick Check
Test filtered search knowledge.
Recap
You learned why filters challenge ANN indexes and how partial indexes, B-tree support indexes, ef_search tuning, and iterative scans keep filtered vector queries both fast and accurate.
Perguntas Frequentes
A aula “Otimização de buscas filtradas” é grátis?
Sim — o texto completo de “Otimização de buscas filtradas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Vector Databases: Pinecone, Weaviate & pgvector, atualize para CoddyKit PRO. O curso de Vector Databases: Pinecone, Weaviate & pgvector inclui 4 aulas no total.
O que vou aprender em “Otimização de buscas filtradas”?
Otimize consultas do pgvector que combinam similaridade vetorial com filtros de metadados usando estratégias de indexação parcial e composta. Você pratica Vector Databases: Pinecone, Weaviate & pgvector com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Vector Databases: Pinecone, Weaviate & pgvector?
Nenhuma experiência prévia é necessária. Vector Databases: Pinecone, Weaviate & pgvector no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Otimização de buscas filtradas”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Vector Databases: Pinecone, Weaviate & pgvector?
Sim. Cada aula de Vector Databases: Pinecone, Weaviate & pgvector inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Indexação IVFFlat para Velocidade
- Indexação HNSW para Revocação
- Ajuste do Desempenho de Consultas
- Otimização de buscas filtradas