Embed documents, store in pgvector, and implement cosine + ANN search with metadata filtering.
From text to filtered search results in pgvector
Step 1 of 5
Embed text
The embedding model turns each document into a vector. The size of the database column has to match the size of the vector.
Step 2 of 5
Insert row
Store the text, its vector and metadata such as the owning team in one row, so they can never drift apart.
Step 3 of 5
Build index
An HNSW index lets pgvector find approximate nearest neighbours without comparing the query to every row. EXPLAIN shows whether the query uses it.
Step 4 of 5
Filter in SQL
The metadata condition sits in the WHERE clause, so rows the caller may not see are never candidates.
Step 5 of 5
Rank by cosine
The query is embedded, the <=> operator measures cosine distance, and the closest k rows come back with their scores.
The filter belongs in the SQL query. Hiding results afterwards is not access control.
Scenario
Build the retrieval layer: embed documents, store in pgvector, and query with metadata filters for access control.
Objective
Implement a VectorStore with embed, insert, and search(filter) methods.
Starter code
Implement the TODOs to complete the lab.
vectorstore.py
~165 tokens
import pgvector
from openai import OpenAI
client = OpenAI()
class VectorStore:
def embed(self, text: str) -> list[float]:
"""Embed text using text-embedding-3-small (1536 dimensions by default, so use VECTOR(1536))."""
# TODO
pass
def insert(self, text: str, metadata: dict) -> str:
"""Insert document with embedding and metadata."""
# TODO
pass
def search(self, query: str, k: int = 5, filters: dict = None) -> list[dict]:
"""Search by similarity with optional metadata filter."""
# TODO — filter must apply at SQL level, not display
pass
Solution hints
1Use pgvector's <=> operator for cosine distance
2Apply metadata filters in the WHERE clause
3Create an HNSW index for ANN
4Return chunk_id, score, text, metadata
Validation steps
Your implementation should pass these checks.
Insert 10 docs, search returns relevant ones
Metadata filter excludes docs not matching filter
Search respects HNSW index (check EXPLAIN)
Cosine similarity scores are in [-1, 1]
Run validation
This is a simulated validation environment. In production, this would run your code against the validation steps.