Tuesday, September 1, 2026

What Is a Vector Database? How Vector Search Works

In the previous article, we learned about AI embeddings and how text can be converted into numerical vectors.

But this creates an important question:

Where do we store all these vectors?
How do we search millions of vectors efficiently?

This is where Vector Databases come into the picture.

Vector databases are an important component of modern AI applications, especially RAG (Retrieval-Augmented Generation) systems.

In this beginner-friendly guide, we will learn what a vector database is, how vector search works, similarity search, Top-K retrieval, metadata filtering, indexing, HNSW, hybrid search, and how vector databases are used in RAG applications.


What Is a Vector Database?

A Vector Database is a database designed to store, index, and search vector embeddings.

Instead of searching only for exact words or values, a vector database can search for vectors that are mathematically similar to a query vector.

Text
  ↓
Embedding Model
  ↓
Vector
  ↓
Vector Database
  ↓
Similarity Search
  ↓
Relevant Information

In a RAG system, a vector database is commonly used to store document chunks and their embeddings so that relevant information can be retrieved when a user asks a question.


Why Do We Need a Vector Database?

Imagine your company has 100,000 documents.

After chunking, those documents might produce millions of individual text chunks.

100,000 Documents
       ↓
Document Chunking
       ↓
Millions of Chunks
       ↓
Millions of Embeddings

If a user asks:

"How many vacation days do employees get?"

The application needs to find the most relevant chunks quickly.

Searching every vector one by one would become expensive and slow as the dataset grows.

Vector databases use specialized indexing and search techniques to make similarity search much more efficient.


Traditional Database vs Vector Database

A traditional relational database is excellent for structured data.

SELECT *
FROM Employees
WHERE Department = 'IT';

This query looks for an exact condition.

A vector database is designed for a different type of question:

"Find documents that are semantically
similar to this question."
Traditional Database Vector Database
Structured data Vector embeddings
Exact conditions Similarity search
SQL queries Vector queries
Rows and columns Vectors and metadata
Excellent for transactions Excellent for semantic retrieval
Important: A vector database does not necessarily replace a traditional database. Many AI applications use both because they solve different problems.

What Does a Vector Database Store?

A vector database usually stores more than just a vector.

A typical record might contain:

ID:
DOC-001-CHUNK-10

Vector:
[0.12, -0.43, 0.71, 0.09, ...]

Text:
Employees receive 20 days
of annual leave.

Metadata:
Document = LeavePolicy.pdf
Page = 12
Department = HR
Year = 2026

The vector is used for similarity search, while the text and metadata help the application understand and use the search result.


How Does Vector Search Work?

The basic process is straightforward.

User Question
      ↓
Embedding Model
      ↓
Query Vector
      ↓
Vector Database
      ↓
Similarity Search
      ↓
Relevant Vectors
      ↓
Original Text
      ↓
LLM

Let's look at each step.


Step 1: Create Document Embeddings

First, documents are divided into chunks.

Document
   ↓
Chunk 1
Chunk 2
Chunk 3
Chunk 4

Each chunk is converted into an embedding.

Chunk 1 → Vector 1
Chunk 2 → Vector 2
Chunk 3 → Vector 3
Chunk 4 → Vector 4

These vectors are stored in the vector database.


Step 2: User Asks a Question

The user asks:

"How many vacation days can I take?"

The question is converted into an embedding.

Question
   ↓
Embedding Model
   ↓
Query Vector

Step 3: Search the Vector Database

The query vector is compared against the stored vectors.

Query Vector
      ↓
Vector Database
      ↓
Similarity Search
      ↓
Relevant Vectors

The database returns the vectors that are closest or most similar according to the selected similarity or distance metric.


Step 4: Retrieve the Original Text

The vector search result points back to the corresponding document chunks.

Vector
  ↓
Document ID
  ↓
Chunk
  ↓
Original Text

For example:

Employees receive 20 days
of paid annual leave.

Step 5: Send Context to the LLM

The retrieved information is provided to the LLM along with the user's question.

Question
   +
Retrieved Context
   ↓
LLM
   ↓
Answer

The LLM can then generate a response based on the retrieved information.


What Is Similarity Search?

Similarity Search is the process of finding vectors that are closest to a query vector according to a chosen similarity or distance measure.

For example:

Query Vector
     ↓
 ┌───────────────┐
 │ Vector DB     │
 │               │
 │ Vector A  ✓   │
 │ Vector B  ✓   │
 │ Vector C      │
 │ Vector D      │
 │ Vector E  ✓   │
 └───────────────┘
     ↓
Top Relevant Results

The search engine ranks the results based on their similarity to the query.


Common Similarity Measures

Vector databases can use different mathematical measures for comparing vectors.

  • Cosine Similarity
  • Dot Product
  • Euclidean Distance

The appropriate metric depends on the embedding model and the vector database configuration.


Cosine Similarity

Cosine similarity compares the angle between two vectors.

Vector A
   ↘
    ↘
     ↘
      ↘ Vector B

Smaller angle
      ↓
Greater similarity

With the common cosine-similarity convention, a value closer to 1 generally indicates greater similarity, while values closer to 0 indicate weaker similarity.


What Is Top-K Search?

A vector search does not normally return every matching vector.

Instead, the application usually requests the Top-K results.

If K = 5:

Query
 ↓
Vector Search
 ↓
Top 5 Results
 ↓
LLM

For example:

Result 1 → Similarity: 0.94
Result 2 → Similarity: 0.91
Result 3 → Similarity: 0.88
Result 4 → Similarity: 0.84
Result 5 → Similarity: 0.81

Only these results may be passed to the next stage of the RAG pipeline.


What Is Vector Indexing?

If a vector database has millions of vectors, comparing a query against every single vector can be expensive.

Vector indexing creates a data structure that helps the system search the vector space more efficiently.

Millions of Vectors
        ↓
Vector Index
        ↓
Efficient Search
        ↓
Relevant Vectors

This is similar to how traditional databases use indexes to speed up certain types of queries.


What Is HNSW?

HNSW stands for Hierarchical Navigable Small World.

It is a popular graph-based indexing technique used for approximate nearest-neighbor search.

Instead of comparing a query with every vector, HNSW builds a graph that helps navigate toward nearby vectors.

                 Vector A
                /        \
               /          \
          Vector B       Vector C
             |              |
          Vector D       Vector E
               \          /
                \        /
                 Vector F

The search can navigate through this graph to find good nearest neighbors efficiently.

Important: HNSW is an approximate nearest-neighbor technique. It trades some search accuracy for improved search performance, with behavior controlled by the implementation and configuration.

Exact Search vs Approximate Search

Exact Nearest-Neighbor Search

The system compares the query against every vector to determine the exact nearest neighbors.

Query
 ↓
Compare with ALL vectors
 ↓
Find exact nearest neighbors

This can become expensive with very large datasets.

Approximate Nearest-Neighbor Search

The system uses an index to find highly relevant neighbors without exhaustively comparing every vector.

Query
 ↓
Vector Index
 ↓
Search likely candidates
 ↓
Top results

This is often much faster for large-scale vector search.


What Is Metadata Filtering?

Vector similarity is not always enough.

Suppose a company has documents from several countries:

India
USA
UK
Canada
Australia

A user asks about an HR policy for India.

The application could apply a metadata filter before or during retrieval, depending on the vector database.

User Question
      ↓
Metadata Filter
Country = India
      ↓
Vector Search
      ↓
Relevant Documents

Metadata might include:

  • Country
  • Department
  • Document type
  • Year
  • Product
  • Customer
  • Access level

Why Metadata Is Important

Metadata can improve both relevance and security.

For example:

Department = Finance
Year = 2026
DocumentType = Policy

The search can be restricted to documents matching those conditions.

Security: Metadata filtering should not be treated as a substitute for a complete authorization model. Sensitive RAG applications should enforce access control throughout the retrieval pipeline.

What Is Hybrid Search?

Hybrid Search combines multiple retrieval approaches.

A common approach combines:

  • Keyword search
  • Vector search
                 User Query
                     ↓
          ┌──────────┴──────────┐
          ↓                     ↓
   Keyword Search         Vector Search
          ↓                     ↓
          └──────────┬──────────┘
                     ↓
              Combined Results
                     ↓
                    LLM

Hybrid search can be particularly useful when exact terms matter.

For example:

Error Code: DB-1024
Product ID: POS-7000
API: PaymentAuthorization

Keyword matching can help with exact identifiers, while vector search can help with natural-language meaning.


Vector Database in a RAG System

Now let's connect everything together.

                 DOCUMENTS
                     ↓
                  Chunking
                     ↓
                Embedding Model
                     ↓
                    Vectors
                     ↓
              ┌───────────────┐
              │ Vector        │
              │ Database      │
              └───────┬───────┘
                      │
                      │
                      ↓
User Question → Embedding
                      ↓
               Vector Search
                      ↓
              Relevant Chunks
                      ↓
                     LLM
                      ↓
                   Answer

Example: Employee Knowledge Base

Imagine a company has the following documents:

Employee Handbook.pdf
Leave Policy.pdf
Travel Policy.pdf
Insurance Policy.pdf

During indexing:

PDF
 ↓
Extract Text
 ↓
Chunk
 ↓
Generate Embeddings
 ↓
Store in Vector Database

Now an employee asks:

"Can I carry my unused leave into next year?"

The application creates a query embedding and searches the vector database.

Question
   ↓
Query Embedding
   ↓
Vector Search
   ↓
Leave Policy Chunk
   ↓
LLM
   ↓
Answer

Vector Database vs Search Engine

Modern search systems can support both keyword and vector retrieval.

The choice between a dedicated vector database, a search engine with vector capabilities, or a traditional database with vector support depends on the application's requirements.

Requirement Possible Approach
Structured transactional data Relational database
Semantic vector search Vector database
Keyword + semantic search Hybrid search platform
Existing database infrastructure Database with vector support

There is no single database that is best for every RAG application.


Can SQL Databases Store Vectors?

Some modern database systems support storing and searching vectors.

This means you do not always need a separate vector database.

Application
     ↓
SQL Database
 ┌───────────────┐
 │ Normal Data   │
 │ Vector Data   │
 │ Metadata      │
 └───────────────┘

This can simplify architecture when an organization already has a database platform capable of handling the required vector workloads.


Popular Vector Database Technologies

Several technologies can be used for vector storage and retrieval.

  • Qdrant
  • Milvus
  • Weaviate
  • Pinecone
  • Chroma
  • FAISS
  • PostgreSQL with vector extensions
  • Other databases and search platforms with vector capabilities

The right choice depends on factors such as scale, deployment model, filtering requirements, performance, ecosystem, and cost.


Vector Database vs FAISS

FAISS is a library for efficient similarity search and clustering of dense vectors.

A vector database generally provides a broader database-oriented feature set, such as:

  • Persistent storage
  • Metadata management
  • Filtering
  • APIs
  • Index management
  • Scalability features
  • Database operations

FAISS can be very useful when you need a similarity-search library rather than a complete database system.


How Many Vectors Can a Vector Database Store?

There is no universal limit.

Capacity depends on:

  • Vector dimensions
  • Number of vectors
  • Index type
  • Available memory
  • Storage
  • Database implementation
  • Hardware
  • Distributed architecture

A small application may have thousands of vectors, while a large system may have millions or billions.


Why Vector Dimension Matters

Suppose an embedding contains 384 dimensions:

[x1, x2, x3, ... x384]

Another model might produce 1536 dimensions:

[x1, x2, x3, ... x1536]

Higher dimensional vectors generally require more memory and computational resources.

However, higher dimensionality does not automatically mean better retrieval quality.


Vector Search Performance

Several factors influence vector search performance:

  • Number of vectors
  • Vector dimensions
  • Index type
  • Hardware
  • Number of concurrent queries
  • Metadata filtering
  • Top-K value
  • Search configuration

For larger systems, indexing and infrastructure design become increasingly important.


What Happens When Documents Are Updated?

Suppose the company updates its leave policy.

The application can process the updated document and replace or update the corresponding chunks in the vector database.

Updated Document
      ↓
Extract Text
      ↓
Chunk
      ↓
Generate Embeddings
      ↓
Update Vector Database
      ↓
New Information Available

The LLM itself does not need to be retrained simply because the source document changed.


Vector Database Security

Security is an important consideration when building enterprise RAG applications.

Vector databases may contain sensitive information or references to sensitive documents.

Applications should consider:

  • Authentication
  • Authorization
  • Tenant isolation
  • Encryption
  • Access-controlled retrieval
  • Metadata filtering
  • Audit logging

A user should only be able to retrieve information they are authorized to access.


Simple RAG Example

Let's summarize the entire process with a simple example.

Document:

"Employees receive 20 days
of paid annual leave."

Step 1 – Create embedding:

Document
   ↓
Embedding Model
   ↓
Document Vector

Step 2 – Store it:

Vector
 +
Text
 +
Metadata
 ↓
Vector Database

Step 3 – User asks:

"How many vacation days do I get?"

Step 4 – Create query embedding:

Question
   ↓
Embedding Model
   ↓
Query Vector

Step 5 – Search:

Query Vector
      ↓
Vector Database
      ↓
Similarity Search
      ↓
Relevant Chunk

Step 6 – Generate answer:

Relevant Chunk
      +
User Question
      ↓
LLM
      ↓
"Employees receive 20 days
of paid annual leave."

Key Takeaways

  • Vector Database: Stores and searches vector embeddings.
  • Vector: Numerical representation of information.
  • Similarity Search: Finds vectors that are close to a query according to a chosen metric.
  • Top-K: Retrieves the most relevant results.
  • Vector Index: Helps make large-scale vector search more efficient.
  • HNSW: A popular approximate nearest-neighbor indexing technique.
  • Metadata Filtering: Restricts results using additional attributes.
  • Hybrid Search: Combines keyword and semantic retrieval.
  • RAG: Uses vector retrieval to provide relevant information to an LLM.

Conclusion

A Vector Database is an important building block for modern AI applications.

It allows applications to store embeddings and efficiently search for information based on semantic similarity.

The basic flow is:

Documents
    ↓
Chunking
    ↓
Embeddings
    ↓
Vector Database
    ↓
User Question
    ↓
Query Embedding
    ↓
Similarity Search
    ↓
Relevant Information
    ↓
LLM
    ↓
Answer

Once you understand embeddings and vector databases, the next major concept is semantic search — how AI can search for information based on meaning rather than exact keywords.

Next: In the next article, we will explore Semantic Search, understand how it differs from traditional keyword search, and see how hybrid search can combine both approaches.

Monday, August 31, 2026

What Are AI Embeddings? A Beginner’s Guide to Vectors and Semantic Search

In the previous articles, we learned what RAG (Retrieval-Augmented Generation) is and how a RAG system uses chunking, vector databases, semantic search, and LLMs.

One of the most important technologies behind this process is AI embeddings.

Embeddings allow AI systems to represent text as numbers so that computers can compare the meaning of different pieces of information.

In this beginner-friendly guide, we will learn what embeddings are, how they work, what vectors and dimensions mean, how similarity is calculated, and why embeddings are important for RAG and semantic search.


What Are AI Embeddings?

An embedding is a numerical representation of data that captures useful characteristics or semantic relationships.

For text, an embedding model converts a sentence, paragraph, or document into a vector of numbers.

Text
 ↓
Embedding Model
 ↓
Vector
 ↓
[0.12, -0.45, 0.78, 0.21, ...]

The resulting vector can contain hundreds or thousands of numerical values depending on the embedding model.

You can think of an embedding as a way of converting human-readable information into a mathematical representation that an AI system can compare.


Simple Example

Consider these two sentences:

Sentence A:
How many vacation days do I have?

Sentence B:
Employees receive 20 days of annual leave.

The words are not exactly the same, but the meanings are closely related.

An embedding model can convert both sentences into vectors:

Sentence A
     ↓
Vector A

Sentence B
     ↓
Vector B

The vectors can then be compared to determine how semantically similar the sentences are.


Why Do AI Systems Need Embeddings?

Computers are very good at processing numbers, but human language is complex.

Consider these questions:

"How many vacation days do I get?"

"How much annual leave am I entitled to?"

"What's my yearly leave allowance?"

A keyword search may treat these as different queries because the words are different.

However, their meanings are very similar.

Embeddings help represent these meanings mathematically so that an AI system can identify the relationship.


Text to Vector

The basic process is:

Human Text
     ↓
Embedding Model
     ↓
Numerical Vector

For example:

"I love programming"

        ↓

[0.034, -0.182, 0.731, 0.245, -0.093, ...]

The numbers themselves are not normally meaningful to a human. Their usefulness comes from how vectors relate to each other in the embedding space.


What is a Vector?

A vector is simply an ordered collection of numbers.

[0.25, -0.13, 0.87, 0.42]

In AI, vectors can represent many types of information, including:

  • Text
  • Images
  • Audio
  • Documents
  • User preferences
  • Products

In RAG applications, vectors are most commonly used to represent document chunks and user questions.


What Are Dimensions?

The number of values in an embedding vector is called its dimension or dimensionality.

For example:

[0.12, 0.45, -0.31]

This vector has 3 dimensions.

A real embedding model might produce a much larger vector:

[0.12, 0.45, -0.31, 0.72, ... many more values ...]

The exact dimensionality depends on the embedding model.

Important: More dimensions do not automatically mean better embeddings. The quality of the embedding model and how well it represents the information are more important than simply having a larger vector.

What Does an Embedding Represent?

An embedding does not normally assign one obvious human-readable meaning to each individual number.

Instead, the vector as a whole represents information learned by the embedding model.

Think of it like a location on a very large mathematical map.

              Similar Meaning
                    ↑
                    │
       A ●          │       ● B
                    │
                    │
                    │
                    │
                    │
                    │
                    └────────────────→

Text with similar meanings tends to be represented closer together in the embedding space.


Embeddings Create a Semantic Space

Imagine a huge mathematical space containing millions of points.

Each point represents an embedding.

                 AI Embedding Space

        Dogs ●
              ● Puppies

                         ● Cars
                   ● Vehicles

        ● Cats

                                ● Computers

Related concepts tend to form regions or clusters in the embedding space.

This allows AI applications to perform semantic searches.


Semantic Similarity

Semantic similarity measures how closely two pieces of text are related in meaning.

For example:

"How do I reset my password?"

"What should I do if I forgot my password?"

These sentences use different words but express a similar intent.

Their embeddings can therefore be relatively close to each other.


Keyword Search vs Semantic Search

Keyword Search

Traditional keyword search looks for matching terms.

Query:
"vacation days"

Document:
"Employees receive 20 days of annual leave."

There may be no exact match for the word vacation.

Semantic Search

Semantic search uses embeddings to compare meaning.

Query:
"How many vacation days do I get?"

        ↓
    Embedding

        ↓
Vector Search

        ↓

Document:
"Employees receive 20 days
of annual leave."

The system can recognize that vacation days and annual leave are semantically related.


How Are Embeddings Used in RAG?

Embeddings are a fundamental part of a typical RAG architecture.

Documents
    ↓
Chunking
    ↓
Embedding Model
    ↓
Vectors
    ↓
Vector Database

When the user asks a question:

User Question
      ↓
Embedding Model
      ↓
Query Vector
      ↓
Vector Database
      ↓
Similar Document Vectors
      ↓
Relevant Chunks
      ↓
LLM
      ↓
Answer

Document Embeddings

During the indexing process, each document chunk is converted into an embedding.

Document Chunk 1
      ↓
Embedding 1

Document Chunk 2
      ↓
Embedding 2

Document Chunk 3
      ↓
Embedding 3

These embeddings are then stored in a vector database.


Query Embeddings

When a user asks a question, the question is converted into an embedding using the same or compatible embedding model used for the indexed content.

User Question
      ↓
Embedding Model
      ↓
Query Vector

The query vector is then compared with the stored document vectors.

Important: In a typical RAG pipeline, the document chunks and user queries need to be represented in a compatible embedding space so that meaningful similarity comparisons can be performed.

How Does Vector Similarity Work?

Once we have two vectors, we need a way to measure how similar they are.

Common approaches include:

  • Cosine Similarity
  • Dot Product
  • Euclidean Distance

The exact choice depends on the embedding model and vector database.


Cosine Similarity

Cosine similarity measures the angle between two vectors.

Conceptually:

Vector A
   ↘
    ↘
     ↘
      ↘ Vector B

Small angle
     ↓
High similarity

When using the common cosine-similarity convention, a value closer to 1 generally indicates greater similarity, while a value closer to 0 indicates weaker similarity.

Negative values can also occur depending on the vectors and model.


Simple Similarity Example

Imagine we have three documents:

Document A:
How to reset your password

Document B:
Password recovery instructions

Document C:
How to configure a database

User asks:

"I forgot my password. How can I recover it?"

The query embedding might produce similarity scores such as:

Document A → 0.91
Document B → 0.88
Document C → 0.24

The system would consider Documents A and B much more relevant than Document C.


What is an Embedding Model?

An embedding model is a machine learning model specifically designed to convert input data into vector representations.

For text:

Text
 ↓
Embedding Model
 ↓
Vector

Different embedding models have different characteristics, such as:

  • Embedding dimension
  • Supported languages
  • Context length
  • Semantic quality
  • Speed
  • Memory requirements

Embedding Model vs LLM

An embedding model and an LLM perform different jobs.

Embedding Model LLM
Converts content into vectors Generates text
Used for similarity and retrieval Used for reasoning and generation
Produces numerical representations Produces natural-language responses
Commonly used before retrieval Commonly used after retrieval in RAG

A RAG system may therefore use both an embedding model and an LLM.


Why Not Use the LLM to Search Documents?

An LLM is designed primarily for understanding and generating language. A vector search system provides an efficient way to find relevant information across a large collection of embedded content.

A typical architecture separates these responsibilities:

Embedding Model
      ↓
Find Relevant Information
      ↓
Vector Database
      ↓
Retrieve Context
      ↓
LLM
      ↓
Generate Answer

This separation makes it possible to search a large knowledge base without sending every document to the LLM.


Embeddings and Vector Databases

The relationship between embeddings and vector databases is important.

Embedding Model
      ↓
Creates Vectors
      ↓
Vector Database
      ↓
Stores & Searches Vectors

The embedding model creates the representation, while the vector database provides infrastructure for storing and retrieving those representations.


Example Vector Database Record

A RAG system might store information similar to:

ID:
DOC-001-CHUNK-05

Text:
Employees receive 20 days of annual leave.

Embedding:
[0.12, -0.42, 0.71, ...]

Metadata:
Document = LeavePolicy.pdf
Page = 12
Department = HR
Year = 2026

The metadata can later be used for filtering and displaying source information.


Embeddings for Images

Embeddings are not limited to text.

Images can also be represented as vectors.

Image
  ↓
Embedding Model
  ↓
Image Vector

This makes it possible to build systems that search for images based on visual or semantic similarity.

For example:

Query:
"red sports car"

        ↓
     Embedding

        ↓
Search Image Vectors

        ↓
Similar Images

Multimodal Embeddings

Some modern AI systems can represent different types of content in compatible embedding spaces.

This can enable relationships between:

  • Text and images
  • Images and text
  • Audio and text
  • Other forms of multimodal data

This area is especially useful for applications that need to search across multiple types of content.


What Happens When a Document Changes?

Suppose your company updates its leave policy.

The old document can be replaced or re-indexed.

Updated Document
      ↓
Extract Text
      ↓
Chunk
      ↓
Generate New Embeddings
      ↓
Update Vector Database
      ↓
New Information Available

The underlying LLM does not need to be retrained simply because the document changed.


Embedding Quality Matters

The quality of a RAG system depends heavily on how well the embedding model represents your data.

A poor embedding model may produce weak retrieval results even when the rest of the system is well designed.

When selecting an embedding model, consider:

  • Language support
  • Domain suitability
  • Retrieval quality
  • Latency
  • Infrastructure requirements
  • Cost
  • Maximum input length

Embedding Model and Language

If your application contains multiple languages, the embedding model's language support becomes important.

For example, a multilingual application may contain:

English
Tamil
Hindi
Japanese
German

A multilingual embedding model may be more appropriate than a model optimized only for English.


Embeddings in a Real RAG Application

Let's look at the complete process using a company knowledge base.

Suppose we have:

Leave Policy.pdf
Travel Policy.pdf
Insurance Policy.pdf
IT Security.pdf

During indexing:

PDF
 ↓
Text Extraction
 ↓
Chunks
 ↓
Embedding Model
 ↓
Vectors
 ↓
Vector Database

Later, a user asks:

"Can I carry unused vacation days
into next year?"

The question becomes an embedding:

Question
 ↓
Embedding Model
 ↓
Query Vector

The vector database searches for similar vectors and may return a chunk from the leave policy.

Query Vector
      ↓
Vector Search
      ↓
Leave Policy Chunk
      ↓
LLM
      ↓
Final Answer

Embeddings and RAG Performance

Several factors can affect retrieval performance:

  • Embedding model quality
  • Chunking strategy
  • Chunk size
  • Chunk overlap
  • Similarity metric
  • Top-K value
  • Metadata filtering
  • Reranking
  • Document quality

This means that improving a RAG system is not simply a matter of selecting a larger LLM.


Embeddings vs Keywords: A Simple Comparison

Keyword Search Embedding Search
Matches words Compares semantic representations
Good for exact terms Good for semantic relationships
Simple and efficient Requires embedding generation
Useful for IDs and exact names Useful for natural-language questions

Many modern applications use hybrid search to combine both approaches.


Common Mistakes with Embeddings

1. Using Different Embedding Spaces

Document embeddings and query embeddings generally need to be generated using compatible models and configurations.

2. Ignoring Chunking

Even a strong embedding model cannot fix poorly structured chunks.

3. Retrieving Too Many Results

More results do not necessarily mean a better answer. Irrelevant context can reduce answer quality.

4. Ignoring Metadata

Metadata can help restrict searches and improve relevance.

5. Assuming Similarity Means Correctness

A high similarity score means that content is considered similar according to the retrieval system. It does not automatically mean that the retrieved information is factually correct.


Embeddings in One Simple Diagram

              DOCUMENT
                  ↓
               Chunking
                  ↓
           Embedding Model
                  ↓
                Vector
                  ↓
          Vector Database
                  │
                  │
                  ↓
            Similarity Search
                  ↑
                  │
             User Query
                  ↓
           Embedding Model
                  ↓
             Query Vector
                  │
                  ↓
          Relevant Documents
                  ↓
                 LLM
                  ↓
              Answer

Key Takeaways

  • Embedding: A numerical representation of data.
  • Vector: An ordered collection of numbers.
  • Dimension: The number of values in an embedding.
  • Embedding Model: A model that converts data into vectors.
  • Semantic Search: Search based on meaning rather than only exact words.
  • Vector Database: Stores and searches vector representations.
  • Similarity: Measures how closely two vectors are related.
  • RAG: Uses embeddings to retrieve relevant information before generating an answer.

Conclusion

AI embeddings are one of the fundamental building blocks of modern AI applications.

They provide a way to represent text and other data as vectors, allowing applications to compare information based on similarity and meaning.

In a RAG system, embeddings connect the user's question with the knowledge stored in documents:

Text
 ↓
Embedding
 ↓
Vector
 ↓
Similarity Search
 ↓
Relevant Information
 ↓
LLM
 ↓
Answer

Once you understand embeddings, the next important concept is the technology that stores and searches these vectors: the Vector Database.

Next: In the next article, we will explore Vector Databases, how they store embeddings, how vector search works, and how they are used in real-world RAG applications.

Sunday, August 30, 2026

How Does RAG Work? Embeddings, Vector Databases, and Semantic Search

In the previous article, we learned what RAG (Retrieval-Augmented Generation) is and why it is useful for building AI applications.

Now let's go one level deeper and understand how a RAG system actually works.

A typical RAG system depends on several important technologies, including embeddings, vector databases, chunking, semantic search, retrieval, and Large Language Models (LLMs).

Understanding these components will make it much easier to build a RAG application using technologies such as C#, .NET, Ollama, and vector databases.


RAG Architecture at a Glance

A simplified RAG architecture looks like this:

                    Documents
                        ↓
                    Chunking
                        ↓
                   Embeddings
                        ↓
                Vector Database
                        │
                        │
                        ↓
User Question → Query Embedding
                        ↓
                 Semantic Search
                        ↓
                Relevant Chunks
                        ↓
                       LLM
                        ↓
                  Final Answer

There are two major parts:

  • Indexing Pipeline: Prepares documents for searching.
  • Query Pipeline: Finds relevant information and generates an answer.

1. What is the RAG Indexing Pipeline?

The indexing pipeline prepares your documents before users start asking questions.

Documents
    ↓
Document Loader
    ↓
Text Extraction
    ↓
Chunking
    ↓
Embedding Model
    ↓
Vector Database

For example, imagine a company has the following documents:

Employee Handbook.pdf
Leave Policy.pdf
Travel Policy.pdf
Insurance Policy.pdf
IT Guidelines.pdf

These documents need to be processed and indexed before the AI can search them.


2. Step 1 – Document Loading

The first step is to load documents from your knowledge source.

A RAG application may load information from:

  • PDF files
  • Word documents
  • Text files
  • HTML pages
  • Websites
  • Databases
  • APIs
  • Code repositories

The application extracts the useful text from these sources.

PDF
 ↓
Text Extraction
 ↓
Plain Text

3. Step 2 – Document Chunking

Large documents are usually divided into smaller pieces called chunks.

Why?

Suppose you have a 200-page PDF containing multiple topics. A user may only need one paragraph from that document.

Sending the entire document to the LLM would be inefficient.

Instead, the document is split into smaller pieces.

Large Document
      ↓
 ┌────┼────┬────┬────┐
 ↓    ↓    ↓    ↓    ↓
 C1   C2   C3   C4   C5

For example:

Employee Handbook

Chunk 1 → Introduction
Chunk 2 → Working Hours
Chunk 3 → Leave Policy
Chunk 4 → Benefits
Chunk 5 → Travel Policy

What is Chunk Size?

Chunk size determines how much content is placed into each chunk.

For example, you might create chunks containing a certain number of tokens or characters.

Document
   ↓
500 tokens
   ↓
Chunk 1

500 tokens
   ↓
Chunk 2

500 tokens
   ↓
Chunk 3

There is no single perfect chunk size for every RAG application.

The ideal size depends on the type of documents, the embedding model, retrieval strategy, and the LLM's context window.


What is Chunk Overlap?

Sometimes consecutive chunks share some content.

This is called chunk overlap.

Chunk 1
[ A B C D E ]

        [ D E F G H ]
             Chunk 2

                  [ G H I J K ]
                       Chunk 3

The overlapping content helps preserve context when important information is located near a chunk boundary.

Tip: Chunking is an important part of RAG quality. Poor chunking can cause relevant information to be split in a way that makes retrieval less useful.

4. Step 3 – What are Embeddings?

One of the most important concepts in RAG is embeddings.

An embedding converts text into a numerical vector that represents aspects of its meaning.

For example:

"How many vacation days do employees get?"
                    ↓
              Embedding Model
                    ↓
       [0.12, -0.42, 0.71, 0.08, ...]

The actual vector may contain hundreds or thousands of dimensions depending on the embedding model.

You normally do not need to understand every number. The important concept is that semantically related text can have similar vector representations.


5. Why Do We Need Embeddings?

Consider these two sentences:

Sentence 1:
How many vacation days can I take?

Sentence 2:
Employees are entitled to 20 days of annual leave.

The words are different, but the meaning is related.

A semantic search system can use embeddings to recognize this relationship.

Sentence 1
    ↓
Vector A

Sentence 2
    ↓
Vector B

Vector A ≈ Vector B
        ↓
Similar Meaning

6. What is a Vector?

A vector is simply a collection of numbers.

[0.15, -0.22, 0.73, 0.08, -0.41, ...]

In AI applications, vectors can represent the semantic characteristics of text, images, audio, and other types of data.

In RAG, we usually create vectors from document chunks and user queries.


7. What is a Vector Database?

A Vector Database is a database designed to store and search vector representations efficiently.

A RAG system can store each document chunk together with its embedding and metadata.

Vector Database

┌──────────────────────────────────────────┐
│ Vector                                   │
│ Original Text                            │
│ Document Name                            │
│ Page Number                              │
│ Metadata                                 │
└──────────────────────────────────────────┘

For example:

Vector:
[0.12, -0.42, 0.71, ...]

Text:
Employees are entitled to 20 days
of annual leave.

Document:
Leave Policy.pdf

Page:
12

8. Why Can't We Just Use SQL?

Traditional databases are excellent for structured data and exact queries.

For example:

SELECT *
FROM Employees
WHERE Department = 'IT';

But consider a question such as:

"What benefits are available to employees
who have been with the company for several years?"

This is a semantic question rather than a simple exact-value lookup.

Vector search allows the system to search based on the meaning represented by the embeddings.

Important: Vector databases do not necessarily replace traditional databases. Many applications use both SQL databases and vector search depending on the type of data and query.

9. What is Semantic Search?

Semantic Search searches for information based on meaning rather than only matching exact words.

For example:

Query:
How much annual vacation do I get?

Document:
Employees receive 20 days
of paid annual leave.

A keyword search might not find a strong match because "vacation" and "annual leave" are different phrases.

Semantic search can recognize that the concepts are related.


10. How Does Similarity Search Work?

When the user asks a question, the application converts the question into an embedding.

User Question
      ↓
Embedding Model
      ↓
Query Vector

The query vector is then compared against vectors stored in the vector database.

Query Vector
      ↓
Vector Database
      ↓
Compare Vectors
      ↓
Find Similar Vectors
      ↓
Top Results

The system retrieves the chunks that are considered most relevant.


11. Cosine Similarity

One commonly used concept for measuring similarity between vectors is cosine similarity.

It measures the angle between two vectors rather than simply comparing their raw values.

Vector A
   ↘
    ↘
     ↘
      → Vector B

Small angle
     ↓
High similarity

A value closer to 1 generally indicates greater similarity, while a value closer to 0 indicates less similarity for common cosine-similarity use cases.

Other similarity or distance measures can also be used depending on the vector database and application.


12. What is Top-K Retrieval?

Instead of returning every matching document, a RAG system normally retrieves a limited number of results.

This is commonly called Top-K retrieval.

For example, if K = 5:

User Question
      ↓
Vector Search
      ↓
Top 5 Relevant Chunks
      ↓
LLM

The retrieved chunks are then added to the prompt or context sent to the LLM.


13. The RAG Query Pipeline

Now let's look at what happens when a user asks a question.

User Question
      ↓
Create Query Embedding
      ↓
Search Vector Database
      ↓
Retrieve Top-K Chunks
      ↓
Build Prompt
      ↓
Send to LLM
      ↓
Generate Answer

For example:

User:
How many vacation days can I take?

        ↓

Query Embedding

        ↓

Vector Search

        ↓

Relevant Chunk:
Employees receive 20 days
of annual leave.

        ↓

LLM

        ↓

Answer:
Employees receive 20 days
of annual leave.

14. What is Context in RAG?

The retrieved information provided to the LLM is commonly referred to as context.

The application might construct a prompt like:

System:
Answer the question using the provided context.

Context:
Employees receive 20 days of
paid annual leave.

Question:
How many vacation days can I take?

The LLM uses the context to generate the response.


15. RAG Does Not Train the LLM

This is one of the most common misunderstandings about RAG.

When you add a new document to a RAG system, you generally do not retrain the LLM.

Instead, the new document is processed and added to the retrieval system.

New Document
      ↓
Chunk
      ↓
Embedding
      ↓
Vector Database
      ↓
Available for Retrieval

The LLM itself remains unchanged.


16. RAG vs Fine-Tuning

RAG Fine-Tuning
Adds external context at runtime Modifies model behavior through additional training
Useful for changing knowledge Useful for specialized behavior
Documents can be updated independently Training is required for model updates
Can retrieve specific source information Does not inherently provide source retrieval

For frequently changing business information, RAG can often be more practical than retraining a model every time information changes.


17. What is Hybrid Search?

Semantic search is powerful, but exact keyword matching can also be important.

Hybrid Search combines keyword-based search with semantic/vector search.

                    User Query
                        ↓
              ┌─────────┴─────────┐
              ↓                   ↓
        Keyword Search       Vector Search
              ↓                   ↓
              └─────────┬─────────┘
                        ↓
                 Combined Results
                        ↓
                       LLM

This can be useful when a query contains important exact terms such as product codes, error codes, API names, or technical identifiers.


18. What is Metadata Filtering?

RAG systems often store metadata along with document chunks.

For example:

Document: LeavePolicy.pdf
Department: HR
Year: 2026
Country: India
Page: 10

The application can use this metadata to restrict retrieval.

For example:

Question
   ↓
Filter:
Country = India
Year = 2026
   ↓
Vector Search
   ↓
Relevant Results

Metadata filtering can be especially useful in enterprise applications where users should only retrieve information relevant to their department, region, product, or access level.


19. Reranking

The first retrieval step may return several potentially relevant chunks. A reranker can then evaluate those results and reorder them based on relevance.

User Question
      ↓
Initial Retrieval
      ↓
20 Candidate Chunks
      ↓
Reranker
      ↓
Top 5 Best Chunks
      ↓
LLM

Reranking can improve retrieval quality in some applications, especially when the initial search returns many similar results.


20. What is a Context Window?

LLMs have a limited amount of information they can process in a single request. This available input capacity is commonly called the context window.

If a RAG system retrieves too much information, it may consume a large portion of the available context.

User Question
      +
Retrieved Chunks
      +
Instructions
      ↓
LLM Context Window

This is one reason why good retrieval is important. The goal is not to retrieve everything. The goal is to retrieve the most useful information.


21. RAG Quality Depends on Retrieval Quality

A powerful LLM cannot completely compensate for poor retrieval.

Consider:

User Question
      ↓
Poor Retrieval
      ↓
Wrong Context
      ↓
LLM
      ↓
Poor Answer

Compare that with:

User Question
      ↓
Good Retrieval
      ↓
Relevant Context
      ↓
LLM
      ↓
Better Answer

This is why RAG development requires attention not only to the LLM but also to document processing and retrieval.


22. Common RAG Problems

Problem 1: Poor Chunking

Important information may be split across chunks in an inconvenient way.

Problem 2: Wrong Retrieval

The vector database may return information that is similar but not actually relevant.

Problem 3: Too Much Context

Retrieving too many chunks can introduce irrelevant information and consume context.

Problem 4: Poor Documents

Badly formatted PDFs, scanned documents, tables, and duplicated content can reduce retrieval quality.

Problem 5: Access Control

A RAG application must ensure that users cannot retrieve documents they are not authorized to access.


23. Complete RAG Architecture

                     INDEXING PIPELINE

Documents
    ↓
Document Loader
    ↓
Text Extraction
    ↓
Chunking
    ↓
Embedding Model
    ↓
Vector Database
    │
    │
    │
    │
    └──────────────────────────────┐
                                   │
                                   ↓
                            QUERY PIPELINE

User Question
    ↓
Query Embedding
    ↓
Metadata Filter
    ↓
Vector / Hybrid Search
    ↓
Reranking
    ↓
Top Relevant Chunks
    ↓
Prompt + Context
    ↓
LLM
    ↓
Final Answer

24. Example: Company Knowledge Assistant

Let's put everything together using a real-world example.

Imagine you are building an AI assistant for a company.

The company has:

500 PDF documents
100 Word documents
1000 HTML pages
Internal technical documentation

The indexing process could be:

Documents
    ↓
Extract Text
    ↓
Clean Text
    ↓
Chunk
    ↓
Generate Embeddings
    ↓
Store in Vector Database

A developer asks:

"How do I resolve error XYZ-102?"

The query pipeline could be:

Question
   ↓
Embedding
   ↓
Vector Search
   ↓
Retrieve Technical Documentation
   ↓
Rerank Results
   ↓
Top Relevant Sections
   ↓
LLM
   ↓
Troubleshooting Steps

25. Where Does the LLM Fit?

The LLM is only one component of a RAG system.

                 RAG Application

┌─────────────────────────────────────────┐
│                                         │
│  Document Processing                    │
│          ↓                              │
│      Embeddings                         │
│          ↓                              │
│    Vector Database                      │
│          ↓                              │
│      Retrieval                          │
│          ↓                              │
│       Context                           │
│          ↓                              │
│         LLM                             │
│          ↓                              │
│       Answer                            │
│                                         │
└─────────────────────────────────────────┘

This is an important concept: RAG is an application architecture, not a type of LLM.


26. RAG Technology Stack

A RAG application can be built using many different technologies.

Layer Examples
Application C#, .NET, Python, JavaScript
LLM GPT, Claude, Gemini, Llama, Qwen
Embedding Model Various text embedding models
Vector Database Various vector database technologies
Document Storage Files, object storage, databases, websites
Retrieval Vector search, keyword search, hybrid search

The exact technology choices depend on your application requirements, scale, cost, security, and infrastructure.


27. RAG with Local LLMs

RAG does not require the LLM to be hosted in the cloud.

You can also build a RAG application using a locally hosted model.

Documents
    ↓
Embeddings
    ↓
Vector Database
    ↓
Retriever
    ↓
Local LLM
    ↓
Answer

Tools such as Ollama can be used to run supported LLMs locally, while your application handles document processing and retrieval.

This can be useful when experimenting with AI locally or when certain data-handling requirements favor local processing.


28. RAG with C# and .NET

RAG is not limited to Python.

Developers can build RAG applications using C# and .NET.

A simplified architecture could look like this:

             ASP.NET Core
                  ↓
              RAG Service
                  ↓
       ┌──────────┼──────────┐
       ↓          ↓          ↓
     LLM     Embeddings   Retriever
                            ↓
                       Vector DB

The application can expose the RAG functionality through a Web API, web application, desktop application, or background service.


29. RAG vs Traditional Database Query

Traditional Database RAG
Structured queries Natural-language questions
Exact conditions Semantic retrieval
Structured data Often unstructured or semi-structured information
Returns records Retrieves context and generates an answer

In real applications, these approaches can also be combined.


30. RAG in Simple Terms

If you remember only one thing from this article, remember this:

Documents
    ↓
Break into Chunks
    ↓
Convert Chunks into Embeddings
    ↓
Store in Vector Database

        ↓

User Asks Question
        ↓
Convert Question into Embedding
        ↓
Search Similar Vectors
        ↓
Retrieve Relevant Chunks
        ↓
Send Context + Question to LLM
        ↓
Generate Answer

Conclusion

A RAG system is much more than simply connecting a chatbot to a vector database.

A well-designed RAG application typically involves document processing, chunking, embeddings, vector storage, semantic retrieval, metadata filtering, reranking, context management, and an LLM.

The most important concepts to understand are:

  • Chunking: Break large documents into useful pieces.
  • Embeddings: Represent text as numerical vectors.
  • Vector Database: Store and search those vectors.
  • Semantic Search: Find information based on meaning.
  • Retrieval: Select relevant information for a question.
  • Context: Provide retrieved information to the LLM.
  • Generation: Let the LLM produce the final response.

Once you understand these components, you are ready to build a real RAG application.

Next: In the next tutorial, we will look at Embeddings in detail and understand how text is converted into vectors and how vector similarity works with practical examples.