Faiss
Last updated
Last updated
Author:
Peer Review:
This is a part of
This tutorial covers how to use Faiss with LangChain .
Faiss (Facebook AI Similarity Search) is a library for efficient similarity search and clustering of dense vectors.
It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also includes supporting code for evaluation and parameter tuning.
This tutorial walks you through using CRUD operations with the Faiss storing , updating , deleting documents, and performing similarity-based retrieval .
[Note]
langchain-opentutorial
is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.
You can alternatively set API keys such as OPENAI_API_KEY
in a .env
file and load them.
[Note] This is not necessary if you've already set the required API keys in previous steps.
Faiss (Facebook AI Similarity Search) is a library for efficient similarity search and clustering of dense vectors.
Core Concepts
Similarity search: Finding vectors that are closest to a query vector
Scaling: Handles vector sets of any size, including those exceeding RAM
Efficiency: Optimized for memory usage and search speed
Vector Operations
Nearest neighbor: Finding k vectors closest to a query vector
Maximum inner product: Finding vectors with highest dot product
Clustering: Grouping similar vectors together
Index Types
Flat: Exact search with exhaustive comparison
IVF: Inverted file structure for faster approximate search
HNSW: Hierarchical navigable small world graphs for high-quality search
PQ: Product quantization for memory compression
OPQ: Optimized product quantization for better accuracy
Performance Metrics
Speed: Query time for finding similar vectors
Memory: RAM requirements for index storage
Accuracy: How well results match exhaustive search (recall)
Technical Features
GPU support: State-of-the-art GPU implementations with 5-20x speedup
Multi-threading: Parallel processing across CPU cores
SIMD optimization: Vectorized operations for faster computation
Half-precision: Float16 support for better performance
Applications
Image similarity: Finding visually similar images
Text embeddings: Semantic search in document collections
Recommendation systems: Finding similar items for users
Classification: Computing maximum inner-products for classification
This section guides you through the data preparation process .
This section includes the following components:
Data Introduction
Preprocess Data
In this tutorial, we will use the fairy tale π The Little Prince in PDF format as our data.
This material complies with the Apache 2.0 license .
The data is used in a text (.txt) format converted from the original PDF.
You can view the data at the link below.
In this tutorial section, we will preprocess the text data from The Little Prince and convert it into a list of LangChain Document
objects with metadata.
Each document chunk will include a title
field in the metadata, extracted from the first line of each section.
This part walks you through the initial setup of Faiss .
This section includes the following components:
Load Embedding Model
Load Faiss Client
In this section, you'll learn how to load an embedding model.
This tutorial uses OpenAI's API-Key for loading the model.
π‘ If you prefer to use another embedding model, see the instructions below.
In this section, we'll show you how to load the database client object using the Python SDK for Faiss .
For the LangChain-OpenTutorial, we have implemented a custom set of CRUD functionalities for VectorDBs.
The following operations are included:
upsert
: Update existing documents or insert if they donβt exist
upsert_parallel
: Perform upserts in parallel for large-scale data
similarity_search
: Search for similar documents based on embeddings
delete
: Remove documents based on filter conditions
Each of these features is implemented as class methods specific to each VectorDB.
In this tutorial, you'll learn how to use these methods to interact with your VectorDB.
We plan to continuously expand the functionality by adding more common operations in the future.
First, we create an instance of the Faiss helper class to use its CRUD functionalities.
This class is initialized with the Faiss Python SDK client instance, index name and the embedding model instance , both of which were defined in the previous section.
Now you can use the following CRUD operations with the crud_manager
instance.
These instance allow you to easily manage documents in your Faiss .
Update existing documents or insert if they donβt exist
β Args
texts
: Iterable[str] β List of text contents to be inserted/updated.
metadatas
: Optional[List[Dict]] β List of metadata dictionaries for each text (optional).
ids
: Optional[List[str]] β Custom IDs for the documents. If not provided, IDs will be auto-generated.
**kwargs
: Extra arguments for the underlying vector store.
π Return
None
Perform upsert in parallel for large-scale data
β Args
texts
: Iterable[str] β List of text contents to be inserted/updated.
metadatas
: Optional[List[Dict]] β List of metadata dictionaries for each text (optional).
ids
: Optional[List[str]] β Custom IDs for the documents. If not provided, IDs will be auto-generated.
batch_size
: int β Number of documents per batch (default: 32).
workers
: int β Number of parallel workers (default: 10).
**kwargs
: Extra arguments for the underlying vector store.
π Return
None
Search for similar documents based on embeddings .
This method uses "cosine similarity" .
β Args
query
: str β The text query for similarity search.
k
: int β Number of top results to return (default: 10).
**kwargs
: Additional search options (e.g., filters).
π Return
results
: List[Document] β A list of LangChain Document objects ranked by similarity.
Delete documents based on filter conditions
β Args
ids
: Optional[List[str]] β List of document IDs to delete. If None, deletion is based on filter.
filters
: Optional[Dict] β Dictionary specifying filter conditions (e.g., metadata match).
**kwargs
: Any additional parameters.
π Return
None
Set up the environment. You may refer to for more details.
You can checkout the for more details.