Velamuvi AIAcademy

Lesson 4 of 9 · Concepts

Metadata Filtering

Combine similarity search with metadata filters: filter operators, pre- vs post-filtering, why post-filtering can return too few results, and per-user privacy.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Attach metadata to records and filter searches with it
  • Use common filter operators: equals, ranges, “in a list”, and combining conditions
  • Explain why filtering after ranking can return too few results
  • Use filters (or namespaces) to keep each customer's data separate

Similar, but only from the right documents

Similarity alone is rarely enough. A user searching in English wants English results; a support bot should only read articles for the product the customer owns; a search over news wants this year's articles.

Most databases offer the same building blocks, with slightly different syntax:

ConditionChroma and Pinecone styleMeaning
Equals{"lang": "en"} or {"lang": {"$eq": "en"}}Language is English
Range{"year": {"$gte": 2025}}Year is 2025 or later
In a list{"plan": {"$in": ["pro", "team"]}}Plan is pro or team
Combine{"$and": [cond1, cond2]} and $orBoth, or either

Qdrant and pgvector express the same ideas differently (filter objects in Qdrant, an ordinary SQL WHERE clause in pgvector), as you'll see in later lessons.

Filtering in action

The search below filters before ranking, so it always looks for the best 3 among the allowed records. The last part shows what goes wrong if you rank first and filter afterwards:

Try it yourselfPython
import math

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

# Each record: id, vector [travel, food, money], text, metadata
records = [
    ("d1", [0.8, 0.3, 0.4], "Cheap flights to Goa",          {"lang": "en", "year": 2026, "plan": "free"}),
    ("d2", [0.9, 0.1, 0.5], "Budget airline tips",           {"lang": "en", "year": 2023, "plan": "free"}),
    ("d3", [0.9, 0.2, 0.4], "Billige Flüge nach Rom",        {"lang": "de", "year": 2026, "plan": "free"}),
    ("d4", [0.5, 0.2, 0.8], "Saving money on train tickets", {"lang": "en", "year": 2025, "plan": "pro"}),
    ("d5", [0.2, 0.9, 0.1], "Street food on a budget",       {"lang": "en", "year": 2026, "plan": "free"}),
    ("d6", [0.6, 0.4, 0.5], "Low-cost holiday planning",     {"lang": "en", "year": 2026, "plan": "pro"}),
]

def matches(meta, where):
    """Supports exact values and {"$gte": n} / {"$in": [...]} conditions."""
    for key, condition in where.items():
        value = meta.get(key)
        if isinstance(condition, dict):
            if "$gte" in condition and not (value is not None and value >= condition["$gte"]):
                return False
            if "$in" in condition and value not in condition["$in"]:
                return False
        elif value != condition:
            return False
    return True

def search(query, k=3, where=None):
    scored = []
    for id, vec, text, meta in records:
        if where and not matches(meta, where):
            continue                                  # filtered out before ranking
        scored.append((cosine(query, vec), id, text))
    scored.sort(reverse=True)
    return scored[:k]

query = [0.9, 0.1, 0.5]   # "cheap flights"
print("No filter:")
for score, id, text in search(query):
    print(f"  {score:.2f} {id} {text}")

print("English, 2025 or newer:")
for score, id, text in search(query, where={"lang": "en", "year": {"$gte": 2025}}):
    print(f"  {score:.2f} {id} {text}")

# The trap: take the top 3 first, THEN filter (post-filtering)
print("Top 3 first, then filter:")
english_new = {"lang": "en", "year": {"$gte": 2025}}
meta_by_id = {id: meta for id, vec, text, meta in records}
for score, id, text in search(query):
    if matches(meta_by_id[id], english_new):
        print(f"  {score:.2f} {id} {text}")

Without a filter, an old article and a German one take two of the three places. With the filter applied before ranking, you get three good English results from 2025 onwards. Ranking first and filtering afterwards left only one result, because the other two of the top 3 were removed.

Real vector databases handle this inside the index: they skip non-matching records while walking the HNSW graph or the IVF lists, so you get k results that match. When a filter is very selective (say, one customer's 50 documents out of 10 million), many databases switch to exact search over just the matching records, which is fast because there are so few of them.

Keeping customers apart

If an app stores documents from many companies in one collection, every query must carry a filter such as {"tenant_id": "acme"}. Some databases offer namespaces or separate collections per tenant, which make this harder to forget.

Common mistakes

Practice exercise

Write the metadata filter. Only documents from the finance team with status final should be printed.

Your solutionPython
docs = [
    {"title": "Q3 budget",        "meta": {"team": "finance", "status": "final"}},
    {"title": "Q3 budget draft",  "meta": {"team": "finance", "status": "draft"}},
    {"title": "Holiday rota",     "meta": {"team": "hr",      "status": "final"}},
    {"title": "Expense policy",   "meta": {"team": "finance", "status": "final"}},
]

def matches(meta, where):
    # Return True only if EVERY key in `where` has the same value in `meta`
    return True

for doc in docs:
    if matches(doc["meta"], {"team": "finance", "status": "final"}):
        print(doc["title"])
Knowledge check

You ask for the top 5 results, then remove those not in the user's language, and often end up with only 1 or 2. What is the fix?

Summary

  • Metadata stored with each vector lets you filter searches by language, date, product, user and more.
  • Common operators: equals, ranges ($gte, $lt), in a list ($in) and and / or.
  • Pre-filtering ranks only allowed records; post-filtering can return too few results.
  • Filters (or namespaces) enforce multi-tenancy; always set them on the server, never from user input.

Next: your first real vector database, Chroma.

Finished reading? Tick it off to track your progress.