LangChain Document Loading and Splitting
In the previous chapter, we introduced LangChain RAG, which uses Embedding and vector databases to let large models answer questions based on external knowledge.
But the previous examples mainly used manually written text. In real projects, a knowledge base may come from PDFs, web pages, Markdown, TXT, CSV, or even an entire document directory.
To use this content for RAG, two steps are usually required first: Document Loader (document loading) and Text Splitter (text splitting).
This chapter is based on LangChain 1.x and introduces common document loaders, Document objects, Chinese text splitting, Markdown heading splitting, and the complete document vectorization workflow.
1. Why do we need document loading and splitting?
A typical RAG knowledge base creation workflow is as follows:
PDF / TXT / Markdown / 网页
↓
Document Loader
↓
Document 对象
↓
Text Splitter
↓
多个文档 Chunk
↓
Embedding 模型
↓
VectorStore
↓
Retriever 检索
The two components have different responsibilities:
| Component | Purpose | Input | Output |
|---|---|---|---|
| Document Loader | Read and parse raw documents | Files, URLs, etc. | Document list |
| Text Splitter | Split documents into smaller chunks | Text or Document | Text chunks or Document list |
The purpose of document splitting is not only to meet model length limits, but more importantly to improve the accuracy of knowledge retrieval.
For example, for a tutorial containing 100 Python knowledge points, if the entire document generates only one vector, searching for a specific knowledge point may be interfered with by a large amount of irrelevant content.
After splitting the document properly, the retrieval system can return chunks more relevant to the question.
2. Document: LangChain's unified document format
Whether loading TXT, PDF, or web pages, LangChain usually converts the content into Document object.
Document contains three common fields:
| property | Description |
|---|---|
page_content |
Document body |
metadata |
Metadata such as source, page number, and title |
id |
Optional document identifier |
Example: manually creating a Document
Example
from
langchain_core.
documents
import
Document
doc
=
Document
(
page_content
=
"Python is a general-purpose programming language suitable for beginners."
,
metadata
=
{
"source"
:
"python-tutorial.txt"
,
"category"
:
"python"
,
"title"
:
"Python Getting Started"
}
)
(
"Content:"
,
doc.
page_content
)
(
"Source: "
,
doc.
metadata
[
"source"
]
)
Output:
内容: Python 是一种通用编程语言,适合初学者学习。
Source: python-tutorial.txt
metadata very important; subsequent RAG retrieval can use it to display document sources, filter user permissions, or locate original materials.
3. Common Document Loaders
LangChain provides a variety of document loaders covering common file and web content.
| Loader | Supported formats | Main dependencies |
|---|---|---|
TextLoader |
TXT, plain text | langchain-community |
PyPDFLoader |
langchain-community、pypdf | |
WebBaseLoader |
Web page HTML | langchain-community、beautifulsoup4 |
CSVLoader |
CSV | langchain-community |
UnstructuredMarkdownLoader |
Markdown | langchain-community、unstructured |
DirectoryLoader |
Multiple files in a directory | langchain-community and corresponding Loader dependencies |
Common dependency installation:
pip install -U langchain-core langchain-community langchain-text-splitters pypdf beautifulsoup4 unstructured python-dotenv
If you need to build a vector knowledge base, you can further install:
pip install -U langchain-openai langchain-chroma
Note that different Loaders may have additional dependencies. Install according to the actual file format; there is no need to install all document parsing libraries at once.
4. TextLoader: loading TXT files
TextLoader Used to read local plain text files, it is the simplest document loader.
For example, create knowledge.txt:
Python 是一种常用的编程语言。
Python 支持面向对象编程。
初学者可以先学习变量、列表、循环和函数。
Example: reading a text file
Example
from
langchain_community.
document_loaders
import
TextLoader
loader
=
TextLoader
(
"knowledge.txt"
,
encoding
=
"utf-8"
)
docs
=
loader.
load
(
)
(
"Number of documents:"
,
len
(
docs
)
)
for
doc
in
docs:
(
"Content:"
,
doc.
page_content
)
(
"Metadata:"
,
doc.
metadata
)
For ordinary TXT, a Document is usually returned, whose metadata contains the source file path.
For example:
文档数量: 1
元数据: {'source': 'knowledge.txt'}
Note:load() Reading a file and returning a Document list does not mean the text has been split.
For larger text files, you still need to use a Text Splitter.
5. PyPDFLoader: loading PDF documents
PDF is a common document format in enterprise knowledge bases.
LangChain can use PyPDFLoader to extract text content from PDFs.
Example: reading a PDF
Example
from
langchain_community.
document_loaders
import
PyPDFLoader
loader
=
PyPDFLoader
(
"python-guide.pdf"
)
docs
=
loader.
load
(
)
(
"Number of documents:"
,
len
(
docs
)
)
for
doc
in
docs
[
:
2
]
:
(
"Page number:"
,
doc.
metadata
.
get
(
"page"
)
)
(
"Source: "
,
doc.
metadata
.
get
(
"source"
)
)
(
"Content:"
,
doc.
page_content
[
:
150
]
)
Typically, when loading a PDF page by page, one Document is generated per page.
Metadata may include:
{
"source": "python-guide.pdf",
"page": 0
}
The page number usually starts from 0. When displaying page numbers to ordinary users, you can add 1 as appropriate.
How to handle scanned PDFs?
It needs special attention that a PDF does not necessarily contain extractable text.
For example:
- Ordinary electronic PDF: text can usually be extracted directly.
- Scanned PDF: pages may be images and require OCR.
- PDF with complex tables: text order may differ from the visual layout.
- Two-column papers: reading order and layout analysis may be required.
Therefore, for documents requiring high accuracy such as contracts, financial statements, and exam papers, you cannot rely solely on PDF text extraction results; you should add OCR, layout analysis, and manual verification as needed.
6. WebBaseLoader: loading web pages
WebBaseLoader It can read web pages and extract text from HTML.
For example, to read a programming tutorial page:
Example
from
langchain_community.
document_loaders
import
WebBaseLoader
url
=
"https://www.runoob.com/python/python-tutorial.html"
loader
=
WebBaseLoader
(
url
)
docs
=
loader.
load
(
)
for
doc
in
docs:
(
"Source: "
,
doc.
metadata
.
get
(
"source"
)
)
(
"Content:"
,
doc.
page_content
[
:
300
]
)
Note that web page loading usually obtains the page text, not necessarily only the article body.
For example, a page may also contain:
- Top navigation.
- Sidebar.
- Footer copyright information.
- Related recommendations.
- Advertisements or other non-body elements.
If you want to use web pages for RAG, it is recommended to further extract the main article content to avoid navigation and repeated page elements affecting retrieval.
**Note:** WebBaseLoader is not a full browser. For web pages that rely on JavaScript to dynamically load content, ordinary HTTP loading may not obtain the finally rendered article.
Before crawling a website in bulk, you should also comply with the target site's access rules and set a reasonable request rate.
7. CSVLoader: loading CSV data
In addition to ordinary documents, LangChain can also load CSV tabular data.
For example, create courses.csv:
name,level,category
Python基础,入门,Python
Java基础,入门,Java
HTML基础,入门,前端
Example: reading CSV
Example
from
langchain_community.
document_loaders
import
CSVLoader
loader
=
CSVLoader
(
file_path
=
"courses.csv"
,
encoding
=
"utf-8"
)
docs
=
loader.
load
(
)
(
"Number of records:"
,
len
(
docs
)
)
for
doc
in
docs:
(
doc.
page_content
)
(
doc.
metadata
)
CSVLoader usually converts each row into a Document.
But note that the large numbers, amounts, and statistical indicators in a CSV are not necessarily all suitable for conversion into vectors for computation.
If a task involves precise filtering, summation, sorting, or statistics, you should usually use structured data tools such as databases, SQL, or pandas.
8. Markdown document loading
Markdown is commonly used for technical tutorials, development documentation, and project READMEs.
You can use the UnstructuredMarkdownLoader Loading:
Example
from
langchain_community.
document_loaders
import
UnstructuredMarkdownLoader
loader
=
UnstructuredMarkdownLoader
(
"README.md"
,
mode
=
"single"
)
docs
=
loader.
load
(
)
(
"Number of documents:"
,
len
(
docs
)
)
(
docs
[
0
]
.
page_content
[
:
300
]
)
This example parses Markdown into text Documents.
For Markdown knowledge bases where you want to preserve heading hierarchy, you can also combine with MarkdownHeaderTextSplitter splitting by heading.
This is usually better than splitting technical documents purely by a fixed character count for preserving chapter structure.
9. DirectoryLoader: loading an entire directory in bulk
Real projects may have dozens or even hundreds of documents.
You can use the DirectoryLoader Load in bulk by file type.
For example:
knowledge/
├── python.txt
├── java.txt
└── html.txt
Example: reading TXT in bulk
Example
from
langchain_community.
document_loaders
import
DirectoryLoader
,
TextLoader
loader
=
DirectoryLoader
(
"./knowledge"
,
glob
=
"**/*.txt"
,
loader_cls
=
TextLoader
,
loader_kwargs
=
{
"encoding"
:
"utf-8"
}
,
silent_errors
=
False
)
docs
=
loader.
load
(
)
(
"Number of Documents loaded:"
,
len
(
docs
)
)
Where:
glob: specifies the files to match.loader_cls: specifies the loader actually used.loader_kwargs: passes parameters to the loader.silent_errors: whether to ignore some loading errors.
If a directory contains PDF, TXT, and Markdown at the same time, you can read them with the corresponding loaders separately and then merge the Document lists.
10. Text Splitter: document splitting
After documents are loaded, the next step is to split long text into chunks suitable for retrieval.
LangChain refers to these chunks as Chunks.
For example:
一篇 3000 字的文章
↓
TextSplitter
↓
Chunk 1:Python 基础语法
Chunk 2:变量与数据类型
Chunk 3:条件判断
Chunk 4:循环语句
Chunk 5:函数和模块
↓
分别建立向量索引
Ideally, each Chunk should contain sufficiently independent knowledge content without introducing too much irrelevant information.
11. RecursiveCharacterTextSplitter
RecursiveCharacterTextSplitter is the general-purpose text splitter recommended by LangChain.
It recursively tries to split text according to a set of separators, preserving natural structures such as paragraphs and sentences as much as possible.
For Chinese content, it is recommended to explicitly add Chinese punctuation.
Example: splitting a Chinese tutorial
Example
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
text
=
"""Python is a simple and easy-to-learn programming language, suitable for beginners.
Python supports multiple data types, including integers, floats, strings, lists, and dictionaries.
Conditional statements are used to control program flow; common syntax includes if, elif, and else.
Loops can repeatedly execute code; Python provides two common loops: for and while.
Functions are used to encapsulate repeated logic, can accept parameters, and return computation results."""
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
65
,
chunk_overlap
=
15
,
separators
=
[
"\n\n"
,
"\n"
,
"。"
,
"!"
,
"?"
,
";"
,
","
,
" "
,
""
]
,
length_function
=
len
)
chunks
=
splitter.
split_text
(
text
)
(
"Original text length:"
,
len
(
text
)
)
(
"Number of chunks:"
,
len
(
chunks
)
)
for
i
,
chunk
in
enumerate
(
chunks
,
1
)
:
(
f
"\n--- Chunk {i}: {len(chunk)} characters ---"
)
(
chunk
)
Here we deliberately set chunk_size to 65 to make it easy to observe the splitting effect.
After running, it prints the actual number, content, and length of the generated Chunks.
If you change chunk_size to 500 while the original text is less than 500 characters, you will usually get only one Chunk.
**Note:** splitting results depend on the content, separators, character length, and overlap rules; the number of Chunks generated in one run should not be treated as a fixed result.
12. chunk_size and chunk_overlap
The two most important parameters of a Text Splitter are:
| Parameters | Meaning | Example |
|---|---|---|
chunk_size |
The target maximum length of each chunk | 500 |
chunk_overlap |
The target overlap length between adjacent chunks | 50 |
chunk_size
If set as follows:
chunk_size=500
Under the default length_function=len , length is usually calculated by Python character count rather than Token count.
Chinese characters are usually counted as one character each.
chunk_overlap
For example:
chunk_size=100
chunk_overlap=20
means you want a certain context overlap between adjacent chunks.
but chunk_overlap=20 does not mean that every two Chunks necessarily overlap by exactly 20 characters.
Actual overlap is affected by paragraph boundaries and the splitting algorithm.
In addition, the more overlap there is, the more text is indexed repeatedly, which may increase Embedding costs and the duplication rate of retrieval results.
13. Guidelines for setting splitting parameters
Different types of documents may require different suitable splitting methods.
The following are character count ranges that can be used for initial testing, not fixed optimal parameters.
| Document type | chunk_size | chunk_overlap | Recommendation |
|---|---|---|---|
| FAQ Q&A | 200~500 | 0~50 | Keep complete Q&A pairs as much as possible |
| Programming tutorials | 500~1000 | 50~150 | Preserve knowledge points and code examples |
| Technical documentation | 500~1200 | 50~150 | Prioritize preserving chapter structure |
| Long articles | 800~1500 | 100~200 | Avoid context breaks |
| Code documentation | Split by function or class | Set as needed | Do not arbitrarily truncate functions |
For example, for a Python tutorial, it is recommended to keep the following content in the same chunk as much as possible:
知识点标题
↓
原理说明
↓
Python 示例代码
↓
运行结果与解释
If code and explanation are scattered across different Chunks, retrieving one of the chunks may not yield complete knowledge content.
14. split_text() and split_documents()
LangChain Text Splitter mainly provides three common methods.
| Method | Input | Output |
|---|---|---|
split_text() |
A string | A list of strings |
create_documents() |
A list of strings | Document list |
split_documents() |
Document list | Document list |
Example: preserving source information
Example
from
langchain_core.
documents
import
Document
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
docs
=
[
Document
(
page_content
=
"Python is a programming language."
100
,
metadata
=
{
"source"
:
"python-guide.txt"
,
"category"
:
"python"
}
)
]
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
200
,
chunk_overlap
=
30
,
add_start_index
=
True
)
chunks
=
splitter.
split_documents
(
docs
)
(
"Original document count:"
,
len
(
docs
)
)
(
"Number of chunks after splitting:"
,
len
(
chunks
)
)
for
chunk
in
chunks
[
:
2
]
:
(
"Source: "
,
chunk
.
metadata
.
get
(
"source"
)
)
(
"Start position:"
,
chunk
.
metadata
.
get
(
"start_index"
)
)
(
"Content:"
,
chunk
.
page_content
[
:
60
]
)
Use split_documents() can make the split Documents inherit the original document's metadata.
add_start_index=True You can also record the starting character position for each chunk to facilitate locating the original text.
**Recommendation:** in RAG projects, prefer using split_documents(), because preserving metadata such as source and page is very important.
15. MarkdownHeaderTextSplitter: splitting by heading
For tutorials, READMEs, and technical documentation, Markdown often has a clear heading hierarchy.
For example:
# Python 教程
## 变量
## Data Type
## 条件判断
## Loop statements
If you split directly by fixed length, different chapters may be mixed together.
You can use the MarkdownHeaderTextSplitter Prioritize splitting by headings.
Example: preserving Markdown heading information
Example
from
langchain_text_splitters
import
MarkdownHeaderTextSplitter
markdown
=
"""# Python Tutorial
Variables
Variables are used to store data.
List
Lists can store multiple elements.
function
Functions are used to encapsulate repeated logic.
"""
headers
=
[
(
"#"
,
"Chapter"
)
,
(
"##"
,
"Knowledge point"
)
]
splitter
=
MarkdownHeaderTextSplitter
(
headers_to_split_on
=
headers
)
docs
=
splitter.
split_text
(
markdown
)
for
doc
in
docs:
(
"Content:"
,
doc.
page_content
)
(
"Metadata:"
,
doc.
metadata
)
After splitting, each Document can retain the corresponding heading hierarchy.
For example:
内容: 变量用于保存数据。
元数据: {'章节': 'Python 教程', '知识点': '变量'}
This approach is especially suitable for programming tutorials organized by chapter.
If a Markdown chapter itself is still very long, you can continue to use RecursiveCharacterTextSplitter for a second round of splitting.
16. How to handle code documents?
Code differs from ordinary articles; you cannot arbitrarily truncate it by fixed length, otherwise a function or class may be split into two incomplete parts.
LangChain's RecursiveCharacterTextSplitter supports setting separators according to the programming language.
Example: splitting Python code
Example
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
,
Language
code
=
"""
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
def hello(name):
return f"Hello {name}"
"""
splitter
=
RecursiveCharacterTextSplitter.
from_language
(
language
=
Language.
PYTHON
,
chunk_size
=
100
,
chunk_overlap
=
10
)
chunks
=
splitter.
split_text
(
code
)
for
i
,
chunk
in
enumerate
(
chunks
,
1
)
:
(
f
"Chunk {i}:"
)
(
chunk
)
This approach uses separators suitable for Python, splitting as close as possible to structures such as classes or functions.
But it is not equivalent to a full Python AST parser, nor can it guarantee that all functions remain intact.
If you need to build high-quality code repository retrieval, you can further use Tree-sitter or AST parsing to build indexes at function, class, and module boundaries.
17. Complete workflow: loading, splitting, vectorization
The following combines the previous operations to build a simple local knowledge base.
Workflow:
本地 TXT 文件
↓
TextLoader
↓
Document
↓
RecursiveCharacterTextSplitter
↓
多个 Chunk
↓
OpenAI Embedding
↓
Chroma
↓
相似度检索
Install dependencies:
pip install -U langchain-community langchain-text-splitters langchain-openai langchain-chroma python-dotenv
in .env Configure in :
OPENAI_API_KEY=your_openai_api_key
Complete example: creating a course knowledge base
To let readers run it directly, the following program automatically creates a local test TXT file.
Filename:build_knowledge.py
Complete example
import
hashlib
from
pathlib
import
Path
from
dotenv
import
load_dotenv
from
langchain_community.
document_loaders
import
TextLoader
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
from
langchain_openai
import
OpenAIEmbeddings
from
langchain_chroma
import
Chroma
load_dotenv
(
)
1. Prepare the teaching test document
path
=
Path
(
"runoob_knowledge.txt"
)
if
not
path.
exists
(
)
:
path.
write_text
(
"""The Python Basics Tutorial introduces variables, data types, conditional statements, loops, and functions.
Python lists are used to store a group of data, and elements can be accessed by index.
Python dictionaries organize data through key-value pairs, suitable for storing structured information.
The HTML tutorial introduces common tags, links, images, forms, and web page structure.
The Java tutorial introduces classes, objects, inheritance, interfaces, and exception handling.
"""
,
encoding
=
"utf-8"
)
2. Load documents
loader
=
TextLoader
(
str
(
path
)
,
encoding
=
"utf-8"
)
docs
=
loader.
load
(
)
3. Split documents
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
80
,
chunk_overlap
=
10
,
separators
=
[
"\n\n"
,
"\n"
,
"。"
,
","
,
" "
,
""
]
,
add_start_index
=
True
)
chunks
=
splitter.
split_documents
(
docs
)
4. Initialize Embedding
embeddings
=
OpenAIEmbeddings
(
model
=
"text-embedding-3-small"
)
5. Connect to persistent Chroma
vector_store
=
Chroma
(
collection_name
=
"runoob_loader_demo"
,
embedding_function
=
embeddings
,
persist_directory
=
"./runoob_chroma_db"
)
6. Manage chunks with stable IDs
ids
=
[
hashlib.
sha256
(
f
"{path}:{doc.metadata.get('start_index')}:{doc.page_content}"
.
encode
(
)
)
.
hexdigest
(
)
for
doc
in
chunks
]
vector_store.
add_documents
(
chunks
,
ids
=
ids
)
(
"Original Document count:"
,
len
(
docs
)
)
(
"Chunk count:"
,
len
(
chunks
)
)
7. Semantic search
results
=
vector_store.
similarity_search
(
"What is a Python list?"
,
k
=
2
)
for
i
,
doc
in
enumerate
(
results
,
1
)
:
(
f
"\nRetrieval result {i}:"
)
(
"Content:"
,
doc.
page_content
)
(
"Source: "
,
doc.
metadata
.
get
(
"source"
)
)
After running, you may get something like:
原始 Document 数量: 1
Chunk 数量: 5
检索结果 1:
内容: Python 列表用于保存一组数据,可以通过索引访问元素。
Source: runoob_knowledge.txt
The actual Chunk count and retrieval ranking depend on the current document content, splitting parameters, and Embedding model.
Here, content-related fixed IDs are used to avoid generating new random IDs every time the same document is run repeatedly.
However, if the original text is modified, the IDs of old content may remain in the database. Therefore, production environments also need to implement deletion of old chunks or a synchronization mechanism based on document versions.
18. Index building and online retrieval should be separated
A RAG system usually consists of two independent workflows:
build_index.py
加载文档
文档切分
Embedding
保存向量数据库
search.py
连接向量数据库
检索问题
返回相关资料
Index building is usually performed only when documents are added or updated.
Each time a user asks a question, there is no need to reload all documents and generate Embeddings.
Example: connecting to an existing knowledge base
Example
from
langchain_openai
import
OpenAIEmbeddings
from
langchain_chroma
import
Chroma
embeddings
=
OpenAIEmbeddings
(
model
=
"text-embedding-3-small"
)
vector_store
=
Chroma
(
collection_name
=
"runoob_loader_demo"
,
embedding_function
=
embeddings
,
persist_directory
=
"./runoob_chroma_db"
)
results
=
vector_store.
similarity_search
(
"How to get started with Python?"
,
k
=
3
)
for
doc
in
results:
(
doc.
page_content
)
Here, use the same as when creating the index:
- Embedding model.
- Chroma collection name.
- Persistence directory.
**Note:** if you change the Embedding model or vector dimension, you should rebuild the corresponding index rather than directly mixing vectors generated by different models.
19. Recommendations for document processing in production
1. Preserve document sources
Preserve metadata such as source, title, page, and section for each Chunk to facilitate later display of sources and locating the original text.
2. Do not rely solely on fixed character count splitting
Tutorials are suitable for splitting by chapter, Markdown by heading, and code by function and class.
The splitting strategy should match the document structure.
3. Clean up irrelevant content
Navigation, footers, and repeated copyright information in web pages may affect retrieval.
It is recommended to extract the main text before building the index and clean up obviously irrelevant page elements.
4. Ensure the integrity of tables and code
If technical documentation contains tables or code examples, try to avoid completely separating table headers from data, or code from explanation.
5. Handle scanned PDFs
Scans need to be combined with OCR to obtain searchable text.
For contracts and financial materials that require high accuracy, the text recognition results should be further verified.
6. Implement index updates and deletion
After a document is modified, you not only need to add new Chunks, but also handle the corresponding old vectors to avoid retrieving outdated content.
7. Set up permission filtering
If the knowledge base contains users' private documents, retrieval must apply permission filtering based on trusted user identity; you cannot expose all documents directly to every user.
8. Evaluate the splitting effect
You can select real user questions, observe whether the retrieved Chunks completely contain the basis for the answer, and then adjust chunk_size, chunk_overlap, and separators.
20. Common questions
1. What is the difference between Document Loader and Text Splitter?
Loader is responsible for reading raw documents, and Text Splitter is responsible for splitting documents into small chunks.
2. Does TextLoader belong to the langchain core package?
This tutorial uses langchain_community.document_loaders.TextLoader, which requires installing langchain-community.
3. Why is only one Chunk obtained when chunk_size=500 is set?
If the original text itself is less than 500 characters, there is usually no need to split further.
4. Does chunk_overlap=50 mean an overlap of exactly 50 characters?
No. It is the target overlap length; the actual result is affected by separators and splitting boundaries.
5. Which should you choose, split_text() or split_documents()?
Use split_text() for ordinary strings; for RAG documents that need to preserve source metadata, prefer split_documents().
6. Can PDF Loader recognize scans?
Ordinary PDF text extraction cannot guarantee recognition of scanned images; OCR needs to be added depending on the document.
7. Should Markdown be split by character or by heading?
Markdown with a clear heading structure can be split by heading first, then overlong chapters can be split a second time.
8. Is ordinary text splitting suitable for code documents?
Simple projects can use the language-aware RecursiveCharacterTextSplitter; complex code repositories are recommended to use a syntax parser to split by function and class.
9. Why does vector retrieval return irrelevant chunks?
It may be related to factors such as document chunking, the Embedding model, the number of retrievals, and the quality of the original content.
10. Do documents need to be re-vectorized after modification?
Text chunks affected by the modification usually need their Embeddings updated, and the old chunks in the vector database need to be maintained synchronously.
11. Why is there a lot of irrelevant content when loading web pages?
Because web pages also contain elements such as navigation and footers, main text extraction and cleaning are needed before indexing.
12. Do you need to re-save source information after splitting?
Using split_documents() can usually inherit the original document's metadata, but it is still recommended to check whether the actual result retains the required fields.
Summary
Document loading and splitting are an important foundation for building a LangChain RAG knowledge base.
This chapter introduces:
Document: unified document object.TextLoader: read TXT files.PyPDFLoader: read PDF documents.WebBaseLoader: read web pages.CSVLoader: read CSV data.UnstructuredMarkdownLoader: read Markdown.DirectoryLoader: load directories in bulk.RecursiveCharacterTextSplitter: recursive character splitting.MarkdownHeaderTextSplitter: split by Markdown heading.split_documents(): document splitting that preserves metadata.Chroma: vectorize and store the split documents.
The most common processing workflow:
loader = TextLoader("knowledge.txt", encoding="utf-8")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size=800,
chunk_overlap=100
)
chunks = splitter.split_documents(docs)
vector_store.add_documents(chunks)
Core principles:The quality of RAG depends not only on the large model; whether document loading is accurate, whether splitting is reasonable, and whether source information is complete also affect the final retrieval and answer quality.