AI

Vector Database for RAG: How It Works and Which to Pick

Vector Database for RAG: How It Works and Which to Pick

Short answer: a vector database stores embeddings, which are lists of numbers that capture what a piece of text means. Given a question, it finds the stored texts whose numbers are closest to the question's, fast. In RAG, that is the retrieval step: it picks the passages the LLM reads before it answers. For a few thousand chunks you often don't need one; plain Python, numpy or pgvector is enough.

This guide explains how vector search works, shows it in runnable Python, and ends with a fair comparison of Chroma, Qdrant, pgvector, FAISS, Milvus, Weaviate, Pinecone and LanceDB.

What a vector database is, in plain words

Think of a library that shelves books by topic instead of by title. Books about graphs sit together. Books about salary talks sit together, far away from the graphs. If you walk in with a question, you go to the right shelf and grab the nearest few books.

A vector database does the same thing with numbers. An embedding model turns each piece of text into a vector, a fixed-length list of numbers. Texts with similar meaning get vectors that point in similar directions. The database stores those vectors and answers one main question: which stored vectors are nearest to this new one?

It has three jobs:

  1. Store each vector with its original text and some metadata, extra fields such as topic, date or owner.
  2. Search for the nearest vectors to a query vector, usually the top k (the best k matches).
  3. Keep up with changes: add, update and delete rows, save them to disk, and stay fast as data grows.

A normal database answers "which rows have topic = 'hr'?". A vector database answers "which rows mean something close to this question?". Many vector databases now do both in one query.

Why RAG needs one

RAG stands for retrieval-augmented generation. You search your own documents first, then paste the best passages into the prompt, so the large language model (LLM) answers from them. If RAG is new to you, start with Crio's RAG explained, with code. The RAG retrieval pipeline simulator shows each stage visually.

The vector database works at two moments:

  • Indexing time (when documents change): split documents into chunks, embed each chunk, and store the vectors with their text and metadata.
  • Query time (every question): embed the question with the same model, ask the database for the nearest chunks, and send those chunks to the LLM.

The LLM never sees the database. It only sees the few chunks that come back. So if the search returns the wrong chunks, the answer is wrong, however good the model is.

Embeddings and similarity in one minute

An embedding model maps text to a vector, often with hundreds of numbers. Vectors from two different models live in different spaces, so never mix them in one search. For a hands-on start with real embeddings and pgvector, see Crio's lesson on embeddings and vector search.

"Nearest" needs a distance measure. There are three common ones:

  • Cosine similarity compares direction only. 1 means same direction, 0 means unrelated.
  • Dot product multiplies matching numbers and adds them up. Longer vectors get bigger scores.
  • Euclidean (L2) distance is the straight-line distance between the two points.

If every vector is scaled to length 1 (normalised), all three give the same ranking. Many tools rely on this. Check which one your tool uses by default. Chroma's default space is l2 (squared L2), and you can switch a collection to cosine or ip (inner product). pgvector gives each measure its own SQL operator. Our RAG interview questions post has a short program that compares all three on the same vectors, so we won't repeat it here.

Build a tiny vector store in plain Python

Here is a complete vector store in standard-library Python. The store itself is under 40 lines; the rest is data and a demo. It holds 12 short placement-prep notes, each tagged with a topic.

One warning first. A real system uses a trained embedding model. To keep this runnable with no downloads, we use a toy embedding: a hashed bag of words. Each word is hashed into one of 1,000 slots and counted, then the vector is scaled to length 1. It matches shared words only, not meaning. That weakness is useful, because it shows exactly what a real model adds.

# toy_store.py: a tiny vector store in plain Python (brute-force cosine search)
import hashlib, math, re

DIM = 1000  # length of every toy vector
STOP = {"a", "an", "the", "is", "in", "on", "of", "to", "and", "or", "for", "by",
        "with", "it", "its", "so", "do", "i", "my", "how", "what", "when", "you",
        "your", "are", "be", "this", "that", "one", "no", "not", "than", "about",
        "should", "if"}

def embed(text):
    """TOY embedding: hashed bag of words. NOT a real embedding model.
    Each word is hashed into one of DIM buckets, then the vector is scaled
    to length 1. It only matches shared words, not meaning."""
    vec = [0.0] * DIM
    for word in re.findall(r"[a-z0-9]+", text.lower()):
        if word not in STOP:
            vec[int(hashlib.md5(word.encode()).hexdigest(), 16) % DIM] += 1.0
    norm = math.sqrt(sum(x * x for x in vec)) or 1.0
    return [x / norm for x in vec]

class TinyVectorStore:
    def __init__(self):
        self.ids, self.vectors, self.texts, self.metas = [], [], [], []

    def add(self, id_, text, meta):
        self.ids.append(id_); self.texts.append(text); self.metas.append(meta)
        self.vectors.append(embed(text))

    def query(self, text, k=3, where=None):
        q = embed(text)
        scored = []
        for id_, vec, meta in zip(self.ids, self.vectors, self.metas):
            if where and any(meta.get(key) != val for key, val in where.items()):
                continue  # metadata filter: skip rows that do not match
            cosine = sum(a * b for a, b in zip(q, vec))  # both have length 1
            scored.append((round(cosine, 3), id_))
        scored.sort(key=lambda s: (-s[0], s[1]))  # best first, ties by id
        return scored[:k]

CHUNKS = [
    ("dsa-1", "dsa", "Detect a cycle in a linked list with two pointers: slow moves one step, fast moves two."),
    ("dsa-2", "dsa", "Binary search needs a sorted array and halves the search range at every step."),
    ("dsa-3", "dsa", "Solve two-sum in one pass with a hash map: store each number, look up its complement."),
    ("dsa-4", "dsa", "BFS finds the shortest path in an unweighted graph; use Dijkstra when edges have weights."),
    ("sd-1", "system-design", "A load balancer spreads incoming requests across many servers."),
    ("sd-2", "system-design", "Cache frequent database reads in Redis to cut latency; set an expiry on each key."),
    ("sd-3", "system-design", "Sharding splits one large database table across machines using a shard key."),
    ("hr-1", "hr", "Answer 'tell me about yourself' in 90 seconds: education, one project, why this role."),
    ("hr-2", "hr", "Asked about CTC expectations? Give a researched range, not a single number."),
    ("hr-3", "hr", "For the weakness question, name a real weakness and the step you are taking to fix it."),
    ("apt-1", "aptitude", "If A finishes a job in 10 days and B in 15 days, together they need 6 days."),
    ("apt-2", "aptitude", "Profit percentage is profit divided by cost price, times 100."),
]

if __name__ == "__main__":
    store = TinyVectorStore()
    for id_, topic, text in CHUNKS:
        store.add(id_, text, {"topic": topic})
    print(f"stored {len(store.ids)} chunks, {DIM} numbers each")
    for question, where in [
        ("shortest path in a weighted graph", None),
        ("how do I make slow database queries faster", None),
        ("what salary should I ask for", None),
        ("how should I answer this question", {"topic": "hr"}),
    ]:
        print(f"\nQ: {question}" + (f"   where={where}" if where else ""))
        for score, id_ in store.query(question, k=3, where=where):
            print(f"  {score:.3f}  {id_}")

Output:

stored 12 chunks, 1000 numbers each

Q: shortest path in a weighted graph
  0.452  dsa-4
  0.000  apt-1
  0.000  apt-2

Q: how do I make slow database queries faster
  0.141  sd-3
  0.135  sd-2
  0.112  dsa-1

Q: what salary should I ask for
  0.000  apt-1
  0.000  apt-2
  0.000  dsa-1

Q: how should I answer this question   where={'topic': 'hr'}
  0.224  hr-1
  0.224  hr-3
  0.000  hr-2

Four things to notice:

  • It works when words overlap. The graph question finds the BFS and Dijkstra note (0.452) through "shortest", "path" and "graph".
  • It ranks by words, not meaning. For slow queries, the sharding note (0.141) beats the caching note (0.135). Both share only "database". A human would pick caching first. A trained embedding model has a fair chance of doing the same.
  • It misses synonyms completely. "Salary" never appears in the notes; the CTC note says "CTC expectations". Every score is 0.000. Matching "salary" to "CTC" is the whole reason to use a real embedding model.
  • It always returns k results. Even with every score at zero, you still get three rows. Real vector databases behave the same way. Add a minimum score, or your LLM gets irrelevant chunks.

The where filter in the last query kept only HR notes, so the search never looked at the others. Hashing has one more catch: two different words can land in the same slot, called a collision. In this demo, 2 pairs of words share a slot, and none of those words appears in a question.

This store compares the question with every stored vector. That is called brute-force or flat search, and it is exact. Its cost grows in a straight line with the number of vectors.

Exact vs approximate search: flat, IVF and HNSW

Flat search is perfect but slow at scale. Approximate nearest neighbour (ANN) indexes skip most of the vectors and accept that they will sometimes miss a true match. The share of true top-k matches they still find is called recall@k. A recall@10 of 0.90 means 9 of the true 10 nearest came back.

Flat. Compare with everything. FAISS's own guide says the flat index is "the only index that can guarantee exact results". pgvector also does exact search by default, which its docs say "provides perfect recall".

IVF (inverted file index). First group the vectors into clusters, using k-means, and remember each cluster's centre. At query time, find the few centres nearest the question and search only those clusters. Picture a city split into neighbourhoods. To find the nearest chai stall, you check only the two or three neighbourhoods closest to you. pgvector's IVFFlat index works this way: it "divides vectors into lists, and then searches a subset of those lists". The number of lists searched is called probes (nprobe in FAISS).

HNSW (hierarchical navigable small world). Build a graph where each vector links to some of its neighbours. Stack a few layers on top, each with fewer vectors and longer links. A search starts at the sparse top layer, jumps close to the target, then drops down and refines. It is like travelling by highway, then main road, then lane. The method comes from a 2016 paper by Malkov and Yashunin.

The program below measures the IVF trade-off on seeded random data. The vectors are grouped around 50 random centres, a rough stand-in for real embeddings, which tend to cluster by topic. We compare IVF results against brute force, which gives the true answer. To keep the toy small, it uses √N lists. That is far fewer than FAISS's guide suggests (4√N to 16√N under 1 million vectors).

# ivf_recall.py: exact (brute-force) search vs a tiny IVF index on seeded random data
import math, random

DIM, K, QUERIES = 8, 10, 40

def unit(v):
    n = math.sqrt(sum(x * x for x in v))
    return [x / n for x in v]

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def make_data(n, rng):
    # Clustered data, a rough stand-in for embeddings that group by topic
    centres = [unit([rng.gauss(0, 1) for _ in range(DIM)]) for _ in range(50)]
    data = []
    for _ in range(n):
        c = rng.choice(centres)
        data.append(unit([x + rng.gauss(0, 0.35) for x in c]))
    return data

def top_k(query, ids, data):
    return sorted(ids, key=lambda i: -dot(query, data[i]))[:K]

def build_ivf(data, n_lists, rng, rounds=5):
    # k-means: pick n_lists centroids, then refine them a few times
    cents = rng.sample(data, n_lists)
    for _ in range(rounds):
        lists = [[] for _ in range(n_lists)]
        for i, v in enumerate(data):
            lists[max(range(n_lists), key=lambda c: dot(v, cents[c]))].append(i)
        cents = [unit([sum(data[i][d] for i in ids) for d in range(DIM)]) if ids else cents[c]
                 for c, ids in enumerate(lists)]
    return cents, lists

print(f"{'vectors':>7} {'lists':>5} {'probes':>6} {'scanned':>8} {'recall@10':>9}")
for n in (1_000, 4_000, 16_000):
    rng = random.Random(42)
    points = make_data(n + QUERIES, rng)
    data, queries = points[:n], points[n:]  # queries are new points, not in the index
    exact = [set(top_k(q, range(n), data)) for q in queries]  # brute force = truth
    n_lists = round(math.sqrt(n))
    cents, lists = build_ivf(data, n_lists, rng)
    for probes in (1, 4, 16):
        found = scanned = 0
        for q, truth in zip(queries, exact):
            near = sorted(range(n_lists), key=lambda c: -dot(q, cents[c]))[:probes]
            ids = [i for c in near for i in lists[c]]
            scanned += len(ids)
            found += len(truth & set(top_k(q, ids, data)))
        print(f"{n:>7,} {n_lists:>5} {probes:>6} {scanned / (QUERIES * n):>8.1%} "
              f"{found / (QUERIES * K):>9.2f}")

Output:

vectors lists probes  scanned recall@10
  1,000    32      1     3.4%      0.47
  1,000    32      4    12.6%      0.85
  1,000    32     16    50.3%      1.00
  4,000    63      1     1.7%      0.45
  4,000    63      4     6.7%      0.86
  4,000    63     16    25.8%      1.00
 16,000   126      1     0.8%      0.48
 16,000   126      4     3.2%      0.83
 16,000   126     16    12.8%      1.00

"Scanned" is the share of stored vectors compared per question. It leaves out the few comparisons with cluster centres. Read the table row by row:

  • One probe is fast and sloppy. It scans under 4% of vectors but finds fewer than half of the true top 10 (0.45 to 0.48).
  • More probes buy recall. Four probes reach 0.83 to 0.86. Sixteen reach 1.00 here.
  • Bigger data makes approximate search pay off. At 16,000 vectors, 16 probes found every true match while scanning only 12.8%. At 1,000 vectors, the same setting scanned half the data, so flat search was nearly as cheap.

That is the trade-off every ANN index exposes: a knob that swaps speed for recall. Each tool names the knobs differently:

IndexKnobspgvector defaultsChroma defaults
Flatnoneused when there is no indexnot offered as a setting
IVF (IVFFlat)lists, probesprobes = 1; start with lists = rows / 1000 up to 1M rowsnot offered
HNSWlinks per node, build list size, search list sizem = 16, ef_construction = 64, ef_search = 40max_neighbors = 16, ef_construction = 100, ef_search = 100

Raising ef_search in HNSW or probes in IVF improves recall and slows queries. pgvector's README says to start IVFFlat probes at √lists. Its comparison is also useful: IVFFlat builds faster and uses less memory than HNSW, but HNSW has the better speed-recall trade-off.

HNSW is not free on memory. FAISS's guide gives its size as (d × 4 + M × 2 × 4) bytes per vector. Here d is the number of dimensions and M the links per vector. At d = 768 and M = 16, that is 3,200 bytes per vector. Ten million such vectors need about 32 GB, against 30.72 GB for the raw float32 vectors alone. FAISS also notes that all its indexes live in RAM.

Filtering means searching only rows whose metadata matches, such as topic = "hr" or company = "TCS". RAG systems use it for two big reasons: relevance (only this course's notes) and permissions (only documents this user may see). Do the permission check in the database query itself. An LLM told to "ignore documents this user can't see" is not access control.

Filters and approximate indexes do not always mix well. pgvector checks the filter only once the approximate index has produced its candidates. Say 10% of rows match your filter. With HNSW and the default ef_search of 40, you get back about 4 rows on average, not 10. Since version 0.8.0, pgvector can run iterative index scans, which keep scanning until enough rows match. Other databases handle filtering inside the index search itself; check how yours does it before you trust filtered results.

Hybrid search runs two searches, one by keywords and one by vectors, and fuses their results into one list. Keyword search, often BM25, is strong on exact strings like error codes, product SKUs and names. Vector search is strong on paraphrases. A common merge method is reciprocal rank fusion (RRF), which combines ranks rather than raw scores. Our RAG interview questions post works through BM25 and RRF in code. Support differs by tool:

  • Weaviate combines BM25 keyword search with vector search in one query.
  • Qdrant merges dense and sparse vectors with RRF or DBSF (distribution-based score fusion).
  • Milvus has built-in BM25 full-text search alongside dense vectors.
  • pgvector pairs with Postgres full-text search; its docs suggest RRF or a cross-encoder to combine them.
  • Pinecone serves full-text, semantic and sparse-vector search from one index.

Hybrid search is not automatically better. It has to beat plain vector search on your own test questions. Crio's vector databases lesson builds product search with filters on a managed database, if you want an e-commerce example.

The same store in ChromaDB, locally

Chroma is an open-source vector database you can run inside a Python program. Below, the same 12 notes go into a real Chroma collection. We pass in the toy embedding from toy_store.py, so the run is repeatable and downloads nothing. Without it, Chroma uses its default model, all-MiniLM-L6-v2, which it downloads on first use.

Setup (in a fresh virtual environment): pip install chromadb==1.5.9, then save toy_store.py from above in the same folder.

# chroma_demo.py: the same 12 chunks in a real, local ChromaDB collection
import chromadb
from chromadb import Documents, EmbeddingFunction, Embeddings
from chromadb.config import Settings
from toy_store import CHUNKS, embed  # reuse the toy embedding from toy_store.py

class ToyEmbedding(EmbeddingFunction):
    """Wraps the toy hashed bag of words so runs are repeatable and nothing is
    downloaded. For a real app, pass a real embedding model here instead."""
    def __init__(self):
        pass

    def __call__(self, input: Documents) -> Embeddings:
        return [embed(text) for text in input]

    @staticmethod
    def name() -> str:
        return "toy-hashed-bow"

    def get_config(self):
        return {}

    @staticmethod
    def build_from_config(config):
        return ToyEmbedding()

client = chromadb.EphemeralClient(Settings(anonymized_telemetry=False))  # in memory
col = client.create_collection(
    "placement_prep",
    embedding_function=ToyEmbedding(),
    configuration={"hnsw": {"space": "cosine"}},  # Chroma's default space is l2
)
col.add(ids=[c[0] for c in CHUNKS],
        documents=[c[2] for c in CHUNKS],
        metadatas=[{"topic": c[1]} for c in CHUNKS])
print(f"chromadb {chromadb.__version__}, {col.count()} chunks stored")

for question, n, where, where_doc in [
    ("how do I make slow database queries faster", 2, None, None),
    ("two pointers on a linked list", 2, None, None),
    ("how do I make slow database queries faster", 1, {"topic": {"$in": ["dsa", "hr"]}}, None),
    ("how do I make slow database queries faster", 1, None, {"$contains": "Redis"}),
]:
    res = col.query(query_texts=[question], n_results=n, where=where, where_document=where_doc)
    print(f"\nQ: {question}")
    if where or where_doc:
        print(f"   where={where}  where_document={where_doc}")
    for id_, dist in zip(res["ids"][0], res["distances"][0]):
        print(f"  distance {dist:.3f} -> cosine {1 - dist:.3f}  {id_}")

Output:

chromadb 1.5.9, 12 chunks stored

Q: how do I make slow database queries faster
  distance 0.859 -> cosine 0.141  sd-3
  distance 0.865 -> cosine 0.135  sd-2

Q: two pointers on a linked list
  distance 0.375 -> cosine 0.625  dsa-1
  distance 0.856 -> cosine 0.144  dsa-3

Q: how do I make slow database queries faster
   where={'topic': {'$in': ['dsa', 'hr']}}  where_document=None
  distance 0.888 -> cosine 0.112  dsa-1

Q: how do I make slow database queries faster
   where=None  where_document={'$contains': 'Redis'}
  distance 0.865 -> cosine 0.135  sd-2

Chroma reports cosine distance, which is 1 minus cosine similarity. So 0.859 means a similarity of 0.141. These are the same scores our plain-Python store gave, in the same order. With only 12 rows, Chroma's HNSW index finds the exact answer.

The two filters show what a real database adds. where filters on metadata, with operators such as $eq, $in and $and. With topics limited to DSA and HR, the best match drops to the linked-list note. where_document filters on the text itself; $contains kept only the note that mentions Redis.

EphemeralClient keeps everything in memory and loses it on exit. For a project, use chromadb.PersistentClient(path="...") to save to disk, or run chroma run and connect over HTTP. In real use, replace ToyEmbedding with a real embedding model, then re-run the "salary" question and check whether it now finds the CTC note.

When you do NOT need a vector database

Plenty of RAG projects never need a separate vector database. Do the arithmetic first. Five thousand chunks with 768 numbers each, stored as float32 (4 bytes per number), take 5,000 × 768 × 4 = 15.36 MB. That fits in memory on any laptop. A flat search over it is one matrix-vector multiply in numpy, and it is exact.

You can probably skip a dedicated vector database when:

  • You have up to a few thousand chunks, and they change rarely. Keep vectors in a numpy array or a file, and search them with brute force.
  • You already run PostgreSQL. Add pgvector. Your vectors sit next to normal rows, with the same backups, joins and access rules. pgvector searches exactly until you add an HNSW or IVFFlat index. Adding one changes results; in the README's words, "you will see different results for queries".
  • You need a library, not a server. FAISS runs inside your own program. You handle storage, updates and metadata yourself.

Move to a dedicated vector database when several of these become true: millions of vectors, many writes per minute, heavy metadata filtering or many tenants. A team that does not want to tune Postgres by hand is another reason. Even then, measure recall on your own questions before and after.

Vector databases compared

Versions below are the latest stable releases on PyPI or GitHub as of 21 November 2026. Licences come from each project's own LICENSE file or docs.

ToolWhat it isLicenceOpen sourceHow you run itLatest version (21 Nov 2026)
ChromaVector databaseApache 2.0YesInside Python (in memory or on disk), client-server, or Chroma Cloudchromadb 1.5.9 (5 May 2026)
QdrantVector database, written in RustApache 2.0YesDocker server, Python client "local mode", or Qdrant Cloudv1.20.2 (16 Nov 2026)
pgvectorPostgreSQL extensionPostgreSQL LicenseYesInside your Postgres 13+ server0.8.7 (1 Oct 2026)
FAISSLibrary, not a databaseMITYesInside your C++ or Python program, in RAMv1.16.0 (10 Nov 2026)
MilvusVector databaseApache 2.0YesMilvus Lite (Python library), Standalone, Distributed, or Zilliz Cloudv3.0.6 (11 Nov 2026)
WeaviateVector databaseBSD 3-Clause core; enterprise features need a commercial keyCore yesDocker, Kubernetes, or Weaviate Cloudv1.40.7 (20 Nov 2026)
PineconeManaged vector databaseProprietary service; Python SDK is Apache 2.0NoManaged cloud only (AWS, GCP, Azure)Python SDK 10.3.0 (3 Nov 2026)
LanceDBEmbedded vector databaseApache 2.0Yes (Embedded)Inside your program; data on local disk or object storagelancedb 0.41.0 (29 Oct 2026)

A few details the table can't hold:

  • Chroma offers in-memory, persistent and client-server modes, plus a hosted Chroma Cloud. It is an easy first vector store to try in Python.
  • Qdrant's Python client has a local mode, QdrantClient(":memory:") or QdrantClient(path=...), which its README says is for "development, prototyping and testing". The same code later talks to a server. Qdrant Cloud has a free tier.
  • pgvector can index vectors of up to 2,000 dimensions with HNSW or IVFFlat (its halfvec type goes to 4,000). Version 0.8.7 fixed a buffer overflow in IVFFlat index builds, so upgrade if you are on an older 0.8.x.
  • FAISS is a toolkit of index types (flat, IVF, HNSW, product quantization and more), with GPU support. Its supported install route is conda; a faiss-cpu wheel is also on PyPI.
  • Milvus is an LF AI & Data Foundation project. Milvus Lite is meant for prototypes and local work; for large production loads its README points to Standalone, Distributed or Zilliz Cloud.
  • Weaviate's repository is mostly BSD 3-Clause. Files in its wl/ folder are under a separate enterprise licence, and those features need a licence key.
  • Pinecone runs as a managed service on AWS, GCP and Azure. Its in-memory emulator, Pinecone Local, reached end of life on 7 October 2026, so there is no local copy to run.
  • LanceDB Embedded runs inside your application's process with no server. LanceDB Enterprise is a separate distributed product.

How to pick, in one line each:

  • Learning or a weekend project: Chroma, LanceDB, or Qdrant's local mode.
  • Already on PostgreSQL: pgvector.
  • You want a search library inside your own service: FAISS.
  • Large self-hosted deployment: Milvus, Qdrant or Weaviate, after testing all three on your data.
  • No time to run servers and a budget to pay: Pinecone, or the managed cloud of an open-source option.

Where vector search breaks

  • Embeddings miss exact strings. Error codes, roll numbers and product SKUs often need keyword search. That is why hybrid search exists.
  • Approximate means approximate. An index can silently drop a true match. Measure recall@k against flat search on a sample, as our IVF program did.
  • Filters can starve results. As the pgvector example showed, a filter after an approximate scan can return far fewer rows than you asked for.
  • Changing the embedding model means re-embedding everything. Vectors from two models cannot be compared. Store the model name with every vector.
  • Memory grows fast. Ten million 768-number vectors are 30.72 GB raw, before any index.
  • Deletes and freshness are your job. If a policy document is removed but its vectors stay, the old policy keeps showing up in answers.
  • Security. Retrieved text goes straight into the prompt. A poisoned document can carry instructions, which is called prompt injection. Treat retrieved chunks as untrusted input. Apply permission filters at retrieval time. Never expose a database server to the internet without authentication. pgvector's README adds that tenants sharing one approximate index can affect each other's recall and speed.

FAQ

Which vector database is best for RAG?

There is no single best one. For learning and prototypes, Chroma or Qdrant's local mode get you running in minutes. If you already use PostgreSQL, pgvector keeps everything in one place. For large self-hosted systems, compare Milvus, Qdrant and Weaviate on your own data. Pinecone suits teams that want a fully managed service.

Is there a free, open-source vector database for RAG?

Yes. Chroma, Qdrant, Milvus and LanceDB are open source under Apache 2.0, and pgvector uses the PostgreSQL License. Weaviate's core is BSD 3-Clause, with some enterprise features under a commercial licence. FAISS is an MIT-licensed library rather than a database. Pinecone is a paid managed service and is not open source.

Can I run a vector database locally?

Yes. Chroma runs inside a Python program, in memory or saved to disk. Qdrant's Python client has a local mode, and Milvus Lite and LanceDB also run in-process. pgvector runs in any local PostgreSQL 13 or newer. Pinecone is the exception: it is cloud only, and its local emulator reached end of life in October 2026.

Is FAISS a vector database?

No. FAISS is a library from Meta for similarity search and clustering of dense vectors. It gives you fast indexes such as flat, IVF and HNSW, and keeps them in RAM. It does not give you a server, persistence, metadata filtering or access control. Many vector databases solve those parts, and some use FAISS-style indexes inside.

How is a vector database different from a normal database?

A normal database finds rows that match exact conditions, like topic equals HR. A vector database finds rows whose embeddings are closest in meaning to a query, using a distance measure. Most real systems need both, which is why vector databases support metadata filters and why PostgreSQL with pgvector is a popular choice.

How does a vector database help when an LLM has no knowledge of my data?

An LLM only knows its training data, and its prompt has limited room. A vector database holds your documents as embeddings. For each question it returns the few most relevant chunks, which go into the prompt. The model then answers from your data, and the system can show which chunks it used.

Keep going

To practise the interview side, with 30 questions and runnable programs for BM25, RRF and similarity, read RAG interview questions and answers. To see where retrieval sits next to tools and agents, read RAG vs MCP vs AI agents. For a bigger project idea, read how to build your own Jarvis by learning LLMs, then the future of AI for software developers.

To build retrieval systems and LLM apps on real projects, with mentors reviewing your work, see Crio's AI Engineering program.

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.