0Pricing
LangChain / RAG / Vector DBs · Lekcja

Obsługa metadanych dokumentów i filtrowanie

Dowiedz się, jak dodawać, wzbogacać i filtrować metadane dokumentów, aby potok RAG ograniczał wyszukiwanie do właściwych źródeł.

Obsługa metadanych dokumentów i filtrowanie to bezpłatna lekcja LangChain / RAG / Vector DBs na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej LangChain / RAG / Vector DBs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs LangChain / RAG / Vector DBs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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 source and page
  • Enrich and clean metadata for filtering and citations
  • Metadata propagates through splitting
  • Use filter or a self-query retriever to scope searches

Często zadawane pytania

Czy lekcja „Obsługa metadanych dokumentów i filtrowanie” jest bezpłatna?

Tak — pełny tekst „Obsługa metadanych dokumentów i filtrowanie” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu LangChain / RAG / Vector DBs, przejdź na CoddyKit PRO. Kurs LangChain / RAG / Vector DBs zawiera 4 lekcji w sumie.

Co nauczysz się w „Obsługa metadanych dokumentów i filtrowanie”?

Dowiedz się, jak dodawać, wzbogacać i filtrować metadane dokumentów, aby potok RAG ograniczał wyszukiwanie do właściwych źródeł. Ćwiczysz LangChain / RAG / Vector DBs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć LangChain / RAG / Vector DBs?

Nie wymagamy żadnego doświadczenia. LangChain / RAG / Vector DBs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Obsługa metadanych dokumentów i filtrowanie”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji LangChain / RAG / Vector DBs?

Tak. Każda lekcja LangChain / RAG / Vector DBs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Wczytywanie różnych typów dokumentów
  2. Zrozumienie strategii dzielenia tekstu
  3. Dostosowywanie dzielenia dokumentów
  4. Obsługa metadanych dokumentów i filtrowanie
← Powrót do LangChain / RAG / Vector DBs