Gestire i metadati dei documenti e i filtri
Impari ad associare, arricchire e filtrare i metadati dei documenti, così che la pipeline RAG limiti il retrieval alle fonti corrette.
Gestire i metadati dei documenti e i filtri è una lezione LangChain / RAG / Vector DBs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento LangChain / RAG / Vector DBs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso LangChain / RAG / Vector DBs include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Domande Frequenti
La lezione «Gestire i metadati dei documenti e i filtri» è gratuita?
Sì — il testo completo di «Gestire i metadati dei documenti e i filtri» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso LangChain / RAG / Vector DBs, passa a CoddyKit PRO. Il corso LangChain / RAG / Vector DBs include 4 lezioni in totale.
Cosa imparerò in «Gestire i metadati dei documenti e i filtri»?
Impari ad associare, arricchire e filtrare i metadati dei documenti, così che la pipeline RAG limiti il retrieval alle fonti corrette. Eserciti LangChain / RAG / Vector DBs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare LangChain / RAG / Vector DBs?
Non è richiesta alcuna esperienza precedente. LangChain / RAG / Vector DBs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Gestire i metadati dei documenti e i filtri»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione LangChain / RAG / Vector DBs?
Sì. Ogni lezione LangChain / RAG / Vector DBs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Caricare diversi tipi di documenti
- Comprendere le strategie di suddivisione del testo
- Personalizzare la suddivisione dei documenti
- Gestire i metadati dei documenti e i filtri