LangChain Document Loaders, Text Splitters and Vector Stores

Load documents, split them and store embeddings in LangChain vector stores.

Last Updated:

Module 13 · Lesson 3 of 5 · Intermediate

LangChain Document Loaders, Text Splitters and Vector Stores

Load documents, split them and store embeddings in LangChain vector stores.

The indexing half of a LangChain RAG application uses three kinds of components: document loaders read sources into Document objects, text splitters chunk them, and vector stores embed and store the chunks. This lesson builds a complete index with each of them and shows how to swap implementations.

What you will learn

  • The Document object and common document loaders
  • How to split documents with RecursiveCharacterTextSplitter and other splitters
  • How to embed and store chunks in an in-memory store and in Chroma
  • How to search a vector store directly, with scores and filters

Prerequisites

pip install -U langchain-core langchain-text-splitters langchain-community langchain-huggingface langchain-chroma pypdf sentence-transformers

The Document object

from langchain_core.documents import Document

doc = Document(page_content="Employees get 18 days of paid leave.",
               metadata={"source": "leave-policy.txt", "department": "hr"})

Everything in LangChain's indexing flow passes lists of Document objects: text in page_content, everything else in metadata.

Document loaders

Many loaders live in the langchain-community package; check the integration's documentation for its current package if an import fails.

from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader, TextLoader

text_docs = DirectoryLoader("docs", glob="**/*.txt", loader_cls=TextLoader,
                            loader_kwargs={"encoding": "utf-8"}).load()
pdf_docs = PyPDFLoader("reports/annual-report.pdf").load()        # one Document per page
print(len(text_docs), len(pdf_docs), pdf_docs[0].metadata)
3 42 {'source': 'reports/annual-report.pdf', 'page': 0, ...}

PDF page numbers in metadata start at 0. Other loaders cover web pages, Word files, CSV, Notion, Confluence and many more. You can always build Document objects yourself from your own loaders (Loading Documents).

Text splitters

from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=120, add_start_index=True)
chunks = splitter.split_documents(text_docs + pdf_docs)
print(len(chunks), chunks[0].metadata)            # metadata is copied to every chunk

md_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=[("#", "h1"), ("##", "h2")])
sections = md_splitter.split_text("# Handbook\n## Leave\nEmployees get 18 days.\n## Expenses\nSubmit within 30 days.")
print([(s.metadata, s.page_content) for s in sections])
[({'h1': 'Handbook', 'h2': 'Leave'}, 'Employees get 18 days.'), ({'h1': 'Handbook', 'h2': 'Expenses'}, 'Submit within 30 days.')]

add_start_index=True records each chunk's character offset in the source, useful for citations. Splitting strategies are explained in Module: Chunking.

Embeddings

from langchain_huggingface import HuggingFaceEmbeddings

embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5",
                                   encode_kwargs={"normalize_embeddings": True})
vector = embeddings.embed_query("How many leave days?")
print(len(vector))      # 384

Swap in OpenAIEmbeddings (langchain-openai) or OllamaEmbeddings (langchain-ollama) without changing the rest of the code.

Vector stores

In memory (for learning and tests)

from langchain_core.vectorstores import InMemoryVectorStore

store = InMemoryVectorStore(embeddings)
store.add_documents(chunks)
for doc in store.similarity_search("carry over unused leave", k=2):
    print(doc.metadata["source"], "|", doc.page_content[:60])

Chroma (persistent)

from langchain_chroma import Chroma

chroma = Chroma(collection_name="policies", embedding_function=embeddings, persist_directory="lc_chroma")
ids = [f"{c.metadata['source']}:{c.metadata.get('start_index', i)}" for i, c in enumerate(chunks)]
chroma.add_documents(chunks, ids=ids)               # stable ids allow updates and deletes

results = chroma.similarity_search_with_score("hotel limit", k=3, filter={"source": "docs/expenses.txt"})
for doc, distance in results:
    print(round(distance, 3), doc.page_content[:60])

All vector stores share methods such as add_documents, similarity_search, delete and as_retriever. Filter syntax and score meaning (similarity or distance) differ by store; check each integration's documentation.

Common errors and troubleshooting

  • Module not found for a loader: install langchain-community and any library the loader needs (for example pypdf).
  • Duplicate chunks after re-running: pass stable ids to add_documents, or delete old ids first.
  • Dimension mismatch in Chroma: the collection was created with another embedding model; use a new collection name.
  • Metadata type errors: some stores accept only simple metadata values (strings, numbers, booleans).

Key takeaways

  • LangChain indexing works on lists of Document objects.
  • Loaders read sources, splitters chunk them while keeping metadata, embeddings and vector stores index them.
  • Use stable ids for updates; filters and scores vary between vector stores.

Frequently asked questions

Which vector store should I start with?

InMemoryVectorStore for learning, Chroma for local persistence, and PGVector, Qdrant or a managed store for production (LangChain with pgvector).

Can I use my own chunking code?

Yes: create Document objects from your chunks and add them to any vector store.

Practice exercises

  1. Load a folder of PDFs and Markdown files, split them, and print the average chunk length per file type.
  2. Delete all chunks of one source from Chroma using their ids and re-add a changed version.

Related tutorials