Skip to main content
Logo image
Apptastic Coder
AI

Vector Databases from Scratch: A Hands-On Guide for AI Engineers

Build, Index, and Query Embeddings Without Black Boxes

Save & share
On this page29 sections

Full Article

Read the complete article, including examples, background, practical insights, and technical details.

Summary

Vector databases make it possible to retrieve information by similarity: a question about "resetting a forgotten password" can find a document titled "Recover access to your account," even when their wording differs.

This guide builds a small, in-memory vector store in Python. You will generate embeddings, validate and store vectors, implement exact similarity search, add metadata filters, and expose the result through an API. You will also learn how approximate indexes change the speed?accuracy tradeoff and what a production database needs beyond a nearest-neighbor algorithm.

The storage and search logic are built from scratch. We use an existing embedding model because training a language model is a separate project.


Introduction

A keyword search looks for words or tokens. A vector search compares numerical representations of the query and stored items. This helps when users describe an idea differently from the documents that explain it.

Imagine a developer knowledge base containing React tutorials, database troubleshooting notes, and deployment guides. A search for "make database reads faster" should retrieve relevant indexing material even if the document never uses that exact phrase.

The basic retrieval pipeline has two paths:

Ingestion: Documents -> Chunks -> Embedding model -> Stored vectors + metadata
Retrieval: User query -> Embedding model -> Similarity search -> Ranked chunks

Understanding each stage helps you diagnose poor results. An index cannot repair an embedding that misses your domain's meaning, and a strong embedding cannot recover text that was never ingested.

Prerequisites and Setup

You need Python 3.10 or newer and basic familiarity with lists, dictionaries, functions, and NumPy arrays. Create a virtual environment, activate it for your shell, then install the tutorial dependencies:

python -m venv .venv
python -m pip install numpy sentence-transformers fastapi uvicorn

Run the installation command after activating the environment. Save the Python examples from Steps 1?3, in order, into vector_store.py. Later sections explain where to put the sample data and API code.

The first embedding-model load downloads model files and requires network access. Subsequent runs can use the locally cached files. Record dependency versions and the model revision when reproducing results across machines.


What Is a Vector Database?

A vector database stores vectors alongside record identifiers, source content, and metadata, then retrieves records using a distance or similarity metric.

A typical record looks like this:

id: "article-42-chunk-3"
vector: [0.12, -0.08, 0.31, ...]
text: "An index can reduce the number of rows scanned..."
metadata: {"tag": "database", "document_id": "article-42"}

The vector supports ranking. The text supplies something useful to display or pass to a language model. Metadata supports constraints such as language, category, document version, or ownership.

Traditional databases can also support vector search, and dedicated vector databases often support exact metadata filters. The distinction is the retrieval operation, not an absolute division between two kinds of database.

A nearest-neighbor index is only one component. A production database also handles durable storage, concurrent writes, updates, deletion, recovery, access control, and operational monitoring. Our implementation deliberately starts with the retrieval core.


Core Concepts: Embeddings and Similarity

What an Embedding Represents

An embedding is a numerical representation produced by a model. Models trained for semantic retrieval aim to place relevant text near related text in their vector space.

Individual dimensions generally do not have simple labels such as "programming" or "sports." Meaning is represented across the vector. Proximity is a learned signal, not proof that two statements are equivalent or factually correct.

Stored vectors and query vectors must belong to a compatible embedding space. Equal dimensions alone do not make two different models compatible. Keep the model identity, revision, preprocessing, and normalization policy with your collection configuration.

Choosing a Similarity Metric

Metric What it measures Better match
Cosine similarity Alignment between two vectors Higher score
Dot product Alignment influenced by vector magnitude Higher score
Euclidean distance Straight-line distance between vectors Lower distance

Cosine similarity is:

cosine(a, b) = dot(a, b) / (norm(a) * norm(b))

If both vectors have unit length, cosine similarity equals their dot product. For unit vectors, squared Euclidean distance is 2 - 2 * dot(a, b), so these metrics produce equivalent rankings, apart from ties and numerical rounding.

This tutorial normalizes vectors once when inserting them and normalizes each query before searching. A cosine score is not a probability or a confidence percentage. Any threshold for accepting results needs evaluation on your own queries.


Step 1: Generating Embeddings

Start vector_store.py with the model and an embedding function:

import numpy as np
from sentence_transformers import SentenceTransformer

MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
model = SentenceTransformer(MODEL_NAME)


def embed(text):
    if not isinstance(text, str) or not text.strip():
        raise ValueError("Text must be a non-empty string")
    return model.encode(text, convert_to_numpy=True)

SentenceTransformer.encode converts text into a NumPy embedding. The library also supports batch encoding and optional normalization; our store will handle normalization explicitly. See the Sentence Transformers API documentation.

For ingestion, encode batches instead of repeatedly calling the model for individual records. Choose a batch size that fits the available memory.

Split Long Documents Before Embedding

Embedding models have finite input limits. Passing an entire book or a long article may truncate useful content and compress several unrelated topics into one representation.

Split documents at meaningful boundaries such as headings and paragraphs. Each chunk should contain enough context to be understandable on its own. A small overlap can preserve ideas that cross boundaries, but excessive overlap creates duplicate results and increases storage.

Keep the parent document ID, chunk position, and source URL with each chunk. Tune chunk size using retrieval examples from your application instead of assuming one size works for every corpus.


Step 2: Storing Vectors

Append the following store and helper functions to vector_store.py:

database = {}
vector_dimension = None


def normalize(vector):
    vector = np.asarray(vector, dtype=np.float32)
    if vector.ndim != 1 or vector.size == 0:
        raise ValueError("Expected a non-empty, one-dimensional vector")
    if not np.all(np.isfinite(vector)):
        raise ValueError("Vector values must be finite")
    length = float(np.linalg.norm(vector.astype(np.float64)))
    if length == 0:
        raise ValueError("Zero vectors cannot be normalized")
    return (vector.astype(np.float64) / length).astype(np.float32)


def add_vector(record_id, vector, text, metadata=None):
    global vector_dimension
    if not isinstance(record_id, str) or not record_id:
        raise ValueError("Record ID must be a non-empty string")
    if record_id in database:
        raise ValueError(f"Duplicate record ID: {record_id}")
    unit_vector = normalize(vector)
    if vector_dimension is not None and unit_vector.size != vector_dimension:
        raise ValueError("Vector dimension does not match the collection")
    record_metadata = dict(metadata or {})
    vector_dimension = unit_vector.size
    database[record_id] = {
        "vector": unit_vector,
        "text": text,
        "metadata": record_metadata,
    }

A dictionary gives us explicit, unique IDs. Rejecting duplicates avoids silently replacing a record. An update operation could intentionally replace an existing record, but it should make that behavior clear.

The validation catches malformed vectors, non-finite values, zero vectors, and dimension mismatches before they reach the search loop. It cannot detect vectors from a different model with the same dimensions; that requires collection-level model configuration.

Everything currently lives in memory and disappears when the process exits. That limitation is useful for learning but must be addressed before relying on the store for durable data.


Append an exact search function:

def search(query_vector, top_k=5, filters=None):
    if isinstance(top_k, bool) or not isinstance(top_k, int) or top_k < 1:
        raise ValueError("top_k must be a positive integer")
    query = normalize(query_vector)
    if vector_dimension is not None and query.size != vector_dimension:
        raise ValueError("Query dimension does not match the collection")

    filters = dict(filters or {})
    results = []
    for record_id, item in database.items():
        if not all(
            key in item["metadata"] and item["metadata"][key] == value
            for key, value in filters.items()
        ):
            continue
        score = float(np.dot(query, item["vector"]))
        results.append({
            "id": record_id,
            "score": score,
            "text": item["text"],
            "metadata": dict(item["metadata"]),
        })

    results.sort(key=lambda result: (-result["score"], result["id"]))
    return results[:top_k]

Because both vectors are normalized, the dot product gives cosine similarity. Results are ordered by descending score, with IDs breaking ties consistently. An empty collection or a filter with no matches returns an empty list.

For N records of dimension D, the unfiltered scoring work is O(N * D). Sorting all scores adds O(N log N) work, although a heap or partial selection can reduce the cost of finding only the best k results.

This implementation favors clarity. A contiguous NumPy matrix and matrix?vector multiplication can make exact search much faster without changing its mathematical result. Keep exact search as a reference when evaluating approximate indexes.


Step 4: Indexing for Speed

Exact search compares the query with every eligible vector. Approximate nearest-neighbor search, or ANN, searches a smaller set of candidates and may miss some of the true nearest neighbors.

Two important approaches are:

  • HNSW: Builds a graph with multiple levels. Search navigates through progressively closer nodes. Search breadth trades latency against recall, while graph connectivity also affects memory use. The original HNSW paper describes the algorithm.
  • IVF: Partitions vectors into clusters and searches selected clusters for each query. It needs representative training data. Searching more clusters increases coverage and work; Faiss exposes this setting as nprobe. See the Faiss index guide.

An approximate index is not automatically better for every workload. Small collections, strict filters, or efficient hardware may make exact search sufficient.

Before replacing the search function, measure latency on realistic data. Then compare ANN results with the exact top k:

recall@k = count(approximate_top_k intersect exact_top_k) / k

This formula assumes at least k eligible records. Use the same query vectors, filters, and metric for both searches, and average results across representative queries. ANN recall measures agreement with exact vector search; it does not establish whether the retrieved documents answer the user's question.

Keep the index-to-record-ID mapping synchronized with your metadata store. Adding, updating, or deleting a document must also update its indexed representation.


Step 5: Building an API

Create api.py beside vector_store.py. This example loads a small corpus at startup and exposes a search endpoint using the same Python functions:

from contextlib import asynccontextmanager

from fastapi import FastAPI
from pydantic import BaseModel, Field

from vector_store import add_vector, database, embed, search

DOCUMENTS = [
    ("1", "Learn React components, props, and state.", {"tag": "dev"}),
    ("2", "A beginner's guide to cricket batting techniques.", {"tag": "sports"}),
    ("3", "Speed up database reads with indexes.", {"tag": "dev"}),
]


@asynccontextmanager
async def lifespan(app):
    for record_id, text, metadata in DOCUMENTS:
        if record_id not in database:
            add_vector(record_id, embed(text), text, metadata)
    yield


app = FastAPI(lifespan=lifespan)


class SearchRequest(BaseModel):
    query: str = Field(min_length=1, max_length=2000, pattern=r"\S")
    top_k: int = Field(default=5, ge=1, le=50)
    tag: str | None = None


@app.post("/search")
def search_endpoint(request: SearchRequest):
    filters = {"tag": request.tag} if request.tag is not None else None
    return {
        "results": search(embed(request.query), request.top_k, filters)
    }

FastAPI uses a Pydantic model to read and validate the JSON request body, as explained in its request-body documentation.

Start the service:

python -m uvicorn api:app --reload

Open http://127.0.0.1:8000/docs and submit this body to /search:

{
  "query": "learn frontend development",
  "top_k": 2,
  "tag": "dev"
}

The response contains matching IDs, scores, text, and metadata. Use the response to inspect relevance rather than expecting a particular hard-coded score.

This demo loads one model and one in-memory collection per process. Multiple workers would have independent copies. A deployed service needs a shared storage strategy, bounded request work, and a plan for model loading and inference capacity. The reload flag is intended for development.


Step 6: Metadata and Filters

The search function already applies metadata filters before scoring. For example:

results = search(
    embed("improve query performance"),
    top_k=3,
    filters={"tag": "dev"},
)

All supplied fields must match exactly. A missing field does not match, even if the requested value is None. Our simple filter language does not support ranges, nested fields, or Boolean expressions.

Filtering matters because the closest vector is not always an eligible result. A document may belong to another category, be outdated, or be inaccessible to the current user.

With ANN, filtering can become more complicated. Retrieving ten global neighbors and then discarding unauthorized or mismatched records may return fewer than ten useful results, even when many eligible records exist. Evaluate the index's filtering behavior under realistic selectivity.

For access control, derive mandatory tenant or user restrictions from authenticated server-side context. A category filter supplied by the caller is not an authorization mechanism.


Persistence, Updates, and Deletion

To make the store survive restarts, persist vectors, IDs, source text, metadata, and the collection's embedding configuration together.

For a learning project, a NumPy file for the matrix and JSON for records can work. Store a manifest with the model revision, dimensions, metric, and schema version. Write snapshots to a new generation and publish a pointer to that generation only after all files are complete, so interrupted writes do not pair new vectors with old metadata.

For a service with ongoing writes, consider transactional record storage and a recoverable indexing process. Define when a successful write becomes searchable and how to replay changes after a crash.

An update that changes text requires a new embedding. A metadata-only edit usually does not. Deleting a document must remove or invalidate every associated chunk in search, persistence, and caches.

Changing the embedding model usually means re-embedding the corpus. Build a separate collection, evaluate it, and switch traffic after validating results instead of mixing incompatible embeddings.


Scaling Considerations

Estimate Memory Before Choosing an Index

Raw float32 vectors require approximately:

vector_bytes = number_of_vectors * dimensions * 4

One million 384-dimensional vectors use about 1.54 GB in decimal units, or 1.43 GiB, before metadata, Python object overhead, indexes, and temporary query buffers. Our dictionary representation adds substantial overhead compared with a contiguous matrix.

Compression can reduce memory, but may change retrieval quality. Measure the effect on your workload.

Separate Ingestion from Query Serving

Document parsing, chunking, and batch embedding are ingestion tasks. User-facing queries need predictable latency. Use queues or separate workers when ingestion competes with search for compute resources.

Cache embeddings for repeated text when useful. Include the model version in the cache key, and include relevant filters and collection versions when caching search results.

Combine Keyword and Vector Retrieval

Semantic similarity helps with paraphrases. Keyword retrieval is valuable for exact identifiers, error codes, and product names. Hybrid retrieval combines both candidate sets.

Their raw scores may have different scales. A rank-based method such as reciprocal rank fusion can combine rankings without treating a keyword score as directly comparable to a cosine score. Evaluate fusion and optional reranking using real queries.

Shard When Measurements Justify It

Sharding distributes records across machines, but introduces query routing, result merging, rebalancing, and failure handling. For comparable scores, each shard can return local candidates that a coordinator merges into a global ranking. ANN misses and selective filters still affect the result.

Track retrieval quality, tail latency, memory use, ingestion lag, and error rates before adding distributed complexity.


Mini Project: Search a Developer Knowledge Base

Create demo.py beside the other files:

from vector_store import add_vector, embed, search

articles = [
    ("react", "Build user interfaces with React components and hooks.", "dev"),
    ("indexes", "Database indexes speed up queries by reducing row scans.", "dev"),
    ("cricket", "Practice batting footwork and shot selection in cricket.", "sports"),
]

for record_id, text, tag in articles:
    add_vector(record_id, embed(text), text, {"tag": tag})

for hit in search(embed("make database reads faster"), top_k=2):
    print(f"{hit['id']}: {hit['score']:.3f} | {hit['text']}")

Run it with python demo.py. The database-indexing article is the intended relevant result; inspect the actual ranking to see whether the model captures the relationship.

Extend the project with ten to twenty articles and a small set of labeled queries. Include paraphrases, exact technical terms, ambiguous requests, and questions with no relevant answer.

Evaluate three different things:

  1. Correctness: Duplicate IDs, invalid vectors, mismatched dimensions, empty collections, and filters behave as documented.
  2. Relevance: Results actually answer the query, based on human labels. A query without a useful match should not automatically be treated as answered merely because search returned a neighbor.
  3. Performance: Measure embedding time and search time separately, then record end-to-end latency under realistic concurrency.

For a RAG application, pass selected source chunks to the generator with their identifiers. Evaluate both retrieval and the final answer: a fluent response can still be unsupported by the retrieved evidence.


Conclusion

A minimal vector store needs embeddings, record storage, a similarity metric, and a ranking function. Building these pieces yourself makes the tradeoffs visible: normalization determines scoring, chunking shapes what can be retrieved, filtering defines eligible results, and indexing trades exhaustive comparisons for faster candidate search.

Use this implementation as an exact-search baseline and a learning tool. Add durability and operational safeguards as your requirements grow, and choose a production storage system based on measured retrieval quality, workload, and maintenance needs.


FAQ

Do I need a dedicated vector database for every AI application?

No. Some applications do not need retrieval at all. Others can use an in-memory matrix, an existing database with vector support, keyword search, or a combination of approaches. RAG does not inherently require a dedicated vector database.

Which similarity metric should I use?

Follow the embedding model's intended scoring method and evaluate it on your data. Cosine is useful when direction matters more than magnitude. Normalizing vectors makes cosine and dot-product rankings equivalent, but normalization may discard information for models that rely on magnitude.

When should I add approximate indexing?

When a measured exact-search baseline cannot meet your latency or throughput requirements within your resource budget. There is no universal record-count threshold; dimensions, filtering, hardware, and concurrency all matter.

Can I store embeddings from different models together?

Use separate collections unless the models are explicitly designed to share a compatible space. Matching vector dimensions is not sufficient.

Why does search return an irrelevant result?

Nearest-neighbor search returns the closest available item, even when every item is a poor match. Investigate missing source content, chunk boundaries, model suitability, filters, and query ambiguity. Use evaluated acceptance rules or reranking when the application needs to decline weak matches.

Is this implementation production-ready?

It is an educational, in-memory baseline. It does not implement durable transactions, coordinated concurrent writes, authentication, replication, or recovery. Its value is making the retrieval mechanics understandable and giving you a reference for testing more advanced systems.

Published
Share this article

Comments load as you scroll…