Back to Techniques

Vector Databases

Efficient storage and retrieval of high-dimensional embeddings.

Last updated: July 2026

DataEmbeddingVector DBQueryNearest matches
Data

You start with raw content - documents, images, or product records.

Data
How Vector Databases worksletslearngenai.com
Listen: Vector Databases (student & teacher)StudentTeacher
0:000:00

A vector database is a specialized data storage and retrieval system designed to store, index, and search high-dimensional numerical representations of data (called embeddings or vectors). Unlike traditional databases that look for exact matches (e.g., 'find the user with ID 42'), a vector database finds items that are semantically similar to a query. That makes it the backbone of modern AI-powered search, recommendations, and RAG applications.

Most real-world data (text, images, audio, video) cannot be searched with simple keyword matching. A vector database lets AI systems understand meaning, not just words. It's the infrastructure layer that makes RAG, semantic search, and personalized recommendations possible at scale. Without it, LLMs can only work with what's in their training data. With it, they can query your entire company's knowledge base in milliseconds.

ComponentWhat it doesExample
Embedding Generation
Raw data (text, image, audio) is passed through an embedding model (e.g., Sentence-BERT, OpenAI text-embedding-3, CLIP), which converts it into a list of numbers: a vector like [0.12, -0.84, 0.33, ...]. Each number captures a dimension of meaning.The sentence 'The dog chased the ball' becomes a 1536-dimensional vector. The sentence 'A puppy ran after the sphere' produces a different but numerically close vector because the meaning is similar.
Vector Storage
Vectors, along with their metadata (e.g., document title, source URL, timestamp), are stored in the database for later retrieval and filtering.An e-commerce platform stores product descriptions as vectors alongside metadata like {product_id: 102, category: 'shoes', price: 79.99} so search results can later be filtered by price.
Indexing (HNSW / IVF)
Vectors are organized using specialized index structures, most commonly HNSW (Hierarchical Navigable Small World) or IVF (Inverted File Index), so similarity search doesn't require scanning every stored vector.Think of HNSW like a well-organized city map with highways (top layer) and local roads (bottom layer). When you search, you start on the highway and zoom in progressively to your destination, rather than walking every street.
Similarity Search (ANN)
When a user submits a query, it's also converted to a vector. The database uses Approximate Nearest Neighbor (ANN) algorithms to find the stored vectors mathematically closest to the query using cosine similarity, Euclidean distance, or dot product.A user types 'lightweight running shoes for flat feet.' This query becomes a vector. The database returns the top 5 product vectors that are spatially nearest: products semantically aligned with that description even if the exact words don't match.

Full assembled example

A company builds a RAG chatbot over its HR policy PDFs: (1) PDFs are chunked into 400-token segments. (2) Each chunk is passed through text-embedding-3-small to produce a 1536-dim vector. (3) Vectors + metadata (doc_name, page_number) are stored in Pinecone with an HNSW index. (4) At query time, the user's question is also embedded. (5) ANN search returns the top 5 semantically matching chunks. (6) Those chunks are passed to GPT-5.5 as context. Result: grounded, non-hallucinated answers from company data.

Core Principles

  • 1Semantic similarity over exact match - Vectors that are numerically close represent concepts that are semantically related. Searching for 'automobile' will surface results about 'car' and 'vehicle' because their embeddings are nearby in vector space. No keyword overlap required.
  • 2Same model for encoding and querying - The embedding model used to store data must be the same model used to encode queries. Mixing models (e.g., storing with BERT, querying with OpenAI) produces incoherent results. It's like translating a book into French, then searching it in German.
  • 3Distance metrics define similarity - The chosen metric (cosine similarity, Euclidean distance, dot product) shapes what 'similar' means. Cosine similarity measures angular closeness (ideal for text); Euclidean measures spatial distance (better for images).
  • 4ANN trades precision for speed - Approximate search finds near-perfect results in milliseconds instead of perfect results in minutes. A recommendation engine that responds in 50ms with 95% accuracy is far more useful than one taking 10 seconds with 100% accuracy.
  • 5Metadata filtering enables precision - Raw vector similarity alone can surface irrelevant results. Combining vector search with metadata filters (e.g., category = 'legal', date > 2024) narrows results to what's actually relevant.
  • 6Embeddings must be retrained when models change - If you switch embedding models (e.g., upgrade from text-embedding-ada-002 to text-embedding-3-large), all stored vectors must be regenerated. Stale vectors cause degraded search quality silently.

Flat Index (Brute Force)

Every query is compared against every stored vector. This is exact, not approximate, and guarantees 100% recall at the cost of linear scan time.

Prompt

You have 10,000 medical research abstracts and need 100% recall for a clinical audit. Flat index ensures no relevant document is missed.

Output

Exact nearest neighbors with perfect recall - suitable only for small datasets where speed is not a constraint
Use when:Small datasets (<100K vectors), evaluation/testing, or scenarios where precision is non-negotiable.

HNSW (Hierarchical Navigable Small World)

Builds a multi-layer proximity graph. Queries traverse from broad to fine layers to find nearest neighbors extremely fast.

Prompt

A news aggregator with 50 million articles needs real-time semantic search. HNSW returns results in under 10ms.

Output

Sub-10ms query latency at high recall - the default choice for production systems requiring both speed and accuracy
Use when:Large-scale production systems requiring low-latency search with high recall.

IVF (Inverted File Index)

Clusters vectors into buckets. A query searches only nearby clusters instead of the full dataset, trading some recall for lower memory use.

Prompt

A streaming service stores 200 million song embeddings. IVF narrows search to the most relevant cluster of genres/moods before comparing.

Output

Fast search over very large datasets with configurable recall/latency trade-off via the nprobe parameter
Use when:Very large datasets where memory is limited; often combined with HNSW as a hybrid (IVF+HNSW).

Product Quantization (PQ / SQ)

Compresses vectors into smaller representations to dramatically reduce memory footprint at a minor cost to precision.

Prompt

A startup needs to run vector search on a budget server. Product Quantization compresses 1536-dim vectors by 8-32x, fitting a billion vectors in memory.

Output

8–32x memory reduction enabling billion-scale vector storage on commodity hardware
Use when:Cost-constrained environments or when storing billions of vectors where memory is the primary bottleneck.

pgvector (Vector Extension for PostgreSQL)

Adds vector similarity search directly to PostgreSQL, enabling hybrid relational and semantic queries without a separate vector database.

Prompt

A team already uses PostgreSQL for user data. They add pgvector (a PostgreSQL extension that adds vector search) and store document embeddings in a new column, combining SQL joins with semantic search in one query.

Output

Semantic search integrated into existing SQL queries: SELECT * FROM docs ORDER BY embedding <=> query_vec LIMIT 5
Use when:Teams with existing PostgreSQL infrastructure who want to avoid maintaining a separate vector store.

Common Mistakes

MistakeReal-World ScenarioFix
Mixing embedding modelsStoring documents with BERT but querying with OpenAI embeddings. Results are nonsensical.Use one model version for all encode/query operations; re-embed if you switch models
Embedding entire documentsA 30-page technical manual stored as one vector; queries return the whole manual instead of the relevant paragraphChunk documents into 300–500 token segments before embedding
Skipping metadata filtersA legal AI retrieves semantically similar documents from the wrong country's jurisdictionAlways combine vector similarity with structured metadata filters
Not normalizing vectorsCosine similarity rankings are skewed because vectors have inconsistent magnitudesL2-normalize all vectors before insert and query
Using flat index at scaleA production app with 50M vectors uses brute-force search. Queries take 30+ seconds.Switch to HNSW or IVF for datasets beyond ~100K vectors
Ignoring index rebuild after bulk updatesMillions of new vectors inserted but index not rebuilt. Search quality degrades silently.Schedule periodic index rebalancing or use databases with auto-indexing
Over-relying on vector search aloneA RAG chatbot returns answers from outdated documents because there's no date filterAdd metadata-based pre/post filtering to enforce recency and relevance

Use Cases by Industry

Use CaseReal-World ExampleBest Approach
Semantic searchEnterprise intranet search that understands 'vacation policy' = 'PTO guidelines'HNSW index + keyword metadata filter hybrid
RAG (Retrieval-Augmented Generation)LLM chatbot that answers questions about your product docs without hallucinatingChunk docs → embed → retrieve top-k → pass to LLM as context
Recommendation engineSpotify-style 'songs similar to this one' using audio embeddingsIVF index with genre/mood metadata filter
Image similarity searchFashion retail lets users upload a photo to find visually similar productsCLIP embeddings + HNSW; filter by category/price
Anomaly & fraud detectionBank flags transactions whose behavior vectors deviate from a user's historical patternCompute distance from user's centroid vector; threshold-based alerting
Customer support automationAI triages incoming tickets by finding semantically similar resolved ticketsEmbed ticket text → match to resolved ticket vectors → suggest solution
1

Basic Semantic Search with ChromaDB (Python)

Prompt

import chromadb
from chromadb.utils import embedding_functions

client = chromadb.Client()
embed_fn = embedding_functions.SentenceTransformerEmbeddingFunction(
    model_name="all-MiniLM-L6-v2"
)
collection = client.create_collection(name="faq", embedding_function=embed_fn)

collection.add(
    documents=[
        "You can reset your password from the account settings page.",
        "Refunds are processed within 5–7 business days.",
        "Our customer support team is available Monday to Friday, 9am–6pm EST.",
    ],
    ids=["faq1", "faq2", "faq3"]
)

results = collection.query(
    query_texts=["How do I change my login credentials?"],
    n_results=2
)
print(results["documents"])

Output

[['You can reset your password from the account settings page.',
  'Our customer support team is available Monday to Friday, 9am–6pm EST.']]

The query 'change my login credentials' semantically matched 'reset your password' with zero keyword overlap.
2

RAG Pipeline with Pinecone + OpenAI

Prompt

# Step 1: Embed and upsert document chunks (run once at ingestion)
for chunk in chunks:
    embedding = openai.Embedding.create(
        input=chunk["text"], model="text-embedding-3-small"
    )["data"][0]["embedding"]
    index.upsert([(chunk["id"], embedding, {"text": chunk["text"]})])

# Step 2: Query at runtime
user_query = "How many vacation days do I get?"
query_embedding = openai.Embedding.create(
    input=user_query, model="text-embedding-3-small"
)["data"][0]["embedding"]

results = index.query(vector=query_embedding, top_k=2, include_metadata=True)
context = " ".join([r["metadata"]["text"] for r in results["matches"]])

# Step 3: Pass context to LLM
response = openai.ChatCompletion.create(
    model="gpt-5.5",
    messages=[
        {"role": "system", "content": "Answer using only the provided context."},
        {"role": "user", "content": f"Context: {context}\n\nQuestion: {user_query}"}
    ]
)

Output

Employees are entitled to 20 days of paid leave per year.

This is the full RAG loop: embed → store → retrieve → generate. The LLM never hallucInates because it's grounded in retrieved context.
3

Image Similarity Search with FAISS

Prompt

import faiss
import numpy as np

# Simulated CLIP embeddings for 5 products (512-dim)
product_embeddings = np.random.rand(5, 512).astype("float32")
faiss.normalize_L2(product_embeddings)  # Normalize for cosine similarity

# Build FAISS flat index
index = faiss.IndexFlatIP(512)  # Inner product = cosine similarity after normalization
index.add(product_embeddings)

# Simulate user uploading a photo → CLIP produces query embedding
query_embedding = np.random.rand(1, 512).astype("float32")
faiss.normalize_L2(query_embedding)

# Search for top 3 similar products
distances, indices = index.search(query_embedding, k=3)
print("Top 3 similar product indices:", indices[0])
print("Similarity scores:", distances[0])

Output

Top 3 similar product indices: [2, 0, 4]
Similarity scores: [0.973, 0.961, 0.948]

The three most visually similar products are retrieved in order of cosine similarity. In production, these indices map back to product IDs and catalog metadata.

Tools & Platforms

ToolBest ForType
PineconeManaged production vector DB; fastest to deploy with no infrastructure overheadManaged cloud
ChromaLocal/LLM app development; beginner-friendly, LangChain/LlamaIndex nativeOpen-source / embedded
MilvusOpen-source, high-scale enterprise deployments; supports billions of vectorsSelf-hosted open-source
QdrantSelf-hosted with advanced filtering; strong Rust-based performanceSelf-hosted open-source
WeaviateMulti-modal search + GraphQL API; integrates directly with OpenAI/CohereManaged / self-hosted
FAISSHigh-performance local similarity search; GPU-accelerated; research/prototypingLibrary (in-process)
pgvectorAdding vector search to existing PostgreSQL databases without a separate systemPostgreSQL extension
LlamaIndexData framework for ingestion, chunking, and querying vector storesOrchestration framework

Frequently asked questions

What is a vector database?

A vector database is a specialized system for storing and retrieving high-dimensional numerical data known as embeddings or vectors. Unlike traditional databases that match exact data entries, vector databases find data that is semantically similar to a query, making them crucial for AI applications like semantic search and personalized recommendations.

How do vector databases work?

Vector databases work by converting raw data into vectors using embedding models, storing these vectors along with metadata, and indexing them for efficient retrieval. When a query is made, it's transformed into a vector, and the database uses algorithms like Approximate Nearest Neighbor (ANN) to find the most similar stored vectors, enabling semantic search.

What are the benefits of using vector databases in AI?

Vector databases enable AI systems to understand the meaning behind data rather than just keywords, facilitating advanced applications like semantic search and retrieval-augmented generation (RAG). They allow for rapid querying of large datasets, providing relevant and personalized results by finding semantically similar data points.

What are common mistakes when using vector databases?

Common mistakes include mixing different embedding models for storage and querying, which leads to incoherent results, and not using metadata filters, which can result in irrelevant search outcomes. Additionally, failing to normalize vectors or rebuild indexes after updates can degrade search quality.

What industries benefit from vector databases?

Industries such as e-commerce, media streaming, and financial services benefit from vector databases. They enable semantic search for customer support, recommendation engines for music and video, and anomaly detection for fraud prevention, enhancing the precision and speed of data retrieval.