Learn/LangChain Mastery/Part 5 · 4. Embeddings & Vector Stores
Lesson 35 of 68
SyllabusLangChain Mastery · Part 5

Metadata Filtering

Narrowing the search space. Mixing structured and unstructured data.

Course outline & contents
LangChain Mastery
Embeddings: What Matters in PracticeEmbedding Models in LangChainVector Stores: FAISS, ChromaPersisting & Reloading IndexesMetadata FilteringDense vs Sparse (BM25 Overview)Hybrid Search Concepts

You ask: "What did the 2023 financial report say about profit?" The vector store finds a chunk: "Profit increased by 10% (2020 report)." Semantically, it is very close. Factually, it is wrong.

Vectors define "Aboutness." Metadata defines "Exactness." You cannot rely on vectors to filter by year, user ID, or category.

2. Pre-Filtering vs Post-Filtering

Logic: "Find all docs where year=2023, THEN find the most similar ones."

  • Pros: Efficient. Guarantees the constraint is met.
  • Cons: Harder for database to optimize (HNSW index).

Post-Filtering (Common but risky)

Logic: "Find top 100 similar docs. THEN remove ones where year!=2023."

  • Risk: What if all top 100 are from 2022? You filter them all out and return 0 results.

Most vector stores now support Pre-filtering native.

filter_search.py
results = vectorstore.similarity_search(
  "profit growth",
  k=5,
  filter={"year": 2023, "department": "finance"}
)

Always attach metadata during ingestion. Effective RAG is 50% Vector Search + 50% SQL-style filtering.

Key Intuition: "Filters are hard constraints. Vectors are soft suggestions."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonPersisting & Reloading IndexesNext lesson →Dense vs Sparse (BM25 Overview)