Extracting Metadata from Documents

Capture title, author, date, section and source so you can filter and cite results.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 3 · Lesson 10 of 13 · Beginner

Extracting Metadata from Documents

Capture title, author, date, section and source so you can filter and cite results.

Metadata is information about a document: its title, source, author, date, department, product, language or access level. In RAG, metadata does three jobs. It lets you filter searches ("only HR policies from 2026"), cite sources in answers, and rank results (newer documents first). This lesson shows where to get metadata and how to store it with each chunk.

Four sources of metadata

SourceExamplesReliability
File system and URLFile name, folder path, URL, modified dateHigh
Embedded file propertiesPDF title and author, DOCX core propertiesMedium (often empty or wrong)
Document contentFirst heading, dates in the text, section headingsMedium
LLM extractionDocument type, topic, product, summaryHigh for semantic fields, at a cost

File system and path metadata

Folder structures often encode useful facts. A path like knowledge_base/hr/policies/leave-policy-2026.pdf tells you the department and document type.

from datetime import datetime, timezone
from pathlib import Path

def path_metadata(path: Path, root: Path) -> dict:
    parts = path.relative_to(root).parts
    stat = path.stat()
    return {
        "source": str(path.relative_to(root)).replace("\\", "/"),
        "file_name": path.name,
        "department": parts[0] if len(parts) > 1 else None,
        "doc_type": parts[1] if len(parts) > 2 else None,
        "modified": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).date().isoformat(),
        "size_bytes": stat.st_size,
    }

Embedded file properties

from pypdf import PdfReader
import docx

def pdf_properties(path: Path) -> dict:
    info = PdfReader(path).metadata or {}
    return {"title": info.get("/Title"), "author": info.get("/Author"),
            "created": str(info.get("/CreationDate", "")) or None}

def docx_properties(path: Path) -> dict:
    props = docx.Document(path).core_properties
    return {"title": props.title or None, "author": props.author or None,
            "created": props.created.isoformat() if props.created else None}

Treat these as hints. Many PDFs carry a title like "Microsoft Word - Document1".

Metadata from content

Simple rules often work well: the first Markdown heading is usually the title, and dates follow a few common formats.

import re

DATE_PATTERN = re.compile(
    r"\b(\d{4}-\d{2}-\d{2}|\d{1,2} (?:January|February|March|April|May|June|July|"
    r"August|September|October|November|December) \d{4})\b"
)

def content_metadata(text: str) -> dict:
    title = next((l.lstrip("# ").strip() for l in text.splitlines() if l.startswith("# ")), None)
    dates = DATE_PATTERN.findall(text[:3000])        # dates near the top are the most telling
    return {"title_from_text": title, "first_date": dates[0] if dates else None}

LLM-based metadata extraction

For semantic fields such as document type, topic or products mentioned, ask an LLM and enforce the output shape with a schema. Using a fixed list of allowed values (an enumeration) keeps the values consistent, which matters for filtering.

from typing import Literal, Optional
from pydantic import BaseModel
import anthropic

client = anthropic.Anthropic()

class DocMetadata(BaseModel):
    title: str
    doc_type: Literal["policy", "procedure", "faq", "contract", "report", "manual", "other"]
    topics: list[str]
    effective_date: Optional[str]      # ISO date if the document states one
    summary: str                       # one or two sentences

def llm_metadata(text: str) -> DocMetadata:
    response = client.messages.parse(
        model="claude-opus-5-5",
        max_tokens=2000,
        output_config={"effort": "low"},
        messages=[{"role": "user", "content":
            "Extract metadata from this document. Use at most 5 short topics. "
            "Give the effective date only if the document states one.\n\n"
            f"<document>\n{text[:20000]}\n</document>"}],
        output_format=DocMetadata,
    )
    return response.parsed_output

meta = llm_metadata(open("docs/leave-policy.txt", encoding="utf-8").read())
print(meta.model_dump())
{'title': 'Zentrix Labs Leave Policy', 'doc_type': 'policy',
 'topics': ['paid leave', 'sick leave', 'leave carry-over'],
 'effective_date': None,
 'summary': 'Defines paid leave and sick leave entitlements for Zentrix Labs employees.'}

Run LLM extraction once per document (not per chunk) during indexing, and cache the result by content hash so unchanged documents are never processed twice.

Attach metadata to every chunk

Metadata is extracted per document but stored per chunk, because chunks are what you search and filter. Add chunk-level fields too: the chunk's position and the section heading it falls under.

def make_chunk_records(doc_id: str, doc_meta: dict, chunks: list[str]) -> list[dict]:
    return [
        {
            "id": f"{doc_id}:{i}",
            "text": chunk,
            "metadata": {**doc_meta, "doc_id": doc_id, "chunk_index": i, "chunk_count": len(chunks)},
        }
        for i, chunk in enumerate(chunks)
    ]
Design tip

Decide your metadata schema before indexing: which fields exist, their types and allowed values. Vector databases filter efficiently only on fields you declare consistently, and adding a field later means re-indexing. The lesson Metadata Filtering and Multi-Tenancy shows how the fields are used.

Key takeaways

  • Metadata enables filtering, citation and ranking by recency or authority.
  • Combine path, file-property, content and LLM-extracted metadata, and treat file properties as hints.
  • Use a schema with fixed allowed values for LLM-extracted fields so filters work reliably.
  • Extract per document, store per chunk, and design the schema before you index.