Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 43

Vector Database Fundamentals

This lesson is built with resources from youtube.com, github.com and 1 more site.

Hello! Welcome back to our module on Retrieval-Augmented Generation (RAG).

In our last lesson, you mastered the art of converting text into vector embeddings—the numerical fingerprints that capture semantic meaning. We now have the "what" (vectors), but we need to address the "where" and "how." How do we store potentially millions of these vectors and search through them with millisecond latency to find the most relevant ones for a user's query?

This lesson will answer that question. Our goal is to set up and query a vector database (e.g., FAISS, ChromaDB) to store and retrieve documents. You'll learn what a vector database is, why it's a critical component of any RAG system, and how to use one in practice.

Why Not a Traditional Database?

You have a background as a backend developer, so you're very familiar with relational (like PostgreSQL) and NoSQL (like MongoDB) databases. You might wonder, why can't we just store vectors in a new column?

The challenge lies in the query. In a traditional database, you query based on exact matches or ranges on indexed fields (e.g., WHERE user_id = 123 or WHERE price > 100). With vectors, we need to find the "closest" vectors to our query vector based on a distance metric like cosine similarity. Doing this naively—by comparing the query vector to every single vector in the database—is computationally infeasible for large datasets.

This is where vector databases shine. They are purpose-built for one thing: extremely fast and efficient similarity search in high-dimensional spaces.

To get a clear overview of what vector databases are and the problems they solve, let's start with a short video.

Complete Tutorial on Vector Database - Learn ChromaDB, Pinecone & Weaviate | Generative AI

This video from DSwithBappy provides an excellent conceptual introduction to vector databases. It explains why we need them for unstructured data and reinforces the role of embeddings.

Watch the first 9 minutes of the video (up to 08:55). Focus on understanding the limitations of traditional databases for unstructured data and how vector databases, combined with embeddings, solve this problem.


Getting Hands-On with ChromaDB

There are many vector databases available, from managed cloud services like Pinecone to low-level libraries like FAISS. For this lesson, we'll focus on ChromaDB. It's an open-source, developer-friendly vector database that is incredibly easy to set up and use, making it perfect for learning and building prototypes. It can run in-memory, be persisted to disk, or even run as a client-server application.

We will follow a practical workflow:

  1. Install and initialize ChromaDB.
  2. Create a "collection" to hold our data.
  3. Add documents (text, embeddings, and metadata) to the collection.
  4. Perform a similarity search by querying the collection.

The following video is a concise walkthrough of these exact steps. We will reference it as we go through the code.

Getting Started with ChromaDB - Lowest Learning Curve Vector Database For Semantic Search

This tutorial by Johnny Code is a fast-paced, practical guide to the basics of ChromaDB. We'll use it to see the core API in action.

Watch from the beginning to 03:21. This will cover installation, creating a client and collection, adding data, and querying. We'll break down the code for each step below.

Step 1: Setup and Initialization

First, install ChromaDB in your Python environment:

pip install chromadb

Next, you initialize a client. By default, this creates an in-memory instance.

import chromadb

# Initialize the ChromaDB client (in-memory)
client = chromadb.Client() 

Step 2: Creating a Collection

In ChromaDB, a collection is where you store your embeddings, documents, and metadata. It's analogous to a table in a relational database.

When you create a collection, ChromaDB automatically sets it up with a high-quality sentence-transformer model (all-MiniLM-L6-v2, the same one we recommended in the last lesson!) to generate embeddings for you. This makes it extremely easy to get started.

# Create a new collection or get an existing one
# ChromaDB will handle embedding generation by default
collection = client.get_or_create_collection(name="my_first_collection")

Step 3: Adding Documents

Now, let's add some data. The collection.add() method is the workhorse here. You provide it with parallel lists for the documents, their metadata, and unique IDs. Your experience with structured data formats will make this feel very natural.

  • documents: A list of text strings.
  • metadatas: A list of dictionaries, where each dictionary can hold structured data associated with a document (e.g., source, author, chapter). This is vital for filtering and for providing context in a RAG application.
  • ids: A list of unique string identifiers for each document.
collection.add(
    documents=[
        "A RAG system retrieves relevant documents to augment a prompt.",
        "Vector embeddings are numerical representations of text meaning.",
        "The weather in London is usually cloudy.",
        "To cook pasta, bring a large pot of salted water to a boil."
    ],
    metadatas=[
        {'source': 'AI-docs', 'topic': 'RAG'},
        {'source': 'AI-docs', 'topic': 'Embeddings'},
        {'source': 'general-knowledge', 'topic': 'Weather'},
        {'source': 'cooking-recipes', 'topic': 'Food'}
    ],
    ids=["doc1", "doc2", "doc3", "doc4"]
)

Step 4: Querying the Collection

This is the similarity search step. You provide a query text, and ChromaDB embeds it and finds the most similar documents in the collection.

# Query the collection to find the 2 most similar documents
results = collection.query(
    query_texts=["What is the process for making pasta?"],
    n_results=2
)

# Print the results
import json
print(json.dumps(results, indent=2))

The output will look something like this:

{
  "ids": [
    [
      "doc4",
      "doc3"
    ]
  ],
  "distances": [
    [
      0.6811...,
      1.4646...
    ]
  ],
  "metadatas": [
    [
      {
        "source": "cooking-recipes",
        "topic": "Food"
      },
      {
        "source": "general-knowledge",
        "topic": "Weather"
      }
    ]
  ],
  "embeddings": null,
  "documents": [
    [
      "To cook pasta, bring a large pot of salted water to a boil.",
      "The weather in London is usually cloudy."
    ]
  ]
}

Notice that the document about cooking pasta (doc4) has the smallest distance, indicating it's the most similar.

Test your understanding!

Looking at the JSON output above, how would you use Python to access the text of the most relevant document returned by the query?

Show answer

You would access it using results['documents'][0][0].

  • results['documents'] gets the list of document lists.
  • The first [0] accesses the results for the first query (since you can pass multiple queries at once).
  • The second [0] accesses the first document in the similarity-ranked list.

Building a Mini RAG-Retriever

Let's tie this into a more realistic RAG scenario. A crucial step before adding documents to a vector database is chunking.

RAG Chunking Process
This image illustrates the standard chunking pipeline: breaking a large document into smaller, more manageable pieces that can be individually retrieved.

We chunk large documents into smaller pieces (e.g., paragraphs or sentences) for two main reasons:

  1. Targeted Retrieval: A user's question might be answerable by a single paragraph within a 50-page document. Retrieving just that paragraph is more efficient and provides a more focused context to the LLM than retrieving the whole document.
  2. Context Window Limits: The retrieved context, plus your prompt, must fit within the LLM's context window. Smaller chunks make this easier to manage.

For a deeper explanation of chunking, the same video we watched earlier has a great segment on it.

Complete Tutorial on Vector Database - Learn ChromaDB, Pinecone & Weaviate | Generative AI

Let's revisit the "Complete Tutorial on Vector Database" video to understand the why and how of document chunking.

Watch the segment from 49:07 to 54:01. The speaker clearly explains the need for chunking and the concept of 'chunk overlap' to preserve context between chunks.

Now, let's write a Python script that simulates the retrieval part of a RAG system.

import chromadb
from sentence_transformers import SentenceTransformer

# 1. Our "Knowledge Base" (a single large document)
knowledge_base_text = """
ChromaDB is an open-source vector database. It is designed to be easy to use and is ideal for developing AI applications with embeddings. 
You can run it in-memory, persist it to disk, or use it in a client-server mode. 
To add data, you create a collection and use the 'add' method, providing documents, metadatas, and unique IDs.
Querying is done via the 'query' method, which performs a similarity search to find the most relevant documents for a given query text.
By default, ChromaDB uses the 'all-MiniLM-L6-v2' model for generating embeddings, which offers a good balance of performance and speed.
For production use, it is recommended to persist the database to disk.
"""

# 2. Chunking the document
# A simple strategy: split by newline. In a real application, you'd use a library like LangChain's text splitters.
chunks = [chunk.strip() for chunk in knowledge_base_text.strip().split('\n')]

# 3. Setup ChromaDB
client = chromadb.Client()
collection = client.get_or_create_collection("rag_collection")

# 4. Embed and Store the chunks
collection.add(
    documents=chunks,
    ids=[f"chunk_{i}" for i in range(len(chunks))]
    # We could add more detailed metadata here
)

# 5. User Query
user_query = "How do you search for data in ChromaDB?"

# 6. Retrieve relevant chunks
retrieved_results = collection.query(
    query_texts=[user_query],
    n_results=2 # Get the top 2 most relevant chunks
)

print("--- User Query ---")
print(user_query)
print("\n--- Retrieved Context Chunks ---")
for doc in retrieved_results['documents'][0]:
    print(f"- {doc}")

# This retrieved context would then be passed to an LLM in the next step.

Persisting Your Database

Running in-memory is great for quick tests, but if your application restarts, you lose all your data. For any real use case, you'll want to persist the database to disk. This is very straightforward in ChromaDB and will feel familiar to your work with other databases.

You simply initialize a PersistentClient instead of the default Client.

# Initialize a client that will store data in the 'my_rag_db' directory
persistent_client = chromadb.PersistentClient(path="./my_rag_db")

# You can now create and use collections just as before
# The data will be saved automatically
persisted_collection = persistent_client.get_or_create_collection("production_rag")

This simple change makes your vector store durable, a key requirement for production systems. For a quick visual on this, the ChromaDB video we watched has a short segment at the end.

Getting Started with ChromaDB - Lowest Learning Curve Vector Database For Semantic Search

The final part of the ChromaDB tutorial shows how to switch from an in-memory client to a persistent one.

Watch from 09:59 to 10:35 to see the code for creating a persistent database.


A Quick Look at FAISS

The learning outcome also mentions FAISS (Facebook AI Similarity Search). It's important to understand what it is and how it differs from ChromaDB.

  • FAISS is a library, not a database. It provides highly optimized C++ indexes for similarity search with a Python wrapper. It's incredibly fast but is lower-level. You are responsible for building the database logic around it (storing metadata, handling updates, etc.).
  • ChromaDB is a database. It uses indexing algorithms (like HNSW, a popular method also available in FAISS) internally but provides a much higher-level, user-friendly API with features like metadata filtering, automatic embedding generation, and a client-server architecture.

For a deeper conceptual understanding of FAISS and its trade-offs, the following article is an excellent resource.

Vector DB implementation using FAISS

This article, 'Vector DB implementation using FAISS', provides a great high-level overview of FAISS, its components, and its pros and cons.

Please read the sections 'Overview of the Components', 'Advantages and Disadvantages of FAISS', and 'Different Types of Indexes Supported by FAISS'. You don't need to study the code implementation, just focus on the conceptual descriptions.

The key takeaway is a classic engineering trade-off:

  • ChromaDB: Higher-level, easier to use, faster development. A great starting point.
  • FAISS: Lower-level, more control, potentially higher performance if tuned correctly, but requires more engineering effort.

Conclusion

You've now bridged the gap between creating embeddings and using them for retrieval. You have a functional, searchable knowledge base—the heart of a RAG system.

Key Takeaways:

  • Vector databases are specialized systems for storing and performing efficient similarity searches on high-dimensional vectors.
  • ChromaDB is a developer-friendly, open-source vector database that simplifies the process with features like automatic embedding generation and metadata management.
  • The core workflow is to create a collection, add documents (with metadata and IDs), and then query the collection to find semantically similar results.
  • Chunking large documents before embedding is a critical pre-processing step for effective retrieval in RAG.
  • Libraries like FAISS offer a lower-level, higher-performance alternative, trading ease-of-use for more control.

Next Up:

In this lesson, we built a simple script to retrieve documents. In the next lesson, we will formalize this process and implement the full retrieval component of a RAG system, connecting it to a query and preparing the context for the final generation step.