Embedding Search
Embedding search allows us to compare vector representations of data for the purposes of finding similar items and patterns. It enables AI systems to answer questions like, “Which items are most similar to this one?” or “What documents are relevant to this query?”
This Lesson Will Cover
- 📏 Understanding similarity metrics for vector comparison
- 📊 Scaling embedding search for large datasets
- 🛠️ Tools and databases for efficient vector search
- 🏗️ Building practical embedding search pipelines
- 🌍 Real-world applications and use cases
The Basics of Embedding Search
Embedding search operates by comparing vectors in a high-dimensional space. Given a query vector, the goal is to identify the vectors in a dataset that are closest to it based on a defined similarity metric.
Common Similarity Metrics
Here are the key similarity metrics used in embedding search:
| Metric | Description | Best For | Range |
|---|---|---|---|
| Cosine Similarity | Measures angle between vectors | Text similarity, direction-based comparisons | -1 to 1 |
| Euclidean Distance | Measures straight-line distance | Spatial data, absolute differences | 0 to ∞ |
| Manhattan Distance | Measures sum of absolute differences | High-dimensional sparse data, grid-based distances | 0 to ∞ |
Cosine Similarity
Cosine similarity measures the cosine of the angle between two vectors, effectively comparing their directional similarity regardless of magnitude.
Mathematical Formula:
where is the dot product, and and are the magnitudes of vectors and .
Intuitive Explanation:
- If two vectors point in the same direction, their cosine similarity is 1.
- If they point in opposite directions, it’s -1.
- If they’re perpendicular, it’s 0.
- It’s useful when the magnitude of the vectors is not meaningful.
Python Implementation:
import numpy as np
def cosine_similarity(v1, v2):
dot_product = np.dot(v1, v2)
norm_v1 = np.linalg.norm(v1)
norm_v2 = np.linalg.norm(v2)
return dot_product / (norm_v1 * norm_v2)
# Example
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
similarity = cosine_similarity(v1, v2)
theta = np.arccos(similarity) * 180 / np.pi
print(f"Cosine Similarity: {similarity:.4f} (angle: {theta:.4f} degrees)")
# Output: Cosine Similarity: 0.9746 (angle: 12.9332 degrees)
Euclidean Distance
Euclidean distance (L2 norm) measures the straight-line distance between two points in the vector space.
Mathematical Formula:
where and are corresponding elements of vectors and .
Intuitive Explanation:
This is the most intuitive distance metric - it’s literally the physical distance between two points. It’s useful when the magnitude of the vectors is meaningful.
Python Implementation:
def euclidean_distance(v1, v2):
return np.sqrt(np.sum((v1 - v2) ** 2))
# Example
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
distance = euclidean_distance(v1, v2)
print(f"Euclidean Distance: {distance:.4f}")
# Output: Euclidean Distance: 5.1962
Manhattan Distance
Manhattan distance (L1 norm) measures the sum of absolute differences between vector components.
Mathematical Formula:
where again, and are corresponding elements of vectors and .
Intuitive Explanation:
Imagine walking through a city grid - you can only walk along blocks, not diagonally. This metric is useful when dealing with sparse high-dimensional spaces because it is less sensitive to outliers and computationally simpler than Euclidean distance.
Python Implementation:
def manhattan_distance(v1, v2):
return np.sum(np.abs(v1 - v2))
# Example
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
distance = manhattan_distance(v1, v2)
print(f"Manhattan Distance: {distance:.4f}")
# Output: Manhattan Distance: 9.0000
Embedding Search at Scale
Let’s return to the problem of embedding search:
Given a query vector, identify the vectors in a dataset that are closest to it based on a defined similarity metric.
A simple approach for doing similarity search over a set of embeddings would be to iterate over all the vectors in the dataset and calculate the similarity metric for each, e.g.
import numpy as np
# Create sample dataset
dataset_vectors = np.random.random((100, 10)) # 100 vectors of dimension 10
query_vector = np.random.random(10) # Query vector of dimension 10
# Calculate similarity scores
scores = [cosine_similarity(query_vector, vector) for vector in dataset_vectors]
print(f"First 10 scores: {scores[:10]}")
# Output:
# First 10 scores: [0.700207568633205, 0.6776289710211337, 0.9453154422375679, 0.8029513477944358, 0.8642581497888051, 0.8675699664363464, 0.8026549101011365, 0.7467066661639747, 0.888037970724348, 0.8108250451690242]
However, this scales as O(n) with the dataset size, making it impractical for large datasets. Even with optimized vector operations (i.e., batching the embeddings into matrices and computing matrix dot products), this search becomes prohibitively slow for real-world applications that require low-latency responses over large-scale datasets.
Tools for Embedding Search
Vector Databases
Vector databases are specialized systems designed for storing and searching high-dimensional embeddings efficiently. They enable quick similarity lookups and scalable handling of millions or billions of vectors.
Here are a few popular options right now:
- Pinecone: A managed vector database that supports real-time similarity search with built-in indexing and scaling.
- Weaviate: An open-source database designed for vector search, with strong integrations for NLP models.
- Milvus: Another powerful vector database, optimized for large-scale AI applications.
These databases handle the complexity of storing, indexing, and retrieving vectors.
Approximate Nearest Neighbors (ANN)
When dealing with large-scale vector search, exact nearest neighbor algorithms become computationally expensive. This is where Approximate Nearest Neighbors (ANN) algorithms come in—they trade perfect accuracy for dramatic improvements in speed and efficiency.
A few examples are:
- FAISS (Facebook AI Similarity Search): A library for fast similarity search, optimized for GPUs.
- Annoy (Approximate Nearest Neighbors Oh Yeah): A memory-efficient library by Spotify, commonly used for recommendation systems.
- HNSW (Hierarchical Navigable Small World Graphs): An algorithm that builds a graph-based index for fast and scalable nearest-neighbor search.
Indexing Strategies
ANN algorithms work by creating optimized index structures that allow for fast querying while maintaining a high probability of finding the true nearest neighbors. While they might occasionally miss the absolute closest matches, they typically find results that are close enough for practical applications, often with search times that are orders of magnitude faster than exact methods.
Common indexing approaches include:
-
Tree-Based Indexing
- Structures like KD-trees and Ball-trees partition the vector space hierarchically
- Each node represents a subset of vectors in a specific region
- Search traverses down branches that are most likely to contain similar vectors
- Works well in low dimensions but suffers from “curse of dimensionality”
-
Hash-Based Indexing
- Locality-Sensitive Hashing (LSH) maps similar vectors to the same “buckets”
- Uses special hash functions that preserve similarity relationships
- Search only needs to examine vectors in nearby buckets
- Trades accuracy for speed through probabilistic matching
-
Graph-Based Indexing
- Builds a navigable graph where nodes are vectors and edges connect similar vectors
- HNSW (Hierarchical Navigable Small World) is a popular example
- Search starts at entry points and “walks” to increasingly similar vectors
- Highly efficient for high-dimensional data
-
Product Quantization
- Compresses vectors by dividing them into smaller subvectors
- Each subvector is approximated using a learned codebook
- Enables memory-efficient storage and fast distance computations
- Often combined with other indexing methods for better performance
Building an Embedding Search Pipeline
Let’s use FAISS to implement a simple exact similarity search pipeline. FAISS supports both exact and approximate indexes; the IndexFlatL2 index below checks every stored vector using Euclidean distance. It is an exact baseline, rather than an example of approximate nearest-neighbor indexing:
- Generate Embeddings: Use pre-trained models like BERT to generate embeddings.
- Store in a Vector Database: Index these embeddings in FAISS.
- Query with Similarity Search: Convert a query string into an embedding and use similarity metrics to find the nearest neighbors.
- Rank and Return Results: Sort results by similarity score and display them to the user.
Example: Searching a Vector Database with FAISS
import faiss
import numpy as np
# Sample dataset of embeddings (pretend these represent words)
data = np.random.random((1000, 128)).astype('float32') # 1000 vectors, 128 dimensions
# Build index
index = faiss.IndexFlatL2(128) # L2 distance (Euclidean)
index.add(data)
# Query vector (pretend this represents some word)
query = np.random.random((1, 128)).astype('float32')
# Search for nearest neighbors
k = 5 # Number of nearest neighbors
distances, indices = index.search(query, k)
print(f"Top {k} nearest neighbors: {indices}")
# Output:
# Top 5 nearest neighbors: [[930 360 867 97 266]]
Common Use Cases of Embedding Search
Here are some real-world applications of embedding search:
- Semantic Search: Find documents, web pages, or knowledge base articles that capture the meaning behind a user’s query, not just keyword matches.
- Personalized Recommendations: Deliver tailored suggestions for products, music, movies, or content.
- Image Retrieval: Find visually similar images across large databases.
- Fraud Detection: Identify unusual patterns and anomalies in transaction data.
- Drug Discovery: Find chemical compounds with similar properties.
- Customer Support: Match incoming support tickets with similar past cases to suggest solutions or route to appropriate teams.
Conclusion
Vector databases implement techniques we discussed here, in order to provide scalable embedding search solutions for RAG and other applications.
Now might be a great time to hop over to the vector database lesson Data Engineering > Databases > Vector.
Key Takeaways
🔍 Embedding search enables finding similar items by comparing vector representations in high-dimensional space.
📏 Common similarity metrics include cosine similarity, Euclidean distance, and Manhattan distance, each suited for different use cases.
📈 Scaling embedding search requires specialized tools like vector databases and Approximate Nearest Neighbor (ANN) algorithms.
🗂️ Popular vector databases include Pinecone, Weaviate, and Milvus, while ANN libraries include FAISS, Annoy, and HNSW.
⚡ Efficient indexing strategies like tree-based, hash-based, graph-based, and product quantization enable fast similarity search.
🌍 Real-world applications span semantic search, recommendations, image retrieval, fraud detection, and more.
Next: Multimodal Embeddings
The applications we just looked at highlight an interesting pattern—many real-world problems involve analyzing multiple types of data together. For example, product recommendations might involve embeddings of the item description and embeddings of the product image itself.
This brings us to our next topic: Multimodal Embeddings, which combine embeddings from multiple data types. These are really neat.
Comments (0)
No comments yet.