AI Tools8 min read

Metadata Filtering in Vector Search: How It Works

How metadata filters work in vector search and RAG: pre- vs post-filtering, filtered HNSW in Qdrant, Weaviate, Milvus and pgvector, schema design and pitfalls.

By AI Agents DirectoryLast checked
Green code characters falling down a dark screen

A vector index answers one question: which stored embeddings are closest to this query embedding? Real applications almost always need a second condition on top of that. A support bot should only retrieve documents the current customer may see. A news assistant should prefer articles from the last week. A shop should skip items that are out of stock. Those conditions live in metadata (Qdrant calls it payload, Milvus calls it scalar fields, Postgres calls it columns), and how the database combines them with approximate nearest neighbour (ANN) search decides whether your results are correct, complete and fast.

This guide covers why filters matter in retrieval-augmented generation (RAG), the two basic ways to apply them, how four engines handle filtered HNSW search according to their own documentation, and the mistakes that cost you recall. For a side-by-side of Chroma and Qdrant as products, see our Chroma vs Qdrant comparison; this post stays on the filtering mechanics.

Why filters matter in RAG

Qdrant’s docs put the case simply: some properties of an object can’t be captured in an embedding, so you add conditions on payload fields such as stock, location or price. In RAG systems three kinds of filter come up again and again:

  • Tenancy. Many customers share one index, and a query from one tenant must never surface another tenant’s chunks. Qdrant’s multitenancy guide recommends keeping tenants in a single collection with a tenant ID field and filtering on it, rather than one collection per tenant, because each collection carries its own overhead.
  • Permissions. Within a tenant, users see different documents. A common pattern is to store group or role identifiers on each chunk and filter by the caller’s groups. Milvus even supports bitwise operators (from Milvus 3.0) for integer fields that pack permission or status flags.
  • Freshness. Policies change and prices go stale. Storing a timestamp and filtering with a range condition keeps old chunks out of the context window. Qdrant supports a datetime payload index for range conditions.

Filtering before generation also keeps the prompt focused, which matters when context is limited (see our notes on RAG context window management).

Pre-filtering vs post-filtering

Weaviate’s filtering concepts page gives a clear account of the trade-off.

ApproachWhat happensMain risk
Post-filteringRun the vector search, then remove results that fail the filterYou can’t predict how many results survive; with a strict filter the top candidates may contain no match at all
Pre-filteringDecide which records are eligible first, then search only among themDone naively it becomes brute force over the eligible set; done well it needs filter-aware graph traversal

Pre-filtering is what you want for tenancy and permissions, because “found nothing” and “found the wrong tenant’s data” are both unacceptable. The hard part is doing it efficiently on an HNSW graph, where removing many nodes can cut the paths a search would normally follow.

Qdrant: payload indexes and filterable HNSW

Qdrant pairs its vector index with payload indexes, which are per-field indexes much like those in a document database. Supported index types include keyword, integer, float, bool, geo, datetime, text and uuid. Besides speeding up lookups, a payload index lets Qdrant estimate how many points a filter matches, and its query planner uses that estimate to choose a strategy.

The docs describe three regimes. When a filter is loose, the regular HNSW graph works fine. When it is very strict, Qdrant can use the payload index to collect the matching points and score them all directly; the full_scan_threshold setting controls when the planner prefers a full scan over graph traversal. For filters in between, Qdrant adds extra edges to the HNSW graph based on indexed payload values so the graph stays navigable under the filter.

Two practical consequences follow. First, create payload indexes before you ingest data; the extra edges only exist for indexes that were present when the graph was built, so adding one later means rebuilding HNSW. Second, those edges are built per indexed field, not for every combination, so stacking two or more strict filters can still leave the graph fragmented. For that case Qdrant offers the ACORN search algorithm, which also checks neighbours of neighbours when direct neighbours are filtered out, gaining accuracy at some cost in speed.

Weaviate: allow lists and filter strategies

Each Weaviate shard keeps an inverted index next to its HNSW index. At query time the inverted index produces an allow list of eligible object IDs, and the HNSW search then only admits IDs on that list to the result set while traversing the graph as usual. Weaviate supports three filter strategies for HNSW (sweeping, acorn and pathseer), and its docs say ACORN became the default in v1.34. ACORN is aimed at filters with low correlation to the query vector, meaning the filter rules out much of the graph region near the query. Weaviate can also switch to a flat, brute-force search over the matching subset once a filter is restrictive enough, since at that point HNSW traversal would be nearly exhaustive anyway.

Milvus: standard and iterative filtering

Milvus applies filter expressions on scalar fields before the ANN search in its standard mode, narrowing the search to matching entities and then returning the top-K. Expressions support comparison, IN, LIKE, logical operators and IS NULL. For very complex expressions that make standard filtering slow, Milvus offers iterative filtering (the iterative_filter search hint): it pulls results from the vector search in batches and checks each against the filter until it has enough. The docs warn that this sequential processing can itself be slow when many entities need checking.

For tenancy, Milvus lets you mark a scalar field as the partition key. Entities are hashed into partitions by that value, and a filter on the key limits the search to the relevant partitions. With Partition Key Isolation enabled (HNSW only), the filter must name a single key value, and Milvus recommends still indexing the partition key field.

pgvector: WHERE clauses and iterative index scans

In Postgres you filter with an ordinary WHERE clause. The pgvector README suggests starting with a normal B-tree or multicolumn index on the filter columns, which gives exact results and works well when the condition matches few rows. With an HNSW or IVFFlat index, though, the filter is applied after the index scan, so a selective condition can return fewer rows than your LIMIT. Since version 0.8.0, iterative index scans fix this by scanning more of the index until enough rows qualify or a cap such as hnsw.max_scan_tuples is hit. Use strict_order for exact distance order or relaxed_order when slight reordering is acceptable in exchange for better recall.

For a filter on a handful of values, the README suggests partial indexes; for many values, table partitioning. For tenants it recommends list partitioning or separate tables, noting that a shared approximate index lets one tenant’s vectors affect another’s recall and speed.

Managed services follow the same idea: Pinecone lets you attach a metadata filter such as {"category": {"$eq": "digestive system"}} to a search so only matching documents come back.

A compact example

This is Qdrant’s payload-partitioning pattern from its multitenancy guide: index the tenant field (with is_tenant, available from v1.11.0, so each tenant’s points are stored together), then filter every query on it.

client.create_payload_index(
    collection_name="{collection_name}",
    field_name="group_id",
    field_schema=models.KeywordIndexParams(
        type=models.KeywordIndexType.KEYWORD,
        is_tenant=True,
    ),
)

client.query_points(
    collection_name="{collection_name}",
    query=[0.1, 0.1, 0.9],
    query_filter=models.Filter(
        must=[
            models.FieldCondition(
                key="group_id",
                match=models.MatchValue(value="user_1"),
            )
        ]
    ),
    limit=10,
)

The tenant filter should be added on the server side of your application from the authenticated session, never taken from the user’s prompt or request body.

Designing a metadata schema

  • Index only what you filter on. Qdrant notes that payload indexes take extra memory and disk. If you can’t index everything, it advises indexing the field that narrows results the most.
  • Use the right type. Store dates as datetime or integer timestamps so range filters can use an index, keep IDs as keyword or uuid fields, and avoid stuffing filterable values into free text.
  • Decide on tenancy early. Payload or partition-key filtering suits many small tenants. Qdrant suggests dedicated shards for fewer, larger tenants, and pgvector suggests partitions or separate tables when isolation matters.
  • Create indexes before loading data wherever the engine builds filter-aware structures at index time, as Qdrant does.
  • Block unindexed filters in production. Qdrant’s strict mode can reject queries that filter on unindexed fields, so a missing index fails loudly instead of quietly slowing every query. Qdrant Cloud applies this by default.

Pitfalls

  • Assuming post-filtering returns k results. It may not. Check how your engine applies the filter, and in pgvector turn on iterative scans or use exact indexes for selective filters.
  • Strict combined filters on HNSW. Very selective filters, or several of them together, can break up the graph. Look for the engine’s remedy: ACORN in Qdrant and Weaviate, a flat-search cutoff in Weaviate, full-scan thresholds in Qdrant.
  • Adding indexes after ingestion in Qdrant without rebuilding HNSW, so the filter-aware edges never get built.
  • Not measuring recall under filters. pgvector’s README recommends comparing approximate results with exact search; do that with your real filters applied, not just unfiltered queries.
  • Treating filters as optional security. If a tenant or permission filter is missing from one code path, nothing in the vector index will catch it. Put filter construction in one shared function and test it.

For more retrieval and vector tooling, browse the LLM infrastructure category.

#vector search#metadata filtering#RAG#HNSW#vector databases
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.