Skip to main content
After documents are chunked, they must be converted into numerical vectors using an Embedding Model and stored in a Vector Database for similarity retrieval. By the end of this page, you will have a working semantic search engine project.

1. Vector Embeddings

Concept

A vector embedding is a dense, low-dimensional mathematical representation of unstructured data (e.g., text, images) mapping semantic meaning to coordinates in a high-dimensional space. Words or sentences with similar contextual meanings reside close to each other in this space.

Objectives

  • Semantic Retrieval: Resolves synonym matching (e.g., matching “automobile” with “car”) and phrase intent, bypassing the limitations of exact keyword matching.
  • Dimensionality Reduction: Converts thousands of vocabulary words into fixed-size numeric arrays (e.g., 384, 768, or 1536 elements) optimized for vector computations.

Embedding Models

  • Cloud API Models: Managed services offering state-of-the-art accuracy (e.g., OpenAI text-embedding-3-small, Google text-embedding-004).
  • Open-Source (Hugging Face) Models: Hosted locally using libraries like sentence-transformers for offline execution and cost efficiency.
    • all-MiniLM-L6-v2: Lightweight, fast inference (384 dimensions).
    • bge-large-en-v1.5: State-of-the-art performance for English retrieval (1024 dimensions).

Vector Database Options

Vector databases index and search embeddings efficiently. Choosing the right database depends on scale and search requirements:

2. Vector Spaces & Distance Metrics

An embedding model maps text chunks to coordinate vectors in a high-dimensional space. To retrieve the best matches, the vector database calculates distance metrics between the user’s query vector (qq) and the stored document vectors (dd):
  • Cosine Similarity: Measures the cosine of the angle between two vectors. It ranges from -1 to 1.
    • Highest Similarity Case: A value closer to 1 (with exactly 1 representing vectors pointing in the identical direction). Ideal for text retrieval because it is independent of document length.
  • L2 Distance (Euclidean): Measures the straight-line distance between two points in vector space.
    • Highest Similarity Case: A value closer to 0 (with exactly 0 representing identical vector coordinates/matching points).
  • Dot Product (Inner Product): Multiplies corresponding coordinates of the query and document vectors and sums them up (qidi\sum q_i d_i).
    • Highest Similarity Case: Larger positive values indicate higher similarity (and a value closer to 1 for normalized vectors).
    • Significance: If vectors are pre-normalized to a length of 1 (as most modern embedding models do), the dot product is mathematically identical to Cosine Similarity.
    • Database Advantage: It is computationally cheaper and much faster to calculate than Cosine or L2 because it avoids expensive square root calculations, making it the preferred metric for large-scale production retrieval.

3. Ingestion + Vector Search Working Project

Let’s build a working database search project step-by-step.

3.1 Install Dependencies

Run in your terminal:
Ensure your API key is in your environment:
Sample File (office_policy.txt):

3.2 Step-by-Step Implementation

Stage 1: Load the Document Data
The document is read using TextLoader and wrapped into a LangChain Document list.
Sample Output:
Stage 2: Chunk the Documents
Split the loaded document into smaller pieces using RecursiveCharacterTextSplitter.
Sample Output:
Stage 3: Generate Embeddings
Initialize the embedding model (text-embedding-004) to map text chunks to numerical vectors.
Sample Output:
Stage 4: Index into ChromaDB
Store the generated embeddings and their original text chunks in ChromaDB.
Sample Output:
Stage 5: Execute Similarity Search
Query the database with a natural language search to retrieve the most semantically relevant text chunk.
Sample Output:

3.3 Assembled Complete Script

Here is the complete, unified script combining all stages:

4. Practice Exercises

Practice 1: Search Scope (Top-K)

Modify the search query step in the working project to retrieve the top 2 matches (k=2). Run a query searching for "travel refunds and screen security" and print both returned chunks. Instructions:
  1. Call .similarity_search(query, k=2) on the vector_db object.
  2. Iterate through the returned list and print each chunk’s content.

Summary

  • Vector Embeddings: Dense numerical representations mapping semantic meaning to multi-dimensional coordinate space. Open-source Hugging Face models (like all-MiniLM-L6-v2) and cloud APIs are used to compute them.
  • Vector Databases: Specialized engines to index and query embeddings. Options include ChromaDB (prototyping), Pinecone (SaaS/hybrid search), Qdrant/Milvus (large scale self-hosted), and pgvector (relational vector integration).
  • Distance Metrics:
    • Cosine Similarity: Measures vector direction (closer to 1 is highly similar).
    • L2 Distance: Measures physical distance (closer to 0 is highly similar).
    • Dot Product: Multiplies elements. Identical to Cosine for normalized vectors, offering high database computation speeds.