Lesson 1 of 9 · Concepts
Why Vector Databases?
Vector databases for beginners: what they store, their operations (upsert, query, filter, delete), why a Python list stops scaling, and where they fit in RAG.
- 6 min read
- Intermediate
- Reviewed
- Explain what a vector database stores and what it is for
- Name the core operations: upsert, query, filter and delete
- Work out why searching a plain list becomes too slow and too big
- Recognise where a vector database sits in a search or RAG app
From a list to a database
In the Embeddings course, you stored vectors in a Python list and compared a query with every one of them. That works for a few thousand documents. Real apps have millions, they add and change documents all day, many users search at once, and the data must survive a restart.
Every record in a vector database has four parts:
| Part | Example | Why it is stored |
|---|---|---|
| ID | "faq-0042" | To update or delete the record later |
| Vector | [0.12, -0.53, ...] (often hundreds of numbers) | To find similar records |
| Document | "You can change a booking up to 24 hours before departure." | To show the result, or pass it to an LLM |
| Metadata | {"lang": "en", "product": "flights"} | To filter results, such as by language or user |
The core operations
Almost every vector database offers the same handful of operations, whatever their exact names:
- Upsert records (one at a time or in batches).
- Query: give a vector, get back the k most similar records, with their scores.
- Filter: limit a query to records whose metadata matches, such as
lang = "en". - Delete records by ID or by filter.
Records are grouped into a collection (some products call it an index or a table), and each collection holds vectors from one embedding model with one size.
Here is the whole idea in a few lines of Python. Real vector databases do the same job, just much faster and at much larger scale:
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
class TinyVectorStore:
"""The core of every vector database, in a few lines."""
def __init__(self):
self.records = {} # id -> (vector, document, metadata)
def upsert(self, id, vector, document, metadata=None):
self.records[id] = (vector, document, metadata or {}) # insert or replace
def delete(self, id):
self.records.pop(id, None)
def query(self, vector, k=2):
scored = []
for id, (vec, doc, meta) in self.records.items():
scored.append((cosine(vector, vec), id, doc))
scored.sort(reverse=True) # most similar first
return scored[:k]
# Toy 3-number embeddings: [travel, food, tech]
store = TinyVectorStore()
store.upsert("a1", [0.9, 0.1, 0.0], "Booking cheap flights")
store.upsert("a2", [0.1, 0.9, 0.1], "Easy pasta recipes")
store.upsert("a3", [0.0, 0.1, 0.9], "Fixing a slow laptop")
store.upsert("a4", [0.7, 0.6, 0.0], "Best street food in Bangkok")
print("Query: 'where to eat on holiday'")
for score, id, doc in store.query([0.6, 0.8, 0.0], k=2):
print(f" {score:.2f} {id} {doc}")
store.upsert("a2", [0.1, 0.9, 0.1], "Easy pasta and rice recipes") # same id: replaced
store.delete("a3")
print("Records stored:", len(store.records))Writing a2 again replaced the old record instead of adding a second copy. That is what makes upsert safe to re-run when a document changes.
Why a plain list stops working
Our query compares the query with every stored vector. Let's count that work for a realistic app:
# How much work is one brute-force search?
documents = 1_000_000 # one million chunks of text
dimensions = 1536 # numbers per embedding
multiplications = documents * dimensions
print(f"Multiplications per query: {multiplications:,}")
queries_per_second = 50
print(f"Per second at {queries_per_second} queries/s: {multiplications * queries_per_second:,}")
bytes_needed = documents * dimensions * 4 # 4 bytes per float32 number
print(f"Memory for the vectors alone: {bytes_needed / 1e9:.1f} GB")Over a billion and a half multiplications for one search, and 6 GB of numbers to keep in memory. A vector database solves this with:
- Indexes that find near neighbours by checking only a small fraction of the vectors (next two lessons).
- Storage on disk, with memory used as a fast cache.
- Filtering, updates and deletes that keep working while the data changes.
- Scaling: splitting data across machines, copies for reliability, many users at once.
Where it fits
A vector database is usually one piece of a larger app:
- Semantic search: the search box on a website or in an app.
- RAG (retrieval-augmented generation): fetch relevant text, then let an LLM answer from it.
- Recommendations: “more like this” for products, articles or songs.
- Duplicate detection: find near-identical support tickets, images or records.
Common mistakes
Complete upsert so a new id is added and an existing id is replaced, never duplicated. The program should then print 2 records, and the updated title for a1.
records = {}
def upsert(id, document):
# Insert a new record, or replace the one that already has this id
pass
upsert("a1", "Booking flights")
upsert("a2", "Pasta recipes")
upsert("a1", "Booking cheap flights")
print(len(records))
print(records["a1"])
What does an upsert do when a record with the same ID already exists?
Summary
- A vector database stores IDs, vectors, documents and metadata, and finds the vectors most similar to a query.
- The core operations are upsert, query, filter and delete, grouped into collections.
- Searching every vector costs about documents × dimensions multiplications per query, which becomes too slow and too large.
- Vector databases add indexes, storage, filtering and scaling to fix this.
Next: how nearest neighbour search works, and what “approximate” really means.
Finished reading? Tick it off to track your progress.