Vector database
Vector database
In the age of AI, the form of data we process has fundamentally changed.
Traditional databases store structured data: numbers, strings, dates.
AI applications process semantics: the meaning of a piece of text, the content of an image, the meaning of a piece of speech; this semantic information is represented as vectors—a sequence of floating-point numbers, such as [0.123, -0.456, 0.789, ...].
A vector database is a database specifically designed to store, index, and query these vectors; without it, RAG (Retrieval-Augmented Generation) cannot be done, semantic search cannot be implemented, and recommendation systems cannot run efficiently.

The core value of a vector database is:Finding the top K results most similar to the query vector in millions or even billions of vectors in milliseconds.
Challenges of vector similarity search
Only by understanding the essence of the problem can we understand why specialized algorithms are needed.
Complexity issue of brute-force search
The simplest approach is brute-force search: calculate the similarity between the query vector and every vector in the library, then sort and take the top K.
Example
============================================
Brute-force search demonstration: simple but inefficient
============================================
import
numpy
as
np
from
typing
import
List
,
Tuple
def
l2_distance
(
v1: np.
ndarray
,
v2: np.
ndarray
)
float
:
"""Calculates the L2 Euclidean distance: smaller is more similar"""
return
np.
sqrt
(
np.
sum
(
(
v1 - v2
)
**
2
)
)
def
brute_force_search
(
query: np.
ndarray
,
vectors: List
[
np.
ndarray
]
,
top_k:
int
=
5
)
List
[
Tuple
[
int
,
float
]
]
:
"""
Brute-force search: calculate the distance to all vectors, sort, and return the Top K
Advantages: simple and accurate, 100% recall
Disadvantages: extremely slow with large amounts of data
"""
Calculate the distance to each vector
distances
=
[
]
for
idx
,
vec
in
enumerate
(
vectors
)
:
dist
=
l2_distance
(
query
,
vec
)
distances.
append
(
(
idx
,
dist
)
)
Sort by distance, take the top K
distances.
sort
(
key
=
lambda
x: x
[
1
]
)
return
distances
[
:top_k
]
Generate 10000 random 128-dimensional vectors (simulated vector database)
np.
random
.
seed
(
42
)
vector_count
=
10000
dimension
=
128
vectors
=
[
np.
random
.
randn
(
dimension
)
for
_
in
range
(
vector_count
)
]
Generate a query vector
query_vector
=
np.
random
.
randn
(
dimension
)
Execute brute-force search
(
f
"Searching Top 5 among {vector_count} vectors..."
)
results
=
brute_force_search
(
query_vector
,
vectors
,
top_k
=
5
)
(
"Search results:"
)
for
idx
,
dist
in
results:
(
f
" Vector {idx:4d}, distance = {dist:.4f}"
)
Output similar to:
Searching Top 5 among 10000 vectors...
Search results:
Vector 8236, distance = 13.3986
Vector 8946, distance = 13.5604
Vector 9891, distance = 13.5688
Vector 5172, distance = 13.5987
Vector 5223, distance = 13.6081
The problem with brute-force search is obvious: every query requires traversing all vectors.
If there are 1 million vectors, each query requires 1 million distance calculations.
If there are 1 billion vectors, each query requires 1 billion calculations—which is completely unacceptable in a production environment.
The "curse of dimensionality" in high-dimensional spaces
To make matters worse, vectors are usually high-dimensional.
OpenAI's text-embedding-3-small is 1536 dimensions, and large is 3072 dimensions.
In high-dimensional spaces, traditional spatial indexing methods (like KD-Tree) suffer a sharp decline in efficiency, even becoming slower than brute-force search.
| Data scale | Brute-force search time (estimate) | Acceptable? |
|---|---|---|
| 10k | ~1 ms | Acceptable |
| 1M | ~100 ms | A bit slow |
| 10 million | ~1 second | Too slow |
| 100 million | ~10 seconds | Completely unacceptable |
| 1 billion | ~100 seconds | Unavailable |
This is why Approximate Nearest Neighbor (ANN) algorithms are needed: sacrificing 100% accuracy for a 100x or even 1000x speedup.
Approximate Nearest Neighbor (ANN) algorithms
The core idea of ANN algorithms is to build an index structure so that all vectors do not need to be traversed during a query.
There are three mainstream algorithms: HNSW, IVF, and PQ.
HNSW: Hierarchical Navigable Small World
HNSW (Hierarchical Navigable Small World) is one of the most popular algorithms currently, inspired by the six degrees of separation theory—that any two people in the world can be connected through at most 6 intermediaries.
HNSW uses a multi-layer sparse small-world graph to quickly coarse-locate from sparse nodes at the top layer, and then perform fine-grained search down to the full data layer at the bottom layer. By using hierarchical jumps, it significantly reduces the number of distance calculations, achieving fast approximate nearest neighbor retrieval with high recall.

**Hierarchical Structure:** The bottom layer, Layer0, stores all vectors; the higher the layer, the fewer the nodes, which act as high-speed channels. The same vector is vertically associated across layers with a dashed line.
Retrieval Process (Blue Line Path):
- Coarse search at the top layer entrance to find the closest point to the query vector in this layer.
- Vertically descend to the middle layer for another coarse localization.
- Fine-grained traversal in the Layer0 full layer to output the nearest neighbors.
**Core Principle:** High layers quickly narrow down the search range, while the bottom layer performs precise matching, optimizing brute-force search to logarithmic complexity, resulting in fast speed and high recall, making it a mainstream vector retrieval algorithm.
Example
============================================
Simplified demonstration of HNSW principles (non-production implementation)
============================================
import
numpy
as
np
import
random
from
typing
import
List
,
Dict
,
Set
,
Tuple
class
SimpleHNSW:
"""Simplified HNSW, used only for demonstration"""
def
init
(
self
,
dim:
int
,
max_level:
int
=
3
,
ef_construction:
int
=
5
)
:
self
.
dim
=
dim
self
.
max_level
=
max_level
Maximum number of layers
self
.
ef_construction
=
ef_construction
Number of candidates considered during map construction
self
.
levels
: List
[
Dict
[
int
,
np.
ndarray
]
]
=
[
{
}
for
_
in
range
(
max_level
)
]
self
.
edges
: List
[
Dict
[
int
,
Set
[
int
]
]
]
=
[
{
}
for
_
in
range
(
max_level
)
]
self
.
next_id
=
0
self
.
enter_point
=
None
Entry point (a point on the top layer)
def
_random_level
(
self
)
int
:
"""Randomly select a level: the higher the probability, the smaller the chance"""
level
=
0
while
random
.
random
(
)
<
0.5
and
level
<
self.
max_level
1
:
level +
=
1
return
level
def
_distance
(
self
,
v1: np.
ndarray
,
v2: np.
ndarray
)
float
:
"L2 distance"
return
np.
sqrt
(
np.
sum
(
(
v1 - v2
)
**
2
)
)
def
_search_layer
(
self
,
query: np.
ndarray
,
level:
int
,
entry:
int
,
ef:
int
)
List
[
Tuple
[
float
,
int
]
]
:
"""Search in a layer: greedily find ef nearest points starting from entry"""
if
entry
not
in
self
.
levels
[
level
]
:
return
[
]
visited
=
set
(
[
entry
]
)
candidates
=
[
(
self
._distance
(
query
,
self
.
levels
[
level
]
[
entry
]
)
,
entry
)
]
result
=
list
(
candidates
)
while
candidates:
Take out the current nearest candidate
candidates.
sort
(
)
dist
,
current
=
candidates.
pop
(
0
)
Traverse neighbors
if
current
not
in
self
.
edges
[
level
]
:
continue
for
neighbor
in
self
.
edges
[
level
]
[
current
]
:
if
neighbor
in
visited:
continue
visited.
add
(
neighbor
)
neighbor_dist
=
self
._distance
(
query
,
self
.
levels
[
level
]
[
neighbor
]
)
Add to candidate and result set
candidates.
append
(
(
neighbor_dist
,
neighbor
)
)
result.
append
(
(
neighbor_dist
,
neighbor
)
)
Keep the result set size no more than ef
result.
sort
(
)
result
=
result
[
:ef
]
return
result
def
add
(
self
,
vector: np.
ndarray
)
int
:
"""Add a vector"""
vec_id
=
self
.
next_id
self
.
next_id
=
1
Randomly determine which layers this vector appears in
max_level_for_vec
=
self
._random_level
(
)
Store vectors in all layers (in actual implementation, only the full vector is usually stored in the bottom layer)
for
level
in
range
(
max_level_for_vec +
1
)
:
self
.
levels
[
level
]
[
vec_id
]
=
vector
self
.
edges
[
level
]
[
vec_id
]
=
set
(
)
If it is the first point, set it as the entry point
if
self
.
enter_point
is
None
:
self
.
enter_point
=
vec_id
return
vec_id
Search from the top down to find the insertion position of each layer
current_entry
=
self
.
enter_point
First search in layers higher than max_level_for_vec and update the entry point
for
level
in
range
(
self
.
max_level
1
,
max_level_for_vec
,
1
)
:
if
current_entry
in
self
.
levels
[
level
]
:
layer_result
=
self
._search_layer
(
vector
,
level
,
current_entry
,
1
)
if
layer_result:
current_entry
=
layer_result
[
0
]
[
1
]
Establish connection at max_level_for_vec and lower levels
for
level
in
range
(
max_level_for_vec
,
1
,
1
)
:
Search for the nearest ef_construction points in this layer
layer_result
=
self
._search_layer
(
vector
,
level
,
current_entry
,
self
.
ef_construction
)
Connect to these points (simplified: bidirectional connection)
for
dist
,
neighbor_id
in
layer_result:
self
.
edges
[
level
]
[
vec_id
]
.
add
(
neighbor_id
)
self
.
edges
[
level
]
[
neighbor_id
]
.
add
(
vec_id
)
Entry for the next layer
if
layer_result:
current_entry
=
layer_result
[
0
]
[
1
]
Update top-level entry
if
max_level_for_vec
self
._random_level
(
)
:
Simplified judgment
self
.
enter_point
=
vec_id
return
vec_id
def
search
(
self
,
query: np.
ndarray
,
top_k:
int
=
5
,
ef:
int
=
10
)
List
[
Tuple
[
int
,
float
]
]
:
"Search Top K nearest neighbors"
if
self
.
enter_point
is
None
:
return
[
]
current_entry
=
self
.
enter_point
From the top layer down to the first layer
for
level
in
range
(
self
.
max_level
1
,
0
,
1
)
:
if
current_entry
in
self
.
levels
[
level
]
:
layer_result
=
self
._search_layer
(
query
,
level
,
current_entry
,
1
)
if
layer_result:
current_entry
=
layer_result
[
0
]
[
1
]
Search for ef points at the bottom layer, then return Top K
layer_result
=
self
._search_layer
(
query
,
0
,
current_entry
,
ef
)
layer_result.
sort
(
)
return
[
(
vec_id
,
dist
)
for
dist
,
vec_id
in
layer_result
[
:top_k
]
]
Test
np.
random
.
seed
(
42
)
dim
=
128
hnsw
=
SimpleHNSW
(
dim
=
dim
,
max_level
=
3
,
ef_construction
=
5
)
Add 100 vectors
(
"Building HNSW index (adding 100 vectors)..."
)
for
i
in
range
(
100
)
:
vec
=
np.
random
.
randn
(
dim
)
hnsw.
add
(
vec
)
(
f
"Index construction complete, entry point = {hnsw.enter_point}"
)
Generate query vector
query
=
np.
random
.
randn
(
dim
)
Search
(
"\nExecuting HNSW search..."
)
results
=
hnsw.
search
(
query
,
top_k
=
5
,
ef
=
10
)
(
"Search results:"
)
for
vec_id
,
dist
in
results:
(
f
" Vector {{vec_id:3d}}, distance = {{dist:.4f}}"
)
Output similar to:
Building HNSW index (adding 100 vectors)...
Index building complete, entry point = 54
Executing HNSW search...
Search results:
Vector 86, distance = 13.7515
Vector 30, distance = 13.8651
Vector 28, distance = 14.0754
Vector 56, distance = 14.1106
Vector 34, distance = 14.2131
Advantages of HNSW:
-
1.Fast query: Usually only a few nodes need to be visited to find the nearest neighbor.
-
2.Fast construction: Vectors can be added incrementally without rebuilding the entire index.
-
3.Simple parameters: Mainly adjust ef_construction (map construction quality) and ef (search quality).
IVF: Inverted File Index
The idea of IVF (Inverted File) is "divide and conquer".
Steps:
-
1.Clustering: Divide the vector space into K "buckets" (using K-Means clustering).
-
2.Index: Each vector is assigned to the nearest bucket.
-
3.Query: First find the N nearest buckets to the query vector, and search only within these N buckets.
Example
============================================
Simplified demonstration of IVF principle
============================================
import
numpy
as
np
from
typing
import
List
,
Tuple
class
SimpleIVF:
"""Simplified IVF, used only to demonstrate the principle"""
def
init
(
self
,
dim:
int
,
nlist:
int
=
10
)
:
self
.
dim
=
dim
self
.
nlist
=
nlist
Number of cluster centers (number of buckets)
self
.
centroids
: np.
ndarray
=
None
Cluster center
self
.
inverted_lists
: List
[
List
[
Tuple
[
int
,
np.
ndarray
]
]
]
=
[
[
]
for
_
in
range
(
nlist
)
]
self
.
next_id
=
0
def
_l2_distance
(
self
,
v1: np.
ndarray
,
v2: np.
ndarray
)
float
:
"L2 distance"
return
np.
sqrt
(
np.
sum
(
(
v1 - v2
)
**
2
)
)
def
_find_nearest_centroid
(
self
,
vector: np.
ndarray
)
int
:
"""Find the nearest cluster center"""
distances
=
[
self
._l2_distance
(
vector
,
c
)
for
c
in
self
.
centroids
]
return
int
(
np.
argmin
(
distances
)
)
def
fit
(
self
,
vectors: List
[
np.
ndarray
]
)
:
"""Initialize cluster centers using K-Means (simplified version: random selection)"""
Simplified: randomly select nlist vectors as initial centers
In actual implementation, K-Means iteration should be used
indices
=
np.
random
.
choice
(
len
(
vectors
)
,
self
.
nlist
,
replace
=
False
)
self
.
centroids
=
np.
array
(
[
vectors
[
i
]
for
i
in
indices
]
)
def
add
(
self
,
vector: np.
ndarray
)
int
:
"""Add vector"""
vec_id
=
self
.
next_id
self
.
next_id
=
1
Find the nearest bucket
centroid_idx
=
self
._find_nearest_centroid
(
vector
)
put into this bucket
self
.
inverted_lists
[
centroid_idx
]
.
append
(
(
vec_id
,
vector
)
)
return
vec_id
def
search
(
self
,
query: np.
ndarray
,
top_k:
int
=
5
,
nprobe:
int
=
3
)
List
[
Tuple
[
int
,
float
]
]
:
"""
Search Top K
nprobe: How many buckets to search (more is more accurate, but slower)
"""
Find the nearest nprobe buckets
centroid_distances
=
[
(
self
._l2_distance
(
query
,
c
)
,
i
)
for
i
,
c
in
enumerate
(
self
.
centroids
)
]
centroid_distances.
sort
(
)
nearest_centroids
=
[
i
for
dist
,
i
in
centroid_distances
[
:nprobe
]
]
Search only in these nprobe buckets
candidates
=
[
]
for
centroid_idx
in
nearest_centroids:
for
vec_id
,
vec
in
self
.
inverted_lists
[
centroid_idx
]
:
dist
=
self
._l2_distance
(
query
,
vec
)
candidates.
append
(
(
dist
,
vec_id
)
)
Sort and return Top K
candidates.
sort
(
)
return
[
(
vec_id
,
dist
)
for
dist
,
vec_id
in
candidates
[
:top_k
]
]
Test
np.
random
.
seed
(
42
)
dim
=
128
Generate 1000 vectors
vectors
=
[
np.
random
.
randn
(
dim
)
for
_
in
range
(
1000
)
]
Build IVF index
ivf
=
SimpleIVF
(
dim
=
dim
,
nlist
=
20
)
ivf.
fit
(
vectors
)
Add vector
for
vec
in
vectors:
ivf.
add
(
vec
)
(
f
"IVF index construction completed, number of buckets = {ivf.nlist}"
)
for
i
in
range
(
ivf.
nlist
)
:
(
f
" Bucket {i:2d}: {len(ivf.inverted_lists[i])} vectors"
)
Query
query
=
np.
random
.
randn
(
dim
)
(
"\nExecuting IVF search (nprobe=3)..."
)
results
=
ivf.
search
(
query
,
top_k
=
5
,
nprobe
=
3
)
(
"Search results:"
)
for
vec_id
,
dist
in
results:
(
f
" vector {vec_id:3d}, distance = {dist:.4f}"
)
Output similar to:
IVF index construction complete, number of buckets = 20
Bucket 0: 63 vectors
Bucket 1: 56 vectors
...
Executing IVF search (nprobe=3)...
Search results:
Vector 863, distance = 13.5409
Vector 189, distance = 13.7083
Vector 491, distance = 13.8628
Vector 264, distance = 13.9812
Vector 781, distance = 14.0021
The advantage of IVF is small memory consumption, and the nprobe parameter can be dynamically adjusted during query to balance speed and accuracy.
PQ: Product Quantization
PQ (Product Quantization) is a compression algorithm.
Core idea:
-
1.Chunking: Splitting high-dimensional vectors into multiple small segments (subvectors).
-
2.Quantization: Clustering each small segment individually and replacing the original vector with the ID of the cluster center.
-
3.LookupUse the table lookup method for fast approximate distance calculation during query.
For example, a 128-dimensional vector is divided into 8 segments, each 16-dimensional, and each segment uses 256 centroids for quantization, resulting in each vector only needing 8 bytes of storage (originally 128 * 4 = 512 bytes).
IVF-PQ combination
In production environments, IVF and PQ are usually combined and used:
IVF is responsible for "bucketing" to reduce the search range, and PQ is responsible for "compression" to reduce memory and computation.
| Algorithm | Speed | Accuracy | Memory | Applicable scenarios |
|---|---|---|---|---|
| Brute-force search | Slow | 100% | High | Small data volume, requires 100% accuracy |
| HNSW | Extremely fast | High | Medium | Query-intensive, requires low latency |
| IVF | Fast | Medium | Low | Large-scale data, acceptable small precision loss |
| IVF-PQ | Fast | Medium | Extremely low | Ultra-large-scale data, memory constrained |
Similarity metric
There are various ways to calculate "similarity," and choosing the correct metric is important.
Cosine Similarity
Cosine similarity measures the angle between the directions of two vectors, with a value range of [-1, 1].
The closer the value is to 1, the more similar they are; the closer it is to -1, the more opposite they are.
Example
============================================
Cosine Similarity Calculation
============================================
import
numpy
as
np
def
cosine_similarity
(
v1: np.
ndarray
,
v2: np.
ndarray
)
float
:
"""
Cosine similarity = (v1 · v2) / (|v1| * |v2|)
The value range is [-1, 1], and closer to 1 means more similar.
"""
dot_product
=
np.
dot
(
v1
,
v2
)
norm1
=
np.
linalg
.
norm
(
v1
)
norm2
=
np.
linalg
.
norm
(
v2
)
return
dot_product /
(
norm1 * norm2
)
Test
np.
random
.
seed
(
42
)
v1
=
np.
array
(
[
1
,
2
,
3
,
4
,
5
]
)
v2
=
np.
array
(
[
2
,
4
,
6
,
8
,
10
]
)
Same direction
v3
=
np.
array
(
[
1
,
2
,
3
,
4
,
5
]
)
opposite direction
v4
=
np.
random
.
randn
(
5
)
random
(
f
"v1 = {v1}"
)
(
f
"v2 = {v2}"
)
(
f
"v3 = {v3}"
)
(
f
"v4 = {v4}"
)
(
)
(
f
"cosine(v1, v2) = {cosine_similarity(v1, v2):.4f} (same direction, should be 1.0)"
)
(
f
"cosine(v1, v3) = {cosine_similarity(v1, v3):.4f} (opposite direction, should be -1.0)"
)
(
f
"cosine(v1, v4) = {cosine_similarity(v1, v4):.4f}"
)
Output:
v1 = [1 2 3 4 5]
v2 = [ 2 4 6 8 10]
v3 = [-1 -2 -3 -4 -5]
v4 = [ 0.4967 -0.1383 0.6477 1.5230 -0.2342]
cosine(v1, v2) = 1.0000 (Same direction, should be 1.0)
cosine(v1, v3) = -1.0000 (Opposite direction, should be -1.0)
cosine(v1, v4) = 0.2143
Characteristics of cosine similarity: it does not care about the length of the vectors, only the direction. This is commonly used in text embeddings because the "semantics" of text are independent of length.
L2 Euclidean Distance
L2 distance is the straight-line distance between two points in space; smaller is more similar.
Inner Product (Dot Product)
Dot product = v1 · v2. If both vectors are normalized, the dot product equals cosine similarity.
Selection guide
| Metric | Value range | When to choose | Typical use cases |
|---|---|---|---|
| Cosine similarity | [-1, 1] | Only cares about direction, not length | Text embedding, semantic search |
| L2 distance | [0, ∞) | Spatial position is important | Image features, recommendation systems |
| Dot product | (-∞, ∞) | The vectors are normalized, or the length is meaningful | Certain specific embedding models |
Vectors output by most embedding models (such as OpenAI's text-embedding series) are normalized, soCosine similarity = dot product, it doesn't matter which one you use.
Comparison of mainstream vector databases
Vector databases are divided into three categories: local libraries (FAISS), lightweight open-source (Chroma, Qdrant), and enterprise-grade (Milvus, Pinecone, Weaviate).
FAISS: A local library released by Facebook
FAISS is not a complete database, but a C++ library (with Python bindings).
Instance
============================================
Basic FAISS Usage Demonstration
============================================
import
numpy
as
np
Note: FAISS must be installed before actual execution
pip install faiss-cpu (CPU version)
or
pip install faiss-gpu (GPU version)
Below is a typical usage of FAISS (code example, not actually executed)
def
faiss_example
(
)
:
"FAISS Usage Example"
1. Prepare data
dimension
=
128
nb
=
10000
Database vector count
nq
=
10
Query vector count
np.
random
.
seed
(
42
)
xb
=
np.
random
.
random
(
(
nb
,
dimension
)
)
.
astype
(
'float32'
)
Database
xq
=
np.
random
.
random
(
(
nq
,
dimension
)
)
.
astype
(
'float32'
)
Query
2. Create Index (IVF Example)
import
faiss
nlist
=
100
Number of cluster centers
quantizer
=
faiss.
IndexFlatL2
(
dimension
)
Quantizer
index
=
faiss.
IndexIVFFlat
(
quantizer
,
dimension
,
nlist
,
faiss.
METRIC_L2
)
3. Training Index
index.
train
(
xb
)
4. Add vector
index.
add
(
xb
)
5. Set nprobe when searching
index.
nprobe
=
10
6. Search Top 5
k
=
5
distances
,
indices
=
index.
search
(
xq
,
k
)
(
"Query results (Top 5 of the first 2 queries):"
)
for
i
in
range
(
min
(
2
,
nq
)
)
:
(
f
"Querying {i}:"
)
for
j
in
range
(
k
)
:
(
f
" Index {indices[i][j]}, Distance {distances[i][j]:.4f}"
)
return
index
HNSW index example
def
faiss_hnsw_example
(
)
:
"""FAISS HNSW Index"""
import
faiss
dimension
=
128
index
=
faiss.
IndexHNSWFlat
(
dimension
,
32
)
32 = M parameter (number of connections per node)
index.
hnsw
.
efConstruction
=
40
ef during map construction
index.
hnsw
.
efSearch
=
16
ef during search
Adding data...
index.add(xb)
return
index
If FAISS is installed, uncomment the following line to run
faiss_example()
(
"FAISS example code: This is a typical use case for FAISS."
)
(
"Key steps: Create index → Train → Add vector → Search."
)
(
)
(
"FAISS common index types:"
)
(
" - IndexFlatL2: brute-force search (accurate but slow)"
)
(
" - IndexIVFFlat: IVF bucket search"
)
(
" - IndexIVFPQ: IVF + PQ compression"
)
(
" - IndexHNSWFlat: HNSW graph index"
)
Features of FAISS:
-
1.Extremely fast: C++ implementation, optimized to the extreme.
-
2.Full functionality: Supports almost all mainstream ANN algorithms.
-
3.Local: No network, no persistence (you need to save the index file yourself).
Applicable scenarios: offline batch processing, do not want to set up services, data volume is not particularly large.
Chroma: Lightweight, local-first
Chroma is a simple and easy-to-use vector database, designed with the goal of "making AI application development faster."
Instance
============================================
Chroma Basic Usage Demonstration
============================================
Installation: pip install chromadb
def
chroma_example
(
)
:
"""Chroma usage example"""
import
chromadb
from
chromadb.
utils
import
embedding_functions
1. Initialize client (local mode, data saved to disk)
client
=
chromadb.
PersistentClient
(
path
=
"./runoob-chroma-db"
)
2. Create or get a collection
collection
=
client.
get_or_create_collection
(
name
=
"runoob_docs"
,
metadata
=
{
"description"
:
"Beginner Tutorial Document Collection"
}
)
3. Add documents (Chroma will automatically handle embedding)
Can use OpenAI, Cohere, etc., or provide your own vectors
documents
=
[
"Python is an interpreted, high-level, general-purpose programming language."
,
"JavaScript is a lightweight, interpreted programming language."
,
"Vector databases are used to store and retrieve vector embeddings."
,
"RAG stands for Retrieval-Augmented Generation, a technology that combines retrieval and generation."
,
HNSW is an approximate nearest neighbor algorithm based on a hierarchical small-world graph.
]
metadatas
=
[
{
"category"
:
"programming"
,
"language"
:
"Python"
}
,
{
"category"
:
"programming"
,
"language"
:
"JavaScript"
}
,
{
"category"
:
"database"
,
"topic"
:
"vector"
}
,
{
"category"
:
"ai"
,
"topic"
:
"rag"
}
,
{
"category"
:
"algorithm"
,
"topic"
:
"hnsw"
}
]
ids
=
[
"doc1"
,
"doc2"
,
"doc3"
,
"doc4"
,
"doc5"
]
Add (using simulated vectors here, should use an embedding model in practice)
import
numpy
as
np
np.
random
.
seed
(
42
)
embeddings
=
[
np.
random
.
randn
(
128
)
.
tolist
(
)
for
_
in
range
(
5
)
]
collection.
add
(
documents
=
documents
,
metadatas
=
metadatas
,
ids
=
ids
,
embeddings
=
embeddings
If not provided, Chroma will use the default embed function
)
(
f
"The collection has a total of {collection.count()} documents"
)
4. Query
query_embedding
=
np.
random
.
randn
(
128
)
.
tolist
(
)
results
=
collection.
query
(
query_embeddings
=
[
query_embedding
]
,
n_results
=
3
,
Metadata filtering can be added
where={"category": "ai"}
)
(
"\nQuery results:"
)
for
i
in
range
(
len
(
results
[
'ids'
]
[
0
]
)
)
:
(
f
"ID: {results['ids'][0][i]}"
)
(
f
"Document: {results['documents'][0][i]}"
)
(
f
"Distance: {results['distances'][0][i]:.4f}"
)
(
"---"
)
return
collection
If Chroma is installed, uncomment the following to run
chroma_example()
(
"Chroma example code: simple design, ready to use."
)
(
)
(
"Chroma features:"
)
(
" - Simple: API friendly, ready to use in minutes"
)
(
" - Local first: can be persisted to disk or run in memory"
)
(
" - Built-in embedding: supports OpenAI, Cohere, Sentence-Transformers"
)
(
" - Supports metadata filtering: metadata can be filtered during query"
)
Qdrant: Production-grade open source
Qdrant is a vector database written in Rust, with good performance and full functionality.
Instance
============================================
Qdrant Basic Usage Demonstration
============================================
Install: pip install qdrant-client
Start service: docker run -p 6333:6333 qdrant/qdrant
def
qdrant_example
(
)
:
"""Qdrant usage example"""
from
qdrant_client
import
QdrantClient
from
qdrant_client.
models
import
Distance
,
VectorParams
,
PointStruct
,
Filter
,
FieldCondition
,
MatchValue
1. Connect the client
client
=
QdrantClient
(
host
=
"localhost"
,
port
=
6333
)
2. Create collection
client.
recreate_collection
(
collection_name
=
"runoob_collection"
,
vectors_config
=
VectorParams
(
size
=
128
,
distance
=
Distance.
COSINE
or L2, DOT
)
,
Optional: Configure HNSW index parameters
hnsw_config=HnswConfig(m=16, ef_construct=100)
)
3. Add point
import
numpy
as
np
np.
random
.
seed
(
42
)
points
=
[
PointStruct
(
id
=
i
,
vector
=
np.
random
.
randn
(
128
)
.
tolist
(
)
,
payload
=
{
"text"
: f
"Content of document {i}"
,
"category"
:
"tech"
if
i %
2
==
0
else
"life"
,
"author"
: f
"author_{i % 3}"
}
)
for
i
in
range
(
100
)
]
client.
upsert
(
collection_name
=
"runoob_collection"
,
points
=
points
)
4. Query
query_vector
=
np.
random
.
randn
(
128
)
.
tolist
(
)
results
=
client.
search
(
collection_name
=
"runoob_collection"
,
query_vector
=
query_vector
,
limit
=
5
,
Filtering can be added
query_filter=Filter(
must=[
FieldCondition(key="category", match=MatchValue(value="tech"))
]
)
)
(
"Query results:"
)
for
result
in
results:
(
f
"ID: {result.id}, Score: {result.score:.4f}"
)
(
f
"Payload: {result.payload}"
)
(
"---"
)
return
client
If Qdrant is started, you can uncomment the following line to run it
qdrant_example()
(
"Qdrant example code: Rust implementation, fully functional."
)
(
)
(
"Qdrant features:"
)
(
" - Good performance: Rust + HNSW"
)
(
" - Full features: Supports filtering, grouping, aggregation, pagination"
)
(
" - Easy deployment: One-click Docker startup"
)
(
" - Supports sharding: Can be horizontally scaled"
)
Mainstream Vector Database Comparison Table
| Product | Type | Deployment | Features | Applicable Scenarios |
|---|---|---|---|---|
| FAISS | Local Library | None | Extremely fast, fully functional, requires self-maintenance | Offline processing, don't want to set up services |
| Chroma | Lightweight | Local/Server | Simple and easy to use, Python preferred | Prototyping, small projects |
| Qdrant | Open source | Docker/K8s | Good performance, full features, Rust | Production environment, medium scale |
| Milvus | Open source | Distributed | Enterprise-grade, most comprehensive features | Large-scale production environment |
| Weaviate | Open source | Docker/K8s | Modular, good ecosystem | Need flexible combination of features |
| Pinecone | Cloud Services | SaaS | Fully managed, on-demand scaling | No operations, fast deployment |
Embedded model selection
The vector database is just infrastructure; the embedding model truly determines the effect.
Comparison of mainstream embedding models
| Model | Dimension | Feature | Price |
|---|---|---|---|
| OpenAI text-embedding-3-small | 1536 | High cost-performance, good overall quality | $0.00002 / 1K tokens |
| OpenAI text-embedding-3-large | 3072 | Highest quality, large dimension | $0.00013 / 1K tokens |
| Cohere Embed v3 | 1024 | Good multilingual support | $0.0001 / 1K tokens |
| bge-large-zh-v1.5 | 1024 | Good Chinese performance, open source and free | Free |
| bge-m3 | 1024 | Multilingual, multi-functional | Free |
| gte-large | 1024 | Balanced choice, open source | Free |
Dimension vs performance trade-off
Higher dimensions usually mean better results, but:
-
1.Storage is more expensive:3072 dimensions take twice the space of 1536 dimensions.
-
2.Slower computation: The computation amount is proportional to the dimension.
-
3.Larger index: HNSW/IVF indexes will also be larger.
Suggestion:First test the effect with a small dimension model, and if it is not enough, then use a large dimension one.In most scenarios, 1536 dimensions are sufficient.
Hybrid Search
Pure vector search is sometimes not good enough because it only matches "semantics," not "keywords."
Hybrid Search = Vector Search + Keyword Search, then merge the results.
BM25 Sparse Retrieval
BM25 is a classic algorithm for traditional search that measures keyword matching degree.
Example
============================================
BM25 Keyword Search Demo
============================================
import
math
from
typing
import
List
,
Dict
,
Set
class
SimpleBM25:
"""Simplified BM25 implementation"""
def
init
(
self
,
k1:
float
=
1.5
,
b:
float
=
0.75
)
:
self
.
k1
=
k1
self
.
b
=
b
self
.
documents
: List
[
List
[
str
]
]
=
[
]
self
.
doc_lengths
: List
[
int
]
=
[
]
self
.
avg_doc_length
:
float
=
0
self
.
term_freqs
: List
[
Dict
[
str
,
int
]
]
=
[
]
self
.
doc_freq
: Dict
[
str
,
int
]
=
{
}
self
.
num_docs
:
int
=
0
def
_tokenize
(
self
,
text:
str
)
List
[
str
]
:
"""Simple tokenization (by space and punctuation)"""
Simplified: convert to lowercase, split by non-alphanumeric characters
import
re
return
[
t.
lower
(
)
for
t
in
re
.
findall
(
r
'\w+'
,
text
)
]
def
fit
(
self
,
documents: List
[
str
]
)
:
"Build index"
self
.
documents
=
[
]
self
.
doc_lengths
=
[
]
self
.
term_freqs
=
[
]
self
.
doc_freq
=
{
}
self
.
num_docs
=
len
(
documents
)
for
doc
in
documents:
tokens
=
self
._tokenize
(
doc
)
self
.
documents
.
append
(
tokens
)
self
.
doc_lengths
.
append
(
len
(
tokens
)
)
Count word frequency
tf: Dict
[
str
,
int
]
=
{
}
for
token
in
tokens:
tf
[
token
]
=
tf.
get
(
token
,
0
)
1
self
.
term_freqs
.
append
(
tf
)
Update document frequency
for
token
in
tf.
keys
(
)
:
self
.
doc_freq
[
token
]
=
self
.
doc_freq
.
get
(
token
,
0
)
1
self
.
avg_doc_length
=
sum
(
self
.
doc_lengths
)
/
self
.
num_docs
def
score
(
self
,
query:
str
)
List
[
float
]
:
"""Calculate the BM25 score for each document"""
query_tokens
=
self
._tokenize
(
query
)
scores
=
[
0.0
]
self
.
num_docs
for
token
in
query_tokens:
if
token
not
in
self
.
doc_freq
:
continue
IDF calculation
df
=
self
.
doc_freq
[
token
]
idf
=
math
.
log
(
1
(
self
.
num_docs
- df +
0.5
)
/
(
df +
0.5
)
)
Calculate score for each document
for
doc_idx
in
range
(
self
.
num_docs
)
:
doc_len
=
self
.
doc_lengths
[
doc_idx
]
tf
=
self
.
term_freqs
[
doc_idx
]
.
get
(
token
,
0
)
BM25 core formula
numerator
=
tf *
(
self
.
k1
1
)
denominator
=
tf +
self
.
k1
(
1
self
.
b
self
.
b
- doc_len /
self
.
avg_doc_length
)
scores
[
doc_idx
]
=
idf * numerator / denominator
return
scores
def
search
(
self
,
query:
str
,
top_k:
int
=
5
)
List
[
Dict
]
:
"""Search Top K"""
scores
=
self
.
score
(
query
)
Sort
results
=
[
{
"doc_idx"
: i
,
"score"
: s
}
for
i
,
s
in
enumerate
(
scores
)
]
results.
sort
(
key
=
lambda
x: x
[
"score"
]
,
reverse
=
True
)
return
results
[
:top_k
]
Test
documents
=
[
"Python is a programming language that is simple and easy to learn."
,
"JavaScript is used for web development, usable for both front-end and back-end."
,
"A vector database is used to store and retrieve vector embeddings."
,
"There are many types of databases, such as relational databases and NoSQL databases."
,
"HNSW is an approximate nearest neighbor search algorithm."
]
bm25
=
SimpleBM25
(
)
bm25.
fit
(
documents
)
Search
query
=
"Database"
results
=
bm25.
search
(
query
,
top_k
=
5
)
(
f
"Query:\"{query}\""
)
(
"BM25 search results:"
)
for
r
in
results:
(
f
" Document {r['doc_idx']}: {documents[r['doc_idx']]}"
)
(
f
" score = {r['score']:.4f}"
)
Output similar to:
Query: "database"
BM25 search results:
Document 2: Vector databases are used to store and retrieve vector embeddings.
score = 0.7134
Document 3: There are many types of databases, such as relational databases and NoSQL databases.
Score = 0.6148
...
RRF: Reciprocal Rank Fusion
RRF (Reciprocal Rank Fusion) is a simple and effective method for fusing multiple search results.
Formula: score = 1 / (k + rank), where k is usually set to 60.
Example
============================================
RRF Fusion Demo
============================================
from
typing
import
List
,
Dict
,
Any
def
rrf_fuse
(
result_lists: List
[
List
[
Any
]
]
,
k:
int
=
60
)
Dict
[
Any
,
float
]
:
"""
RRF Fusion: Sum scores using 1/(k + rank) for each result list
result_lists: Multiple sorted result lists
"""
scores: Dict
[
Any
,
float
]
=
{
}
for
results
in
result_lists:
for
rank
,
item
in
enumerate
(
results
)
:
score
=
1.0
/
(
k + rank
)
scores
[
item
]
=
scores.
get
(
item
,
0
)
- score
return
scores
Example: vector search results and BM25 search results
vector_results
=
[
"doc3"
,
"doc1"
,
"doc4"
,
"doc2"
,
"doc5"
]
Vector search considers doc3 most relevant
bm25_results
=
[
"doc2"
,
"doc4"
,
"doc3"
,
"doc5"
,
"doc1"
]
BM25 considers doc2 most relevant
RRF fusion
fused
=
rrf_fuse
(
[
vector_results
,
bm25_results
]
)
Sorting
final_rank
=
sorted
(
fused.
items
(
)
,
key
=
lambda
x: x
[
1
]
,
reverse
=
True
)
(
"Vector search results:"
,
vector_results
)
(
"BM25 search results:"
,
bm25_results
)
(
)
(
"Final ranking after RRF fusion:"
)
for
doc
,
score
in
final_rank:
(
f
" {doc}: {score:.6f}"
)
Output:
Vector search results: ['doc3', 'doc1', 'doc4', 'doc2', 'doc5']
BM25 search results: ['doc2', 'doc4', 'doc3', 'doc5', 'doc1']
Final ranking after RRF fusion:
doc3: 0.032787
doc2: 0.032787
doc4: 0.032520
doc1: 0.016393
doc5: 0.016393
Fusion weight tuning
Besides RRF, weighted linear fusion can also be used:
final_score = α * vector_score + (1 - α) * bm25_score
α is the weight for vector search and needs to be tuned based on actual data.
Re-ranking
Hybrid retrieval can be further improved by first retrieving a batch of candidates and then re-ranking them with a more powerful model.
Cross-Encoder Principle
Bi-Encoder (for retrieval): Encodes the query and document separately and compares them using similarity.
Cross-Encoder (for re-ranking): Concatenates the query and document and inputs them into the model to directly output a relevance score.
Cross-Encoder is more accurate but slower, so it is suitable for re-ranking only the top 50-100 candidates.
Instance
============================================
Re-ranking process demonstration
============================================
def
reranking_pipeline_example
(
)
:
"""
Two-stage retrieval process:
1. Coarse retrieval: Quickly find Top 100 using vector search
2. Fine ranking: Re-rank Top 100 using Cross-Encoder
"""
(
"Two-stage retrieval process:"
)
(
)
(
"Stage 1: Coarse Retrieval (Vector Search)"
)
(
- Goal: fast, low latency
)
(
- Method: HNSW/IVF vector search
)
(
" - Output: Top 100 candidates"
)
(
)
(
"Stage 2: Fine Ranking (Cross-Encoder)"
)
(
- Goal: Accurate, high quality
)
(
- Method: Cross-Encoder pairwise scoring
)
(
" - Output: Final Top 10"
)
(
)
(
"Typical configuration:"
)
(
- Retrieval stage: HNSW efSearch = 128, retrieve 100
)
(
- Re-ranking stage: Use bge-reranker or Cohere Rerank
)
(
)
(
"Why not just use Cross-Encoder to search everything?"
)
(
" - Cross-Encoder is too slow, searching 1 million articles is unrealistic"
)
(
- Vector search for 1 million is fast, Cross-Encoder re-ranking for 100 is also fast
)
Cohere Rerank API example (pseudocode)
def
cohere_rerank_example
(
)
:
"""
Cohere Rerank API usage example
"""
(
"Typical usage of Cohere Rerank API:"
)
(
)
(
'''
import cohere
co = cohere.Client(api_key="your-api-key")
query = "What is a vector database?"
documents = [
"Content of document 1...",
"Content of document 2...",
... # Top 100 candidates
]
results = co.rerank(
query=query,
documents=documents,
top_n=10,
model="rerank-english-v3.0"
)
for r in results:
print(r.index, r.relevance_score, documents[r.index])
'''
)
reranking_pipeline_example
(
)
Performance and latency trade-off
| Solution | Quality | Speed | Cost | Applicable Scenarios |
|---|---|---|---|---|
| Pure Vector Search | Medium | Extremely Fast | Low | Extremely high speed requirements |
| Hybrid search | Medium-high | Fast | Medium | Balanced choice |
| Vector + re-ranking | High | Medium | Medium-High | Quality focused |
| Mixed + Reorder | Highest | Medium-Slow | High | Quality first |
Production Environment Optimization
There are many details to pay attention to when moving from Demo to production.
Index Sharding Strategy
When the data volume exceeds the capacity of a single machine, sharding is required:
-
1.Sharding by ID: Simple, but all shards must be searched during queries.
-
2.Sharding by vector clustering: Only search a few relevant shards during query.
Metadata filtering
In production environments, metadata filtering is almost always required.
Two strategies:
-
1.Pre-filtering: First filter by metadata, then perform vector search.
-
2.Post-filtering: First perform vector search, then filter by metadata.
Selection principle: If many vectors remain after filtering, use pre-filtering; if few remain, use post-filtering.
Incremental update
Most vector databases support incremental addition, but note:
-
1.Batch additionAdd in batches, do not add one by one.
-
2.Index rebuildingSome indexes (such as IVF) require periodic retraining.
-
3.Version managementRetain old version indexes so that you can roll back during updates.
Monitoring metrics
Production environment should monitor:
-
1.Query latency: P50, P95, P99.
-
2.Recall rate: Regularly check the quality of Top K results.
-
3.Index sizeMemory/disk usage.
-
4.QPSQueries per second.