Vector Databases

Updated · 6 min read
mediumPython 3.13aiembeddingsvector-databasessearchpython

A vector database is a database that stores embeddings together with the text and metadata they came from, and finds the vectors nearest to a query vector quickly. It is used when there are too many documents to compare one by one, and when results must be filtered, for example by category, date or permission.

What a Vector Database Stores

Vectors, text and metadata, searched together
PartDescription
IDIt is used to identify each record, so it can be updated or deleted
VectorIt is used to find similar records by meaning
TextIt is used to show the result and to send it to a model
MetadataIt is used to filter results, such as by category, date, source or who may see it
IndexIt is used to find nearest vectors fast without checking every one

Example: A Tiny Vector Store

This program builds a small in-memory vector store over the 50 FAQ answers from "Semantic Search" (faq.json), with a category filter:

Python
import json
 
import numpy as np
from sentence_transformers import SentenceTransformer
 
class VectorIndex:
    """A tiny in-memory vector store: vectors, their items, and search with a filter."""
 
    def __init__(self, model):
        self.model = model
        self.items = []
        self.vectors = np.empty((0, model.get_embedding_dimension()))
 
    def add(self, items):
        new = self.model.encode([item["text"] for item in items], normalize_embeddings=True)
        self.vectors = np.vstack([self.vectors, new])
        self.items += items
 
    def search(self, query, k=2, category=None):
        scores = self.vectors @ self.model.encode(query, normalize_embeddings=True)
        hits = [(float(scores[i]), self.items[i]) for i in scores.argsort()[::-1]
                if category is None or self.items[i]["category"] == category]
        return hits[:k]
 
index = VectorIndex(SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2"))
index.add(json.load(open("faq.json")))
print("Stored", index.vectors.shape[0], "vectors of", index.vectors.shape[1], "numbers")
 
for category in [None, "admission"]:
    print("Filter:", category or "none")
    for score, item in index.search("Is there anything happening in March?", category=category):
        print(f"  {score:.2f}  [{item['category']}] {item['text']}")
Output
Stored 50 vectors of 384 numbers
Filter: none
  0.51  [timetable] Spring break is the week of March 23.
  0.41  [timetable] Spring term starts on January 12 and ends on May 29.
Filter: admission
  0.40  [admission] Admission forms for next year are due by March 1.
  0.31  [admission] Decisions are sent by email in the second week of April.

Explanation: add() embeds each item and stacks its vector under the others, keeping the items in the same order. search() scores every vector, sorts them, and keeps only items that match the filter. Without a filter, the March question returns spring break; with category="admission", it returns the March 1 forms deadline, which is what a family applying to the school needs.

The tiny store checks every vector, which is fine for thousands of items. With millions, vector databases use an approximate nearest-neighbor (ANN) index: it groups similar vectors and checks only the most promising groups, so it is much faster but can occasionally miss a close match.

KindDescription
Exact searchIt is used for small collections; checks every vector, never misses
Approximate (ANN) searchIt is used for large collections; checks promising regions, very fast, rarely misses

Common Choices in November 2026

OptionDescription
pgvectorIt is used to add vector search to a PostgreSQL database you already run
ChromaIt is used for local projects and prototypes, with a simple Python interface
FAISSIt is used as a fast vector search library inside your own program
Managed servicesIt is used when you want a hosted vector database, such as Pinecone or a cloud provider's offering

Common Mistakes

Storing vectors without the text and metadata. You can't show, filter or cite a result you can't trace back.

Forgetting to re-embed after changing documents. Update the vector whenever its text changes.

Filtering after taking the top results. Filter first, or you may end up with too few results.

Interview Corner

What does a vector database add over storing vectors in a list?

Fast nearest-neighbor search at scale (usually approximate), metadata filtering, and normal database features such as updates, deletes, persistence and access control.

What is approximate nearest-neighbor search?

An index that finds very close vectors without checking every one, trading a small chance of missing the true nearest match for a large gain in speed.

Practice

Exercise: add a date filter. Add a "month" field to a few timetable answers and let search() filter by it. Then search "When are exams?" with and without the filter.

Check your understanding:

  1. What four things does a vector database record hold?
  2. What did the admission filter change in the example?
  3. When do you need approximate search?

Quick check: vector databases

4 questions
1What does a vector database store with each vector?
2What did category="admission" return first for the March question?
3What does an approximate nearest-neighbor index trade?
4Why filter by who may see a document?

Key Takeaways

Quick reference

NeedApproach
Thousands of itemsExact search in memory
Millions of itemsAn ANN index in a vector database
Already on PostgreSQLpgvector
Restrict resultsMetadata filters

Was this tutorial helpful?

Lesson 93 of 186