惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
I
InfoQ
H
Hacker News: Front Page
D
Docker
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
博客园 - 【当耐特】
T
Tor Project blog
U
Unit 42
H
Heimdal Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Privacy & Cybersecurity Law Blog
PCI Perspectives
PCI Perspectives
美团技术团队
O
OpenAI News
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Metadata Filtering Before Vector Search: The Recall Win Nobody Measures
Gabriel Anhaia · 2026-06-13 · via DEV Community

A support agent asks the bot a question about a customer's enterprise contract. The bot retrieves the top 10 chunks by cosine similarity across the whole corpus. Two of them are from a different customer's contract that happens to use near-identical boilerplate language. The model writes a confident answer citing a clause that does not exist in the customer's actual agreement.

That is not a hallucination in the usual sense. The retrieval was working as designed. The vector index found the most semantically similar chunks, and boilerplate is semantically similar across customers by definition. The fix is not a better embedding model. The fix is telling the index to never look at the other customer's documents in the first place.

That is metadata filtering. Most teams treat it as an access-control checkbox. It is also one of the cheapest recall wins in the pipeline, and almost nobody measures it.

What pre-filtering actually does

Your vector store holds chunks. Each chunk carries metadata: customer_id, doc_type, language, indexed_at, team. Pre-filtering means you apply a hard predicate on that metadata before the vector search ranks anything.

Without a filter, a query for "late payment penalty" searches all 2 million chunks and returns the 10 closest in embedding space. With a filter, you search only the chunks where customer_id = 4417, then rank those. The search space drops from 2 million to maybe 800 chunks. Every one of the top-10 results now comes from the right document set.

The recall framing matters here. Recall is the fraction of relevant chunks you manage to retrieve. When the corpus is full of near-duplicate boilerplate, irrelevant-but-similar chunks crowd out the relevant ones in the top-k. Cut the search space to the documents that can possibly be relevant, and the relevant chunks stop competing with look-alikes. The top-k fills with chunks that have a real chance of answering.

# Qdrant: filter then search, in one call.
from qdrant_client import QdrantClient
from qdrant_client.models import (
    Filter, FieldCondition, MatchValue,
)

client = QdrantClient(url="http://localhost:6333")

def search(query_vec, customer_id, k=10):
    flt = Filter(
        must=[
            FieldCondition(
                key="customer_id",
                match=MatchValue(value=customer_id),
            ),
        ]
    )
    return client.search(
        collection_name="contracts",
        query_vector=query_vec,
        query_filter=flt,
        limit=k,
    )

The query vector is the same. The only change is the predicate. The result quality change is not subtle when your corpus has natural partitions.

Pre-filter versus post-filter (this is where it goes wrong)

There are two places to apply the predicate, and they are not equivalent.

Post-filter: run the vector search over the whole corpus, get the top-k, then drop the chunks that fail the predicate. The problem: if you ask for 10 and 9 of the top 10 belong to other customers, you keep one chunk. You wanted 10. You got 1. The relevant chunks were ranked at positions 40, 55, 71 and never made the candidate set.

Pre-filter: restrict the candidate set to chunks that pass the predicate, then rank within it. You always get up to 10 results from the right partition.

Post-filtering silently starves recall. It looks like it works in a demo where the test query happens to match the dominant partition. It collapses on the queries where the relevant partition is a small slice of the corpus, which is the case that matters for multi-tenant systems.

Most managed vector stores do pre-filtering when you pass the predicate into the search call, and post-filtering when you filter the result list yourself in application code. Read your store's docs for which one the API gives you. Pinecone, Qdrant, Weaviate, and pgvector with the right index all support pre-filtering. The trap is filtering in Python after the fact and assuming it is the same thing.

The cardinality trap

Pre-filtering is not free, and the cost depends on how selective your predicate is.

Approximate nearest-neighbor indexes like HNSW are graphs. The search walks the graph from entry points toward the query vector. A filter prunes nodes during the walk. When the filter keeps most of the graph, the walk works normally. When the filter keeps a tiny fraction, the walk hits dead ends. The reachable nodes that pass the filter become sparse, the graph traversal stalls, and you either get degraded recall or the engine falls back to a slow brute-force scan over the matching set.

This is the cardinality trap, and it cuts both ways.

  • High-cardinality field, low selectivity (language = "en" when 95% of the corpus is English): the filter barely shrinks the search space. You pay the filter cost and gain almost nothing.
  • High-cardinality field, high selectivity (customer_id = 4417 when each customer is 0.04% of the corpus): the matching set is tiny and scattered through the HNSW graph. The graph walk degrades. Some engines auto-switch to brute force, which is fine at 800 chunks and a problem at 80,000.

The selectivity sweet spot is a predicate that removes most of the corpus but leaves a matching set large enough for the index to traverse and small enough to be worth filtering. For very selective tenant filters, a payload index (Qdrant), a partitioned collection, or a metadata-aware index config is what keeps the filtered search fast.

# Qdrant: index the field you filter on, or the
# filtered search degrades to a scan at scale.
from qdrant_client.models import PayloadSchemaType

client.create_payload_index(
    collection_name="contracts",
    field_name="customer_id",
    field_schema=PayloadSchemaType.KEYWORD,
)

Without that index, a customer_id filter on a large collection makes the engine scan every payload to find matches. With it, the engine knows the matching set up front and plans the search around it. The difference at 2 million chunks is tens of milliseconds versus seconds.

Measuring the recall lift

The win is real, but you have to measure it on your corpus, because it depends entirely on how partitioned your data is. A flat single-tenant knowledge base sees almost no lift. A multi-tenant contract store sees a large one.

Build a gold set: real queries paired with the chunk IDs that actually answer them, labeled by hand. Then run the same queries twice, with and without the filter, and compute recall@k on each.

def recall_at_k(retrieved_ids, gold_ids, k=10):
    top = set(retrieved_ids[:k])
    hits = top & set(gold_ids)
    return len(hits) / len(gold_ids)

def compare(gold_set, customer_lookup):
    # embed, mean, search_no_filter come from your
    # stack; ids() pulls point IDs off the results.
    no_filter, with_filter = [], []
    for item in gold_set:
        q = embed(item["query"])
        cid = customer_lookup[item["query_id"]]

        unfiltered = search_no_filter(q, k=10)
        filtered = search(q, customer_id=cid, k=10)

        no_filter.append(
            recall_at_k(ids(unfiltered), item["gold_ids"])
        )
        with_filter.append(
            recall_at_k(ids(filtered), item["gold_ids"])
        )

    return {
        "recall_no_filter": mean(no_filter),
        "recall_with_filter": mean(with_filter),
    }

Run this before you ship the filter. If the lift is small, your corpus is not partitioned enough for filtering to matter and you should spend the effort on reranking instead. If the lift is large, you have found a recall win that costs one predicate and a payload index. Either way, you now have a number, which is more than most teams retrieving against a multi-tenant corpus can say.

Composing filters without killing selectivity

Real queries carry more than one constraint. The agent wants the current English version of a contract for one customer. That is three predicates: customer_id, language, indexed_at recent.

from qdrant_client.models import Range

def search_scoped(query_vec, customer_id, k=10):
    flt = Filter(
        must=[
            FieldCondition(
                key="customer_id",
                match=MatchValue(value=customer_id),
            ),
            FieldCondition(
                key="language",
                match=MatchValue(value="en"),
            ),
            FieldCondition(
                key="status",
                match=MatchValue(value="active"),
            ),
        ]
    )
    return client.search(
        collection_name="contracts",
        query_vector=query_vec,
        query_filter=flt,
        limit=k,
    )

Order the predicates by selectivity in your head, even if the engine reorders them internally. The most selective field (customer_id) does the heavy lifting. The others trim the remainder. Adding a low-selectivity predicate like language on top of a high-selectivity one is cheap. Stacking five low-selectivity predicates and expecting them to substitute for one good high-selectivity predicate is how teams end up with a filter that costs latency and returns the same noisy candidate set.

The metadata schema is the thing to get right early. You cannot filter on a field you did not store at ingestion. Carry customer_id, doc_type, language, status, and indexed_at through the chunking layer as payload on every chunk. Retrofitting metadata onto an indexed corpus means a full re-index, which is the expensive thing this whole technique is supposed to help you avoid.

The part nobody writes about

Vector search gets the blog posts. The cosine similarity, the reranker, the query rewriter. Metadata filtering is plumbing, so it gets a checkbox in the access-control story and no place in the recall story.

That is the gap. For any corpus with natural partitions, the predicate you apply before the index runs does more for top-k quality than the third reranker you were about to add. It is cheaper, it is deterministic, and it is auditable: you can prove the bot never saw the other customer's contract, which is a sentence your security review will want to hear.

Store the metadata. Pre-filter, not post-filter. Index the high-selectivity field. Measure the lift on your own gold set. The recall win is sitting in a field you are probably already storing and not searching against.

If this was useful

The RAG Pocket Guide covers the retrieval layer end to end — metadata schemas, hybrid filter-plus-vector search, the cardinality traps that degrade filtered ANN, and how to wire an eval that catches a recall regression before your users do. If your retrieval quality depends on a corpus with real partitions, the filtering chapter is where the cheap wins live.

RAG Pocket Guide