Runoob Tutorial ArchiveEnglish

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:

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.

Traditional database vs. vector database: a comparison of query methods Traditional database (exact match) SELECT * WHERE name = 'iPhone' Match result: √ iPhone Pro 128GB x iPhone 15 (no match) x Apple phone (no match) x smartphone iOS (no match) Vector database (semantic similarity) search(embed("iPhone"), top_k=4) Similar results (with similarity): √ iPhone Pro 128GB 0.98 √ iPhone 15 0.95 √ Apple phone 0.93 √ Smartphone iOS 0.87

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.

Embedding process illustration Text "The weather is really nice today" Image A photo of a cat Audio A clip of music Embedding model Embedding Model text-embedding-3 CLIP / ResNet ... Text vector (1536 dims): [0.12, -0.54, 0.87, 0.03, ...] Image vector (512 dims): [-0.33, 0.71, 0.22, 0.95, ...] Audio vector (256 dims): [0.66, -0.11, 0.48, -0.72, ...] Tip: objects with similar semantics end up closer together as vectors in the space.

Semantically close means vectors are close.

To understand with a simplified 2D example (the actual dimension is hundreds to thousands):

Semantic clustering in vector space (2D illustration) x y Animal category Cat Dog Rabbit Bear Tech category Computer Phone Keyboard Monitor Food category Pizza Burger Noodles Query: pet Querying the vector for "pet" is closer to "cat" and "dog", belonging to the animal cluster.

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}} ]

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} ]

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 ]

Comparison of three methods

Comparison of three similarity computation methods Method Principle Result meaning Recommendation scenarios Cosine similarity Compute the cosine of the angle between two vectors Focus on direction, ignore magnitude [-1, 1], the closer to 1 the more similar Text search, NLP first choice Euclidean distance Straight-line distance between two points Focus on absolute position differences [0, ∞), the closer to 0 the more similar Image retrieval, coordinate system data Dot product Sum of products of vector components Consider both direction and magnitude Larger value means more similar (no fixed range) Recommendation systems, normalization scenarios

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

)

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

]

)

print

(

f

"v1 vs v2 cosine similarity: {cosine_similarity(v1, v2):.4f}"

)

 

Approximately 0.9997 (very similar)

print

(

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 index principle: cluster first, then search within the bucket. Cluster 1 center Cluster 2 center Cluster 3 center Query Far Close! Far Perform exact search only within the nearest cluster 2, greatly reducing computation.

IVF execution steps:

  1. Training phase: Use K-Means to cluster all vectors into N clusters and record the center of each cluster
  2. 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.

HNSW layered structure diagram Layer 2 (sparsest, long-range jumps) A B Layer 1 (medium density, medium-range jumps) C A D B E Layer 0 (densest, exact search) F C A G D H B E I During query, take large jumps from the top level to locate the region, then refine level by level to precisely find the nearest neighbor.

Core idea of HNSW:

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.

Horizontal comparison of mainstream vector databases Database Type Deployment method Feature Applicable scenarios Difficulty Chroma Open source, free Pure vector DB Local / cloud Embedding-first Minimal API, Python-native Easiest LangChain integration RAG prototyping, AI application development Getting started Qdrant Open source, free Pure vector DB Local / Docker Cloud service Rust implementation, strong performance Supports filtered + vector hybrid search Production-grade recommendation, performance first Intermediate Weaviate Open source, free Multimodal DB Local / cloud SaaS GraphQL API, built-in vectorization Multimodal (text + image) Multimodal retrieval, knowledge graph Intermediate Milvus Open source, free Pure vector DB Distributed deployment Kubernetes LF AI Foundation project Large-scale distributed, full-featured Hundreds of millions of records, enterprise-scale Advanced Pinecone Commercial SaaS Managed vector DB Pure cloud Fully managed service Zero ops, ready to use out of the box Free tier available Quick launch, teams without ops capability Getting started pgvector Open-source plugins PG extension Already using PostgreSQL Use the environment directly Reuse existing PG infrastructure SQL interface, fastest to get started Projects already using PG, lightweight integration Getting started

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

)

)

]

)

print

(

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"

]

)

print

(

f

"\nQuery: {query}"

)

print

(

"-"

50

)

for

i

,

(

doc

,

dist

)

in

enumerate

(

zip

(

results

[

"documents"

]

[

0

]

,

results

[

"distances"

]

[

0

]

)

)

:

similarity

=

1

Cosine distance to similarity

   

print

(

f

"Rank {i+1} (Similarity {similarity:.4f}):"

)

   

print

(

f

" {doc}"

)

   

print

(

)

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 ──────────────────────────────────────────

print

(

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

)

print

(

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.

Typical application scenarios of vector databases RAG RAG knowledge base QA Convert enterprise documents into vectors, Retrieve relevant snippets when the user asks Hand it to the LLM to generate the answer. Representative: ChatPDF, NotionAI Enterprise knowledge base assistant Recommend Personalized recommendation system Convert user behavior and product info into vector, find users with similar taste likes what" to make recommendations. Representative: Spotify song recommendation E-commerce related product recommendations Picture Search by image Encode image into a vector, Find visually similar items via similarity search Similar images, no labels needed. Representative: Google image search Taobao photo search for products Detection Anomaly detection Normal behavior is mapped to the clustered Vector region, vectors of anomalous behavior Detectable by being far from the normal region. Representative: network intrusion detection Financial fraud detection Deduplication Content deduplication / copyright detection Judge two segments by vector similarity Identify whether content is highly similar Plagiarized or duplicated content. Representative: paper plagiarism detection system Music copyright detection Face Face / biometric recognition Encode face into feature vector, Retrieve the most similar in the vector store Known face recognized. Representative: face access control system Phone face unlock

RAG (Retrieval-Augmented Generation) Architecture

RAG is one of the most major application scenarios for vector databases. The core workflow is as follows:

RAG system workflow Step 1 User question "How does Python handle exceptions?" Step 2 Vectorize the question Embedding model -> [0.12, -0.54, ...] Step 3 Vector retrieval In the vector DB Find the most similar document Step 4 LLM generation Retrieved content + question -> Prompt -> answer Step 5 Return answer Document-based Accurate, traceable answers The vector database plays a core role in step 3: finding the most relevant knowledge snippets in milliseconds.

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

  1. 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])

  1. 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

)

  1. Set n_results reasonably: do not set a very large top_k blindly; generally, 3-10 items are enough for RAG scenarios.

  2. 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

)

  1. 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 Database Core Knowledge Recap Vector / embedding Convert the object into High-dimensional numeric vector Close in semantics means close in distance Is the foundation of everything Similarity computation Cosine similarity Euclidean distance Dot product Text prefers cosine Index algorithm HNSW most popular IVF suitable for large scale Flat suitable for small data Approximate for speed Selection reference Getting started: Chroma Production: Qdrant Already using PG: pgvector Billion-scale: Milvus Core applications RAG knowledge QA Personalized recommendation Search by image Anomaly detection

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

  1. Step 1: Understand the concepts of vectors and embeddings, and run the Chroma example in this article
  2. Step 2: Try to build a simple document Q&A system using LangChain + Chroma
  3. Step 3: Learn indexing algorithms like HNSW and understand the trade-off between accuracy and speed
  4. Step 4: Select a suitable vector database based on actual project requirements and deploy it in a production environment

Reference Resources