MarkdownHeaderSplitter
MarkdownHeaderSplitter
ATX 스타일 Markdown 헤더(#, ## 등)에서 문서를 분할하고, 선택적으로 2차 분할을 적용하는 컴포넌트예요. 헤더 계층 구조는 각 청크의 메타데이터로 보존돼요. 인덱싱 파이프라인에서 Converter와 DocumentCleaner 뒤에 두면 돼요.
본문
개요
MarkdownHeaderSplitter는 텍스트 문서를 다음과 같이 처리해요.
- ATX 스타일 Markdown 헤더(
#,##, …,######)에서 문서를 청크로 분할하면서, 헤더 계층 구조를 메타데이터로 보존해요. - 선택적으로 Haystack의
DocumentSplitter를 사용해 각 청크에 2차 분할(단어·단락·문장·줄 단위)을 적용해요. - 상위 헤더, 페이지 번호, 분할 ID 같은 메타데이터를 보존하고 전파해요.
ATX 스타일 헤더(예: # Title)만 인식돼요. Setext 스타일 헤더(===로 밑줄 긋기)는 지원되지 않아요.
컴포넌트를 초기화할 때 설정할 수 있는 파라미터가에요.
page_break_character: 페이지 나눔을 식별하는 데 쓰는 문자. 기본값은 폼 피드\f.keep_headers:True면 헤더가 청크 내용에 남아요.False면 헤더가 메타데이터로만 이동해요. 기본값은True.secondary_split: 헤더 분할 후의 선택적 2차 분할. 옵션:None,"word","passage","period","line". 기본값은None.split_length: 2차 분할 사용 시 분할당 최대 단위 수. 기본값은200.split_overlap: 2차 분할 사용 시 분할 사이에 겹치는 단위 수. 기본값은0.split_threshold: 2차 분할 사용 시 분할당 최소 단위 수. 기본값은0.skip_empty_documents: 내용이 비어 있는 문서를 건너뛸지. 기본값은True.
각 출력 문서의 메타데이터에는 다음이 포함돼요.
source_id: 원본 문서의 ID.page_number: 페이지 번호.page_break_character를 찾으면 갱신돼요.split_id: 상위 문서 내에서의 청크 인덱스.header: 이 청크의 헤더 텍스트.parent_headers: 계층 순서대로 된 상위 헤더 텍스트 목록.
컴포넌트는 텍스트 문서에서만 동작해요. 내용이 None이거나 문자열이 아닌 문서는 ValueError를 발생시켜요.
사용법
단독 사용:
from haystack import Document
from haystack.components.preprocessors import MarkdownHeaderSplitter
text = (
"# Introduction\n"
"This is the intro section.\n"
"## Getting Started\n"
"Here is how to start.\n"
"## Advanced\n"
"Advanced content here."
)
doc = Document(content=text)
splitter = MarkdownHeaderSplitter(keep_headers=True)
result = splitter.run(documents=[doc])
# result["documents"] contains one document per header section,
# with meta["header"], meta["parent_headers"], meta["source_id"], and so on
2차 분할과 함께:
섹션이 길 때 단어 단위로 2차 분할을 추가해서 각 청크가 최대 크기를 넘지 않게 할 수 있어요.
from haystack import Document
from haystack.components.preprocessors import MarkdownHeaderSplitter
text = "# Section\n" + "Some long body text. " * 50
doc = Document(content=text)
splitter = MarkdownHeaderSplitter(
keep_headers=True,
secondary_split="word",
split_length=20,
split_overlap=2,
)
result = splitter.run(documents=[doc])
파이프라인 안에서:
이 파이프라인은 Markdown 파일을 문서로 변환하고, 정리하고, 헤더로 분할한 뒤 인메모리 문서 저장소에 작성해요.
from pathlib import Path
from haystack import Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.converters.txt import TextFileToDocument
from haystack.components.preprocessors import MarkdownHeaderSplitter
from haystack.components.writers import DocumentWriter
document_store = InMemoryDocumentStore()
p = Pipeline()
p.add_component("text_file_converter", TextFileToDocument())
p.add_component("splitter", MarkdownHeaderSplitter(keep_headers=True))
p.add_component("writer", DocumentWriter(document_store=document_store))
p.connect("text_file_converter.documents", "splitter.documents")
p.connect("splitter.documents", "writer.documents")
path = "path/to/your/files"
files = list(Path(path).glob("*.md"))
p.run({"text_file_converter": {"sources": files}})