处理文档元数据与筛选
学习如何附加、丰富和筛选文档元数据,让您的 RAG pipeline 将检索范围限定在正确的来源内。
处理文档元数据与筛选 是 CoddyKit 上的免费 LangChain / RAG / Vector DBs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 LangChain / RAG / Vector DBs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Metadata Matters
Every document chunk in LangChain carries a page_content string and a metadata dictionary. While the content feeds the embedding model, metadata drives filtering, attribution, and traceability.
- Source file or URL
- Page number or section
- Author, date, language
The Document Object
A LangChain Document is a lightweight container. You can construct one directly and pass any JSON-serializable values in metadata.
from langchain_core.documents import Document
doc = Document(
page_content="Annual revenue grew 12%.",
metadata={"source": "report.pdf", "page": 4, "year": 2025}
)
print(doc.metadata["source"])Automatic Metadata from Loaders
Most loaders inject metadata for free. A PyPDFLoader adds source and page, while a WebBaseLoader adds the URL and page title.
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("handbook.pdf")
pages = loader.load()
print(pages[0].metadata)
# {"source": "handbook.pdf", "page": 0}Enriching Metadata After Load
You often need to add fields the loader does not know about, like a category or tenant id. Iterate and mutate the dictionary.
for d in pages:
d.metadata["department"] = "finance"
d.metadata["sensitive"] = False
print(pages[0].metadata["department"])Metadata Survives Splitting
When you split documents, the splitter copies the parent metadata onto each child chunk. This means filters set before splitting still apply afterward.
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=200)
chunks = splitter.split_documents(pages)
print(chunks[0].metadata["source"])Filtering at Retrieval Time
Vector stores accept a filter argument so you only search the relevant slice. This is faster and reduces irrelevant matches.
results = vectorstore.similarity_search(
"vacation policy",
k=3,
filter={"department": "hr"}
)Self-Query Retrieval
A SelfQueryRetriever lets the LLM translate a natural-language query into both a semantic search and a metadata filter automatically.
You describe the metadata schema once, and the model decides when to filter.
Cleaning Noisy Metadata
Loaders sometimes produce verbose or nested metadata that vector stores reject. Flatten or whitelist the keys you need.
def clean(d):
keep = {"source", "page", "department"}
d.metadata = {k: v for k, v in d.metadata.items() if k in keep}
return d
cleaned = [clean(d) for d in chunks]Metadata for Citations
Storing the source and page lets you cite where an answer came from. After retrieval, format the metadata into a human-readable reference.
for r in results:
src = r.metadata["source"]
pg = r.metadata.get("page", "?")
print(f"[{src} p.{pg}]")Type Constraints
Many vector databases only allow scalar metadata values: strings, numbers, and booleans. Lists or dicts must be serialized to JSON strings or removed.
- Good:
{"page": 4} - Reject:
{"tags": ["a","b"]}
A Practical Filter Pipeline
Combine enrichment, cleaning, and filtered search into one flow so every query is scoped to the correct subset of your corpus.
docs = PyPDFLoader("policy.pdf").load()
for d in docs:
d.metadata["region"] = "EU"
chunks = splitter.split_documents(docs)
# index chunks, then:
vectorstore.similarity_search("data retention", filter={"region": "EU"})Quick Check
Test your understanding of metadata handling.
Recap
You learned to work with document metadata:
- Loaders auto-add fields like
sourceandpage - Enrich and clean metadata for filtering and citations
- Metadata propagates through splitting
- Use
filteror a self-query retriever to scope searches
用 AI 导师学习 LangChain / RAG / Vector DBs — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「处理文档元数据与筛选」课时是免费的吗?
是的 — 「处理文档元数据与筛选」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 LangChain / RAG / Vector DBs 课程的其余内容,请升级到 CoddyKit PRO。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
「处理文档元数据与筛选」这节课中我会学到什么?
学习如何附加、丰富和筛选文档元数据,让您的 RAG pipeline 将检索范围限定在正确的来源内。 你通过在浏览器中直接运行的动手代码来练习 LangChain / RAG / Vector DBs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 LangChain / RAG / Vector DBs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 LangChain / RAG / Vector DBs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「处理文档元数据与筛选」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 LangChain / RAG / Vector DBs 课中编写并运行代码吗?
能。每节 LangChain / RAG / Vector DBs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。