LESSON 31 Β· VECTOR DATABASES

What is a Vector Database?

A vector database stores and searches high-dimensional vectors, usually embeddings, so AI applications can quickly find information that is semantically similar to a query.

30 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain what a vector database stores and why embeddings are useful.
  • Understand the difference between a vector and a normal database record.
  • Describe how similarity search works at a high level.
  • Understand metadata, filtering, indexing, and top-k retrieval.
  • Build a small Python mental model of a vector search system.
  • Explain how vector databases fit into semantic search and RAG.
1

What Is a Vector Database?

A vector database is a database designed to store vectors and efficiently retrieve the vectors that are most similar to a query vector. In Generative AI, those vectors commonly come from an embedding model.

VECTOR DATABASEStore vectors + metadata β†’ search by similarity β†’ return the most relevant records
InputQuery embeddingOutputTop matching records
Simple idea:A traditional database is excellent at answering questions such as β€œfind the order where id = 4821.” A vector database is built for questions such as β€œfind the documents whose meaning is closest to this query.”
2

Why Do We Need One?

Embeddings turn text, images, audio, or other content into vectors. Once you have thousands or millions of vectors, you need a practical way to store them, search them, filter them, update them, and retrieve the best matches.

1 Β· DATAMillions of chunks

Knowledge bases can contain a large number of embedded documents.

2 Β· SEARCHSimilarity matters

Exact keyword matching may miss relevant wording and concepts.

3 Β· SPEEDFast retrieval

Searching every vector naively becomes expensive as the collection grows.

4 Β· CONTROLMetadata filters

Real applications often need filters such as product, tenant, language, or date.

Think of the vector database as infrastructure:The embedding model creates the representation; the vector database makes that representation useful at application scale.
3

What Does It Store?

A useful mental model is that one stored item contains more than just a vector. It usually combines the vector with an identifier, metadata, and often the original text or a reference to it.

IDdoc_102Unique identifier
VECTOR[0.12, -0.44, …]Embedding representation
METADATAproduct = "shoes"Structured filters
CONTENT / REFchunk_102.txtText or source reference
Important: The exact storage model differs between products. Some systems store payload text directly; others store a pointer to the source document.
4

Vector Database vs. Traditional Database

They are not necessarily competitors. Many production systems use both: a relational or document database for application data and a vector database or vector index for semantic retrieval.

TRADITIONAL DATABASE

Exact / structured lookup

QueryWHERE customer_id = 4821
  • Rows and structured fields
  • Exact values and ranges
  • Transactions and relationships
VS
VECTOR DATABASE

Similarity lookup

QueryFind content similar to this meaning
  • Vectors and metadata
  • Nearest-neighbor search
  • Semantic retrieval
Do not replace your SQL database automatically:Use each system for the job it is good at. User accounts, orders, payments, and inventory often still belong in traditional databases.
5

How Similarity Search Works

The application first converts the user's query into an embedding. The vector database then compares that query vector with stored vectors and returns the closest matches according to the selected distance or similarity metric.

1. User queryβ€œHow can I reset my password?”
β†’
2. EmbeddingQuery becomes a vector
β†’
3. Vector searchFind nearby vectors
β†’
4. Top resultsRelevant chunks + metadata
Candidate A0.91Very close
Candidate B0.83Relevant
Candidate C0.58Less similar
6

What Does β€œTop-k” Mean?

Most retrieval systems ask for the top-k nearest results. If k = 5, the search returns the five highest-ranked candidates after applying the selected search rules.

QUERYβ€œreturn policy for damaged items”
#1Damaged item returns0.94
#2Return policy0.89
#3Refund conditions0.81
#4Replacement process0.76
#5Shipping damage claims0.72

A high similarity score does not automatically mean the result is correct. Retrieval quality should be evaluated on your real questions and documents.

7

Metadata Makes Retrieval More Useful

Similarity is only one dimension of retrieval. Metadata lets you narrow the search before or during vector retrieval.

tenant_idSearch only one customer's data.
categoryRestrict results to support articles.
languageReturn documents in the user's language.
datePrefer or restrict recent information.
VECTOR QUERYβ€œHow do I cancel an order?”
+
FILTERcategory = orders
β†’
SEARCH SPACEOnly matching records
8

Indexing: How Search Becomes Fast

If a collection contains a huge number of vectors, comparing a query with every single vector can be expensive. Vector systems therefore use indexing and approximate nearest-neighbor techniques to search efficiently.

NAIVE SEARCHCompare with everything

Simple conceptually, but costly at large scale.

β†’
VECTOR INDEXOrganize the search space

Use an index to find promising nearby candidates quickly.

β†’
RESULTSReturn top-k

Rank the candidate vectors and return the best matches.

Trade-off:Approximate search can exchange a small amount of recall for much better speed and scale. The right index and settings depend on the workload.
9

Python: A Tiny Vector Store Mental Model

This example is intentionally simple. It shows the data flow without depending on a particular vector database vendor.

</> Python
documents = [
    {"id": "doc-1", "text": "Reset your password from account settings.", "vector": [0.90, 0.10]},
    {"id": "doc-2", "text": "Track your order from the shipping page.", "vector": [0.20, 0.85]},
    {"id": "doc-3", "text": "Update your billing address in your profile.", "vector": [0.65, 0.35]},
]

query_vector = [0.82, 0.18]

# In a real vector database, the index performs this search efficiently.
# Here we keep the example conceptual and focus on the stored structure.
for document in documents:
    print(document["id"], document["text"], document["vector"])

print("Query vector:", query_vector)
What to notice:Each record has an ID, content, and vector. A real vector database adds persistent storage, indexing, similarity search, filtering, updates, and operational features around this basic idea.
10

Python: Calculate a Simple Similarity Ranking

Before using a database, it helps to understand the operation it accelerates. This small example ranks two-dimensional vectors with cosine similarity.

</> Python
import numpy as np

def cosine_similarity(a, b):
    a = np.array(a, dtype=float)
    b = np.array(b, dtype=float)
    denominator = np.linalg.norm(a) * np.linalg.norm(b)
    return float(np.dot(a, b) / denominator)

query = [0.82, 0.18]
candidates = {
    "password reset": [0.90, 0.10],
    "order tracking": [0.20, 0.85],
    "billing address": [0.65, 0.35],
}

ranked = sorted(
    ((name, cosine_similarity(query, vector))
     for name, vector in candidates.items()),
    key=lambda item: item[1],
    reverse=True,
)

for name, score in ranked:
    print(f"{score:.3f}  {name}")
Connection to the database:This is the same basic ranking idea you learned in the previous cosine-similarity lesson. A vector database makes this operation practical for much larger collections and adds storage, indexing, filtering, and retrieval APIs.
11

Vector Database in a RAG System

RAG uses retrieval to bring relevant external information into the model's context. A vector database is commonly used as the retrieval layer for that workflow.

DocumentsPDFs, pages, FAQs
β†’
ChunksSmall searchable units
β†’
EmbeddingsVectors representing meaning
β†’
Vector DBStore + index + search
β†’
LLMAnswer with retrieved context
IngestionChunk content and create embeddings.
RetrievalEmbed the user query and search for nearby vectors.
GenerationPass the best retrieved chunks to the LLM.
12

Vector Database vs. Vector Index

These terms are related but not identical. A vector index is the search structure; a vector database is a broader storage and retrieval system that can manage vectors, metadata, persistence, and APIs.

APPLICATIONRAG / Semantic Search
↓
DATABASE LAYERVectors + metadata + CRUD
↓
SEARCH LAYERVector index / nearest-neighbor search
↓
STORED DATAEmbeddings + records
Why this matters: When evaluating a vector product, look beyond β€œdoes it store vectors?” Also consider filtering, persistence, indexing options, updates, backups, security, scaling, and operational tooling.
13

Common Vector Database Operations

INSERT / UPSERTStore a vector

Add a new document or replace an existing record.

QUERYSearch by similarity

Return the nearest vectors for a query embedding.

FILTERNarrow candidates

Combine semantic search with structured metadata.

UPDATERefresh knowledge

Change metadata, content references, or embeddings.

DELETERemove records

Delete stale, private, or invalid content.

FETCHRead by ID

Retrieve a known vector record directly.

14

When Should You Use a Vector Database?

SEMANTIC SEARCHMeaning-based search

Find relevant content even when the query and document use different words.

RAGPrivate knowledge

Retrieve company documents, manuals, policies, or product knowledge for an LLM.

RECOMMENDATIONSSimilar items

Find products, articles, images, or users with similar representations.

IMAGE SEARCHVisual similarity

Search for images using image embeddings instead of filenames alone.

CLASSIFICATION SUPPORTNearest examples

Retrieve similar historical examples before making a decision.

DISCOVERYExplore related content

Surface documents or media that are conceptually close to a selected item.

15

What a Vector Database Does Not Do

It does not create embeddings.

The embedding model normally converts content into vectors. The database stores and searches those vectors.

It does not understand text like an LLM.

A vector search system retrieves candidates. An LLM can then reason over retrieved context.

It does not guarantee relevant answers.

Poor chunking, poor embeddings, weak filters, or bad queries can still produce poor retrieval.

It is not automatically a replacement for SQL.

Most applications still need conventional databases for structured transactional data.

16

How to Choose One Later

You do not need to choose a vendor in this lesson. When you reach that decision, compare the system against your actual workload.

ScaleHow many vectors and queries?
FilteringWhich metadata filters are required?
LatencyHow quickly must results return?
RecallHow much retrieval quality matters?
OperationsHosted or self-managed?
CostStorage, queries, and infrastructure.
Evaluate with your own dataset:A benchmark that looks good on a generic dataset may not produce the best retrieval quality or cost profile for your application's documents.
PRACTICE

Design a Tiny Knowledge Base

Imagine you are building a customer-support RAG application.

  1. Choose 10 support articles.
  2. Split them into searchable chunks.
  3. Assign each chunk an ID and metadata such as category and language.
  4. Create an embedding for every chunk.
  5. Imagine a user asks: β€œHow do I reset my password?”
  6. Describe what the vector database should return as the top 3 results.
Challenge: Write down which metadata filter you would use if the user is asking specifically about the mobile app and explain why semantic similarity alone may not be enough.
QUICK QUIZ

Test Your Understanding

1. What is the main job of a vector database?

Store and efficiently retrieve vectors and associated records using similarity search.

2. What is usually stored alongside an embedding?

An identifier and metadata, plus content or a reference to the source content.

3. What does top-k retrieval mean?

Return the k highest-ranked candidate results from the search.

4. Does a vector database replace an LLM?

No. It retrieves relevant information; the LLM can use that information to generate an answer.

5. Why are vector indexes important?

They make nearest-neighbor search much more efficient on large vector collections.

30-Second Recap

ContentDocuments / data
β†’
EmbeddingMeaning β†’ vector
β†’
Vector DBStore + index
β†’
SimilarityFind nearest
β†’
RAGUse context

Key Takeaways

  • A vector database is designed to store and retrieve high-dimensional vectors efficiently.
  • Embeddings represent the meaning or characteristics of content as vectors.
  • Similarity search finds records whose vectors are close to a query vector.
  • Metadata filtering can make retrieval more precise and safer.
  • Indexes help vector search scale beyond naive comparisons.
  • Vector databases are commonly used in semantic search, recommendations, and RAG.
  • The database retrieves information; it does not replace the embedding model or LLM.