Skip to content
All labs
Intermediate55 minProduction RAG

Embeddings and vector search

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.

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
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.