Vector Database
Vector Database
A Vector Database is a database system specifically designed to store, index, and retrieve high-dimensional vector data.
You can think of it as: storing things with similar meanings together, and being able to quickly find the things most similar to this one.
Unlike traditional databases that query using exact matching (WHERE name = 'Alice'), vector databases query using similarity (finding the 10 images most similar to this picture).
An intuitive analogy
Imagine a library scenario:
| Database Types | Retrieval methods | Analogy |
|---|---|---|
| Traditional database | Precise retrieval by ISBN or book title | Find a book with a specific number |
| Vector database | Retrieval by content relevance | Find "all sci-fi novels similar in style to The Three-Body Problem" |
This semantic similarity is the core problem that vector databases solve.
Why do we need a vector database?
Before diving into technical details, let's understand what problem vector databases solve.
Limitations of traditional databases
Traditional relational databases (MySQL, PostgreSQL) are very good at handling structured data, but they struggle with the following requirements:
- Image search (finding visually similar images)
- Semantic search (when a user searches for "Apple phone," they can find content related to "iPhone")
- Recommendation systems (finding "songs with a similar style to the songs you like")
- Anomaly detection (finding the log with the largest difference from normal behavior)
The common characteristic of these problems is: needing to understand the "meaning" of the content, rather than performing literal matching.
Problems with traditional solutions
Original prompt (Chinese, left untranslated)
用 LIKE '%苹果%' 搜索 → 找不到 "iPhone"、"Apple"
用全文索引搜索 → 找不到语义相关但用词不同的内容
Comparison diagram
The chart below intuitively illustrates the fundamental difference in query methods between traditional databases and vector databases.
Core concepts: Vectors and Embeddings
Understanding vectors and embeddings is the first step to mastering vector databases.
What is a Vector
Mathematically, a vector is an ordered set of numbers.
Original prompt (Chinese, left untranslated)
[0.12, -0.54, 0.87, 0.03, ..., 0.61] ← 这就是一个向量
In machine learning, this set of numbers represents the semantic features of an object, with dimensions typically ranging from 128 to 4096.
What is an Embedding?
An Embedding is the process and result of converting real-world objects (text, images, audio, etc.) into vectors.
This conversion is performed by an embedding model, whose core idea is: objects with similar semantics have vectors that are closer in space.
Semantically close means vectors are close.
To understand with a simplified 2D example (the actual dimension is hundreds to thousands):
Key understanding: Two vectors that are close in distance in vector space have original content that is also more semantically similar. This is the foundation of all vector database capabilities.
Similarity Calculation Methods
The core of finding the "most similar vector" is calculating the distance or similarity between two vectors. Here are three of the most commonly used methods.
Cosine Similarity
Cosine similarity measures the angle between the directions of two vectors, ignoring their lengths. This is the most commonly used method, especially suitable for text scenarios.
Formula:
[ \text{CosineSimilarity}(A, B) = \frac{A \cdot B} {|A||B|} = \frac{\sum_{i=1}^{n} A_i B_i} {\sqrt{\sum_{i=1}^{n} A_i^2}\sqrt{\sum_{i=1}^{n} B_i^2}} ]
- Result Range: -1 to 1, the larger the value, the more similar
- Applicable Scenarios: Text semantic search, document similarity
Euclidean Distance
Euclidean distance measures the straight-line distance between two points; the smaller the distance, the more similar they are.
Formula:
[ d(A,B) = \sqrt{\sum_{i=1}^{n}(A_i-B_i)^2} ]
- Result range: 0 to ∞, smaller values indicate greater similarity
- Applicable scenarios: image retrieval, location-related applications
Dot Product
The dot product is the sum of the products of vectors, combining directional and length information.
Formula:
[ A \cdot B = \sum_{i=1}^{n} A_i B_i ]
- Applicable Scenarios: Recommendation systems (equivalent to cosine similarity when vectors are normalized)
Comparison of three methods
Python code example
The following example demonstrates the Python implementation of three similarity calculation methods:
Instance
import
numpy
as
np
Cosine similarity: measures directional similarity
def
cosine_similarity
(
a
,
b
)
:
return
np.
dot
(
a
,
b
)
/
(
np.
linalg
.
norm
(
a
)
- np.
linalg
.
norm
(
b
)
)
Euclidean distance: measures absolute position difference
def
euclidean_distance
(
a
,
b
)
:
return
np.
linalg
.
norm
(
a - b
)
Dot Product: Combining direction and length
def
dot_product
(
a
,
b
)
:
return
np.
dot
(
a
,
b
)
Example vector
v1
=
np.
array
(
[
0.12
,
0.54
,
0.87
,
0.03
]
)
v2
=
np.
array
(
[
0.10
,
0.50
,
0.90
,
0.05
]
)
v3
=
np.
array
(
[
0.80
,
0.20
,
0.30
,
0.70
]
)
(
f
"v1 vs v2 cosine similarity: {cosine_similarity(v1, v2):.4f}"
)
Approximately 0.9997 (very similar)
(
f
"v1 vs v3 cosine similarity: {cosine_similarity(v1, v3):.4f}"
)
Approximately -0.55 (not similar)
Original prompt (Chinese, left untranslated)
v1 vs v2 余弦相似度: 0.9997
v1 vs v3 余弦相似度: -0.5512
Vector indexing algorithm
When the data volume is large (millions, hundreds of millions), calculating similarity for every data point (brute-force search) is too slow. Vector databases use specialized indexing algorithms to accelerate queries.
Brute-force Search (Flat / Brute-force)
Brute-force search iterates over all vectors and calculates similarity one by one.
| Dimension | Description |
|---|---|
| Principle | Iterates over all vectors and calculates similarity one by one |
| Advantages | 100% accurate result |
| Disadvantages | Extremely slow when data volume is large, O(n) complexity |
| Applicable | Data volume is less than 100,000, and high precision is required |
IVF (Inverted File Index)
IVF execution steps:
- Training phase: Use K-Means to cluster all vectors into N clusters and record the center of each cluster
- Query phase: First find the centers of the closest few clusters, then perform precise search only within these clusters
HNSW (Hierarchical Navigable Small World)
HNSW is currently the most mainstream vector indexing algorithm, balancing speed and accuracy.
Core idea of HNSW:
- Construct a multi-layer graph structure, sparse at the top layer and dense at the bottom layer.
- During query, start from the top layer entry point and perform a "jumping game": greedily jump to closer nodes in each layer, then descend to the next layer.
- Significantly reduces the number of nodes that need to be compared, with a time complexity close to O(log n).
Other common indexes
| Index types | Features | Applicable Scenarios |
|---|---|---|
| Flat (Brute Force) | Accurate but slow | Small datasets, accuracy prioritized |
| IVF_Flat | Accurate search after clustering, fast speed | Medium to large scale, ample memory |
| IVF_PQ | Quantization compression, saves memory | Ultra-large scale, memory constrained |
| HNSW | Fast speed, high accuracy, high memory usage | Most commonly used, recommended first choice |
| ScaNN | Offered by Google, optimizes throughput | High Concurrency Production Environment |
Comparison of Popular Vector Databases
Below is a horizontal comparison of the most mainstream vector databases, to help you make a choice in different scenarios.
Beginner's Advice: Start with Chroma or pgvector; the former is suitable for AI application prototypes, and the latter is suitable for projects that already have PostgreSQL.
Quick Start: Python Example
Below, we demonstrate the complete CRUD process using Chroma (easiest to get started with).
Installation
Instance
pip
install
chromadb openai
Complete example: Building a document semantic search system
The following code demonstrates from start to finish how to build a semantic document search system using Chroma.
Example
import
chromadb
from
chromadb.
utils
import
embedding_functions
─── 1. Initialize Client ───────────────────────────────────────────
Persist to local (recommended)
client
=
chromadb.
PersistentClient
(
path
=
"./my_vector_db"
)
Use OpenAI embedding models (or switch to a local model)
openai_ef
=
embedding_functions.
OpenAIEmbeddingFunction
(
api_key
=
"your-openai-api-key"
,
Required: Replace with your API Key
model_name
=
"text-embedding-3-small"
1536 dimensions, high cost-performance ratio
)
─── 2. Create a collection (similar to a "table" in a relational database) ────────────────────────
collection
=
client.
get_or_create_collection
(
name
=
"my_documents"
,
Collection name
embedding_function
=
openai_ef
,
Bind embedding function
metadata
=
{
"hnsw:space"
:
"cosine"
}
Use cosine similarity
)
─── 3. Insert Documents ──────────────────────────────────────────────
documents
=
[
"Python is an object-oriented interpreted programming language widely used in data science and AI development"
,
"Machine learning is a subfield of artificial intelligence that allows computers to learn patterns from data"
,
Deep learning uses multi-layer neural networks and performs excellently in image recognition and NLP tasks.
,
Vector databases are specialized in storing high-dimensional vectors and support semantic similarity search.
,
PostgreSQL is a powerful open-source relational database.
,
"Redis is an in-memory high-performance key-value database, often used for caching"
,
"Docker containerization technology allows applications to run consistently in any environment"
,
Git is a distributed version control system, a fundamental tool for modern software development.
,
]
ids
=
[
f
"doc_{i}"
for
i
in
range
(
len
(
documents
)
)
]
Batch insert (Chroma automatically calls the embedding model to convert to vectors and store)
collection.
add
(
documents
=
documents
,
ids
=
ids
,
metadatas
=
[
{
"source"
:
"tutorial"
,
"index"
: i
}
for
i
in
range
(
len
(
documents
)
)
]
)
(
f
"{len(documents)} documents inserted"
)
Original prompt (Chinese, left untranslated)
已插入 8 条文档
instance
─── 4. Semantic Search ──────────────────────────────────────────────
query
=
"How to do AI with Python"
results
=
collection.
query
(
query_texts
=
[
query
]
,
n_results
=
3
,
Return the 3 most similar
include
=
[
"documents"
,
"distances"
,
"metadatas"
]
)
(
f
"\nQuery: {query}"
)
(
"-"
50
)
for
i
,
(
doc
,
dist
)
in
enumerate
(
zip
(
results
[
"documents"
]
[
0
]
,
results
[
"distances"
]
[
0
]
)
)
:
similarity
=
1
- dist
Cosine distance to similarity
(
f
"Rank {i+1} (Similarity {similarity:.4f}):"
)
(
f
" {doc}"
)
(
)
Original prompt (Chinese, left untranslated)
查询:如何用 Python 做人工智能
--------------------------------------------------
第 1 名(相似度 0.9231):Python 是一种面向对象的解释型编程语言...
第 2 名(相似度 0.8874):机器学习是人工智能的子领域...
第 3 名(相似度 0.8612):深度学习使用多层神经网络...
Instance
─── 5. Search with filtering conditions (metadata filtering)───────────────────────
results_filtered
=
collection.
query
(
query_texts
=
[
"Database Technology"
]
,
n_results
=
2
,
where
=
{
"source"
:
"tutorial"
}
,
Search only in documents where source=tutorial
include
=
[
"documents"
,
"distances"
]
)
─── 6. Update Documentation ──────────────────────────────────────────────
collection.
update
(
ids
=
[
"doc_0"
]
,
documents
=
[
"Python is currently the most popular programming language, widely used in AI, data analysis, and web development"
]
,
metadatas
=
[
{
"source"
:
"tutorial"
,
"index"
:
0
,
"updated"
:
True
}
]
)
─── 7. Delete Document ──────────────────────────────────────────────
collection.
delete
(
ids
=
[
"doc_7"
]
)
Delete Git related documentation
─── 8. View collection statistics ──────────────────────────────────────────
(
f
"Current number of documents in collection: {collection.count()}"
)
Do not use third-party embedding APIs (purely local)
If you do not want to use the OpenAI API, you can run a local embedding model completely offline.
Example
import
chromadb
from
sentence_transformers
import
SentenceTransformer
Use local embedding model (no API Key required, completely offline)
model
=
SentenceTransformer
(
"paraphrase-multilingual-MiniLM-L12-v2"
)
Supports Chinese
client
=
chromadb.
Client
(
)
collection
=
client.
create_collection
(
"local_demo"
)
texts
=
[
"The weather is very nice today"
,
"Sunny, suitable for going out"
,
"The stock market rose sharply"
,
"It might rain tomorrow"
]
Insert after manual vector generation
embeddings
=
model.
encode
(
texts
)
.
tolist
(
)
collection.
add
(
embeddings
=
embeddings
,
documents
=
texts
,
ids
=
[
f
"id_{i}"
for
i
in
range
(
len
(
texts
)
)
]
)
Query
query_embedding
=
model.
encode
(
[
"How is the weather today"
]
)
.
tolist
(
)
results
=
collection.
query
(
query_embeddings
=
query_embedding
,
n_results
=
2
)
(
results
[
"documents"
]
)
Output: [['The weather is great today', 'Sunny, suitable for going out']]
pgvector example (PostgreSQL users)
If your project is already using PostgreSQL, pgvector is the lightest way to integrate.
Instance
-- Install extension
CREATE
EXTENSION
IF
NOT
EXISTS
vector;
-- Create table: store article titles and their vectors (1536 dimensions)
CREATE
TABLE
articles
(
id SERIAL
PRIMARY
KEY
,
title TEXT
NOT
NULL
,
content TEXT
,
embedding vector
(
1536
)
-- Vector column, 1536 dimensions
)
;
-- Create HNSW index to accelerate queries
CREATE
INDEX
ON
articles
USING
hnsw
(
embedding vector_cosine_ops
)
WITH
(
m
=
16
,
ef_construction
=
64
)
;
-- Insert data (vectors are passed in after being generated by the application layer)
INSERT
INTO
articles
(
title
,
embedding
)
VALUES
(
'Python Beginner's Guide'
,
'[0.12, -0.54, 0.87, ...]'
::vector
)
;
-- Semantic search: find the 5 most similar articles
SELECT
id
,
title
,
1
(
embedding
<=>
'[0.10, -0.50, 0.90, ...]'
::vector
)
AS
similarity
FROM
articles
ORDER
BY
embedding
<=>
'[0.10, -0.50, 0.90, ...]'
::vector
LIMIT
5
;
Note: <=> is the vector distance operator provided by pgvector, used to calculate cosine distance. Subtracting the cosine distance from 1 yields the cosine similarity.
Typical Application Scenarios
Vector databases have a very wide range of applications in the AI era. Here is an overview of the six most typical scenarios.
RAG (Retrieval-Augmented Generation) Architecture
RAG is one of the most major application scenarios for vector databases. The core workflow is as follows:
Selection Recommendations and Best Practices
Selection Decision Tree
Based on your specific situation, choose the appropriate vector database according to the following decision tree:
Original prompt (Chinese, left untranslated)
你的情况是什么?
│
├─── 已有 PostgreSQL,且数据量 < 500 万
│ └──> 用 pgvector,无缝集成,零额外运维
│
├─── 做 AI/LLM 应用原型,快速验证
│ └──> 用 Chroma,几行代码跑起来
│
├─── 需要生产级部署,性能优先,数据量 500 万 ~ 1 亿
│ └──> 用 Qdrant,Rust 实现,性能强
│
├─── 超大规模(> 1 亿),有 K8s 运维能力
│ └──> 用 Milvus,分布式,功能最全
│
└─── 团队没有运维能力,愿意付费
└──> 用 Pinecone 云服务,开箱即用
Embedding Model Selection
Choosing the appropriate embedding model is the crucial first step for vector database applications.
| Requirements | Recommended Models |
|---|---|
| Chinese and English text (high quality) | OpenAI text-embedding-3-small |
| Chinese text (local offline) | BAAI/bge-large-zh-v1.5 |
| Multilingual general | paraphrase-multilingual-MiniLM-L12-v2 |
| Multimodal text and image | OpenAI CLIP series |
Performance optimization tips
- Batch insertion: insert multiple records at once to avoid frequent single-record writes.
Example
Recommendation: Batch insertion
collection.
add
(
documents
=
docs_list
,
ids
=
ids_list
)
Not recommended: looping single items (re-indexing every time, extremely low efficiency)
for doc, id in zip(docs_list, ids_list):
collection.add(documents=[doc], ids=[id])
- Vector normalization: Pre-normalizing vectors before using cosine similarity can speed up computation.
Instance
import
numpy
as
np
def
normalize
(
v
)
:
"""L2 normalize the vector to make its norm 1"""
return
v / np.
linalg
.
norm
(
v
)
-
Set n_results reasonably: do not set a very large top_k blindly; generally, 3-10 items are enough for RAG scenarios.
-
Make good use of metadata filtering: use where conditions during search to narrow the search scope.
Instance
Search only in the "Technical Documentation" category to narrow the scope and improve accuracy.
collection.
query
(
query_texts
=
[
"Python exception handling"
]
,
where
=
{
"category"
:
"tech_doc"
}
,
n_results
=
5
)
- Periodically rebuild the index: Rebuild the HNSW index when the data volume increases to maintain query performance.
Common pitfalls
The following are the most common issues and solutions encountered by beginners when using a vector database.
| Issue | Description | Solution |
|---|---|---|
| Embedded models must be unified | Insertion and querying must use the same model | Fix the model version in the configuration file |
| Dimension mismatch | Switched models but did not rebuild the collection | Delete and rebuild the collection when changing models |
| Text is too long | Most models have token limits (512~8192) | Chunk long text first |
| Similarity is inaccurate | Text is not chunked, semantics are diluted | Split documents by paragraph or fixed length |
| Slow cold start | Index loading time when data volume is large | Pre-warm or use persistent index |
Summary
Let's review the core knowledge points of this tutorial:
Vector databases are an important part of the infrastructure in the AI era.
It solves the semantic similarity search problem that traditional databases cannot handle, and is a core component for building RAG systems, recommendation systems, and multimodal search.
Suggested learning path
- Step 1: Understand the concepts of vectors and embeddings, and run the Chroma example in this article
- Step 2: Try to build a simple document Q&A system using LangChain + Chroma
- Step 3: Learn indexing algorithms like HNSW and understand the trade-off between accuracy and speed
- Step 4: Select a suitable vector database based on actual project requirements and deploy it in a production environment