向量数据库入门
向量数据库是RAG应用的核心组件,它能够存储和检索高维向量,实现语义搜索能力。
什么是向量数据库?
传统数据库用关键词精确匹配,向量数据库用语义相似度匹配:
传统搜索:
查询:"苹果手机"
结果:包含"苹果手机"四个字的文档
向量搜索:
查询:"苹果手机"
结果:包含"iPhone"、"苹果公司产品"等语义相关文档核心概念
向量(Embedding)
文本转换为数值向量的过程:
文本:"苹果是一家科技公司"
↓ Embedding模型
向量:[0.23, -0.45, 0.67, 0.12, ...] # 通常768或1536维相似度计算
python
import numpy as np
def cosine_similarity(a, b):
"""余弦相似度"""
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
vec1 = [0.5, 0.5, 0.5]
vec2 = [0.7, 0.7, 0.7]
similarity = cosine_similarity(vec1, vec2) # 接近1表示相似主流向量数据库
| 数据库 | 特点 | 适用场景 |
|---|---|---|
| FAISS | Meta开源,本地运行 | 开发测试、小规模 |
| Chroma | 轻量级,易用 | 中小规模应用 |
| Pinecone | 云服务,免运维 | 生产环境 |
| Milvus | 开源,高性能 | 大规模企业应用 |
| Qdrant | Rust实现,高效 | 高性能需求 |
快速入门:Chroma
安装
bash
pip install chromadb langchain-chroma基本使用
python
import chromadb
# 创建客户端
client = chromadb.Client()
# 创建集合
collection = client.create_collection("documents")
# 添加文档
collection.add(
documents=[
"Python是一种编程语言",
"机器学习是人工智能的子领域",
"LangChain是开发AI应用的框架"
],
ids=["doc1", "doc2", "doc3"]
)
# 查询
results = collection.query(
query_texts=["什么是AI?"],
n_results=2
)
print(results["documents"])
# ['机器学习是人工智能的子领域', 'LangChain是开发AI应用的框架']使用Embedding模型
OpenAI Embeddings
python
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(
texts=["文档1", "文档2", "文档3"],
embedding=embeddings,
persist_directory="./chroma_db" # 持久化存储
)
# 查询
results = vectorstore.similarity_search("查询文本", k=3)本地Embedding模型
python
from langchain_community.embeddings import HuggingFaceEmbeddings
# 使用本地模型(免费)
embeddings = HuggingFaceEmbeddings(
model_name="BAAI/bge-small-zh-v1.5" # 中文模型
)
vectorstore = Chroma.from_texts(
texts=["中文文档1", "中文文档2"],
embedding=embeddings
)FAISS入门
python
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
# 创建向量库
texts = ["文档1", "文档2", "文档3"]
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_texts(texts, embeddings)
# 保存
vectorstore.save_local("faiss_index")
# 加载
vectorstore = FAISS.load_local(
"faiss_index",
embeddings,
allow_dangerous_deserialization=True
)
# 搜索
results = vectorstore.similarity_search("查询", k=2)向量数据库操作
添加文档
python
from langchain_core.documents import Document
docs = [
Document(page_content="内容1", metadata={"source": "file1.txt"}),
Document(page_content="内容2", metadata={"source": "file2.txt"})
]
vectorstore.add_documents(docs)删除文档
python
# 删除指定ID
vectorstore.delete(["doc1", "doc2"])
# 清空所有
vectorstore.delete_collection()元数据过滤
python
# 搜索时过滤
results = vectorstore.similarity_search(
"查询",
k=5,
filter={"source": "file1.txt"}
)检索策略
相似度搜索
python
# 返回最相似的k个文档
docs = vectorstore.similarity_search("查询", k=3)
# 返回文档和相似度分数
docs_and_scores = vectorstore.similarity_search_with_score("查询", k=3)MMR搜索(最大边际相关性)
python
# 平衡相关性和多样性,避免返回内容过于相似
docs = vectorstore.max_marginal_relevance_search(
"查询",
k=4,
fetch_k=20 # 先获取20个候选
)小结
| 概念 | 说明 |
|---|---|
| Embedding | 文本→向量 |
| 相似度 | 向量之间的距离 |
| FAISS | 轻量级本地向量库 |
| Chroma | 易用的向量数据库 |
| 元数据过滤 | 按属性筛选结果 |
下一步
学会向量数据库后,继续学习 知识库搭建。