Vector Store with FAISS
FAISS, or Facebook AI Similarity Search, is a library used for efficient similarity search and clustering of high-dimensional vectors. It is commonly used in AI applications such as semantic search, Retrieval-Augmented Generation (RAG), recommendation systems, and document retrieval.Topics Covered
- Indexing vectors with FAISS
- Persisting a FAISS index
- Loading and querying an index
1. What is a Vector Store?
A vector store stores numerical representations called embeddings. For example, a sentence embedding model converts text into a vector:2. Installing FAISS
Install the required libraries:faiss-cpu is sufficient for learning and small projects.
3. Indexing Vectors with FAISS
The basic workflow is:Important FAISS Concepts
Vector dimension
Every embedding has a fixed number of dimensions. For example:IndexFlatL2
A simple FAISS index is:
IndexFlatL2 performs similarity search using Euclidean distance.
The lower the distance:
4. Complete Example: Create and Query a Vector Store
Create a file named:5. How FAISS Search Works
When you execute:distances
Contains the similarity distances:
IndexFlatL2, smaller values indicate more similar vectors.
indices
Contains the positions of matching vectors:
6. Persisting a FAISS Index
Creating embeddings can take time for large datasets. Instead of recreating the FAISS index every time, we can save it to disk. FAISS provides:Save the Index
7. Complete Example: Save Documents and FAISS Index
8. Loading and Querying the Index
Create a file named:9. FAISS Vector Store Workflow
Use the same embedding model for both document embeddings and query embeddings.If you create document vectors using one model and query vectors using another incompatible model, the similarity search results may not be meaningful.
10. Using Cosine Similarity with FAISS
Sentence embeddings are often compared using cosine similarity. To use cosine similarity in FAISS:- Normalize the vectors.
- Use
IndexFlatIP.
11. IndexFlatL2 vs IndexFlatIP
For semantic search with sentence embeddings, normalized embeddings with
IndexFlatIP are a common and intuitive approach.
12. Key FAISS Methods
Create an index
Add vectors
Search vectors
Number of stored vectors
Save index
Load index
13. Important Points
- FAISS stores and searches numerical vectors efficiently.
- Text must first be converted into embeddings.
- The vector dimension must match the FAISS index dimension.
index.add()stores vectors in the index.index.search()finds the nearest vectors.kdetermines how many results are returned.faiss.write_index()saves the index.faiss.read_index()loads a previously saved index.- Store documents and metadata separately alongside the FAISS index.
- Use the same embedding model for indexing and querying.
- For cosine similarity, normalize embeddings and use
IndexFlatIP.