Indexing API
Relevant source files
The following files were used as context for generating this wiki page:
The LangChain Indexing API provides a robust mechanism for populating and synchronizing a VectorStore or DocumentIndex with documents from a data source. It is designed to be efficient by avoiding redundant work, tracking which documents have been added, updated, or deleted. This ensures that the vector store remains a current representation of the source data, which is crucial for Retrieval-Augmented Generation (RAG) applications.
The core of the API is the index function, which orchestrates the process of loading, hashing, comparing, and writing documents. It uses a RecordManager to maintain the state of the indexed documents, allowing for intelligent updates and cleanups. This system supports various cleanup strategies to handle stale documents, making it a versatile tool for managing document indexes.
Core Components
The Indexing API is built around three main components that work together to manage the lifecycle of documents in a vector store.
docs_source: The source of documents, which can be aBaseLoaderor anyIterable[Document]. This provides the documents to be indexed.record_manager: An instance of aRecordManagersubclass. This component is responsible for tracking the state of indexed documents, including their hashes and source IDs, to determine whether they are new, updated, or should be deleted.vector_store: The destination for the indexed documents. This can be any object that conforms to theVectorStoreorDocumentIndexinterface, where the document embeddings are stored for retrieval.
Sources: libs/core/langchain_core/indexing/api.py:276-282
The index and aindex Functions
The primary entry points to the indexing functionality are the synchronous index function and its asynchronous counterpart aindex. These functions handle the entire indexing workflow, from loading documents to cleaning up stale entries.
This diagram illustrates the high-level interaction between the user-provided components and the index function.
Parameters
The index and aindex functions accept several parameters to customize the indexing behavior.
| Parameter | Type | Description |
|---|---|---|
docs_source | Union[BaseLoader, Iterable[Document]] | The source of documents to be indexed. |
record_manager | RecordManager | The manager for tracking document state. |
vector_store | Union[VectorStore, DocumentIndex] | The vector store to index documents into. |
batch_size | int | The number of documents to process in a single batch. Default is 100. |
cleanup | Optional[Literal["incremental", "full", "scoped_full"]] | The strategy for cleaning up stale documents. |
source_id_key | Union[str, Callable[[Document], str], None] | A key or function to extract a source ID from a document's metadata. Required for incremental and scoped_full cleanup. |
cleanup_batch_size | int | The batch size for deletion operations during cleanup. Default is 1,000. |
force_update | bool | If True, forces re-indexing of all documents, even if they appear to be up-to-date. Default is False. |
key_encoder | Union[Literal["sha1", ...], Callable] | The hashing algorithm or function used to generate a unique ID for each document. Default is sha1. |
upsert_kwargs | Optional[dict[str, Any]] | Additional keyword arguments to pass to the vector store's add_documents or upsert method. |
Sources: libs/core/langchain_core/indexing/api.py:273-318
Return Value: IndexingResult
Both index and aindex return an IndexingResult object, which is a TypedDict that provides a summary of the operation.
| Key | Type | Description |
|---|---|---|
num_added | int | The number of new documents added to the vector store. |
num_updated | int | The number of documents that were updated because they were not up-to-date. |
num_deleted | int | The number of stale documents deleted from the vector store. |
num_skipped | int | The number of documents skipped because they were already up-to-date. |
Sources: libs/core/langchain_core/indexing/api.py:259-270
Indexing Process Flow
The indexing process is a multi-step workflow that ensures the vector store is efficiently synchronized with the source documents.
This diagram shows the sequence of operations within the index function.
Document Hashing and Deduplication
To track documents, the API generates a unique ID for each document by hashing its content and metadata. This allows for efficient checking of whether a document has changed.
The key_encoder parameter in the index function controls the hashing. It can be a string specifying a standard algorithm (sha1, sha256, sha512, blake2b) or a custom callable function. The default is sha1, but a warning is issued as it is not collision-resistant. For new applications, a stronger algorithm like sha256 or blake2b is recommended.
Within each batch of documents, the API also performs deduplication based on these generated hashes, ensuring that identical documents are not processed multiple times.
Sources: libs/core/langchain_core/indexing/api.py:182-226, libs/core/langchain_core/indexing/api.py:357-365
State Management with RecordManager
The RecordManager is a crucial component for tracking the state of the index. It's an abstract base class that defines the interface for recording when documents are written to the vector store.
This class diagram shows the RecordManager interface and its SQLRecordManager implementation.
SQLRecordManager is a concrete implementation that uses a SQL database (via SQLAlchemy) to store the document records. It manages a table to keep track of document keys, group IDs (source IDs), and the timestamp of the last update.
Sources: libs/langchain/langchain/indexes/_sql_record_manager.py
Cleanup Strategies
The cleanup parameter controls how stale documents (i.e., documents present in the vector store but not in the current docs_source) are handled.
| Strategy | Description |
|---|---|
None | No cleanup is performed. Stale documents are left in the vector store. |
incremental | Deletes documents associated with source IDs seen during the current indexing run that were not updated. This is done continuously during indexing. Requires source_id_key. |
full | Deletes all documents in the vector store that were not updated during the current indexing run. This is performed after all new documents have been indexed. |
scoped_full | A mix of full and incremental. It deletes all documents associated with source IDs seen during the current indexing run that were not updated. This is performed after all new documents have been indexed. Requires source_id_key. |
Sources: libs/core/langchain_core/indexing/api.py:290-302
Usage Example: VectorStoreIndexWrapper
The VectorStoreIndexWrapper provides a high-level, convenient way to use the indexing API. It encapsulates a vector store, an embedding model, and a text splitter, and exposes a simple index method that calls the underlying langchain_core.indexing.index function. This wrapper simplifies the process of creating and maintaining a vector store index from documents.
The _get_source_id_assigner function is used internally to get the source ID from a document's metadata, which is essential for cleanup operations.
Sources: libs/langchain/langchain/indexes/vectorstore.py:21-46, libs/core/langchain_core/indexing/api.py:110-123
Conclusion
The LangChain Indexing API is a powerful and flexible system for managing the lifecycle of documents within a vector store. By leveraging a RecordManager to track state and providing multiple cleanup strategies, it automates the often complex task of keeping a document index synchronized with its source data. This functionality is fundamental for building reliable and up-to-date RAG systems that can depend on the freshness and accuracy of their underlying data.