AI Hints
Home›RAG Tutorial›Working with Indexes
RAG · Lesson 35 of 120

Metadata Filters

Search only what matches.

⏱ 2 min read▶ Video at 35:07🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Northwind has two price lists, an old one from twenty twenty five, and the current one. A search for a price can return the old one. Metadata filters fix this, by searching only chunks that match a rule.

Metadata Filters
From the video: Metadata Filters
  • Two price lists
  • Old one can win
  • Filter it out

Filtering out old pages

Search filters takes a rule, a function that looks at each chunk. We score every chunk, but skip any that fail the rule. First we search without a rule, then with a rule that drops the old price list. Run it. Without the filter, the old price list comes first. With it, the old list is gone.

filters.pypython
import numpy as np
from rag_kit import load_docs, make_chunks, embed

chunks = make_chunks(load_docs())
vectors = embed([c["text"] for c in chunks])

def search(question, k=2, rule=lambda c: True):
    scores = vectors @ embed([question])[0]
    order = [i for i in np.argsort(-scores) if rule(chunks[i])]
    return [chunks[i]["source"] for i in order[:k]]

q = "How much is the Volt e-bike?"
print("no filter:  ", search(q))
print("current only:", search(q, rule=lambda c: c["source"] != "price_list_2025.md"))
Output
no filter:   ['price_list_2025.md', 'price_list_2026.md']
current only: ['price_list_2026.md', 'servicing.md']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Filters in practice

Real vector stores take filters as part of the search, like a year greater than twenty twenty five, or a product equal to Volt. Common filters are date, product, language, and who's allowed to see a document.

keyvalue
Datecurrent only
ProductVolt, Trail
Languagematch the user
Permissionswho can see it

Summary

Metadata filters restrict search to chunks that match a rule, like current documents only. Next, top k and scores.

Key takeaways
  • Rule per chunk
  • Skip what fails
  • Old versions out
Next up: Top-k and Scores — how many to fetch