数据库
在构建语义搜索、RAG 或相似匹配应用且需要管理…
适用于需要为语义搜索、RAG 或相似性应用选择并运维 Pinecone、Weaviate、Chroma 等向量数据库的场景。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
在构建语义搜索、RAG 或相似匹配应用且特定
解决思路
- 用 OpenAI `client.embeddings.create` 将文本转 embedding,model 用 `text-embedding-3-small`,返回 `response.data[0].embedding`。
- 批量生成 OpenAI embedding:`client.embeddings.create(input=texts, model='text-embedding-3-large')`,提取每个 `item.embedding`。
- 用 Sentence Transformers 生成开源 embedding:`SentenceTransformer('all-MiniLM-L6-v2')`,调用 `model.encode(texts).tolist()`。
- 用 Cohere 生成 embedding:`cohere.Client('YOUR_API_KEY').embed(texts=texts, model='embed-english-v3.0', input_type='search_document')`,返回 `response.embeddings`。
- 按用例选择 embedding 配置:`openai-small` 1536 维、成本 0.02、通用低成本;`openai-large` 3072 维、成本 0.13、高准确率;`sentence-transformers` 384 维、成本 0、本地或隐私敏感;`cohere-multilingual` 1024 维、成本 0.10、多语言。
- Pinecone 安装:`pip install pinecone-client`。
- Pinecone 初始化:`Pinecone(api_key='YOUR_API_KEY')`。
- Pinecone 列出已有索引:`pc.list_indexes()`,打印 `idx.name`。
- 创建 Pinecone serverless 索引:`pc.create_index(name='production-search', dimension=1536, metric='cosine', spec=ServerlessSpec(cloud='aws', region='us-east-1'), deletion_protection='enabled', tags={...})`。
- 连接 Pinecone 索引并查看统计:`pc.Index(index_name)`,`index.describe_index_stats()`。
- Pinecone 选择性元数据索引:创建索引时配置 `schema.fields`,对 `document_id`、`category`、`created_at`、`tags` 设 `filterable=True`;对 `document_title`、`document_url`、`full_content` 设 `filterable=False`,以省内存但可随结果返回。
- Weaviate 安装:`pip install weaviate-client`。
- Weaviate 连接:本地用 `weaviate.connect_to_local()`;Weaviate Cloud 用 `weaviate.connect_to_wcs(cluster_url='YOUR_WCS_URL', auth_credentials=weaviate.auth.AuthApiKey('YOUR_API_KEY'))`。
- Weaviate 创建 collection:`client.collections.create(name='Documents', vectorizer_config=Configure.Vectorizer.text2vec_openai(model='text-embedding-3-small'), properties=[...])`,属性含 title、content、category、created_at、tags。
- 获取 Weaviate collection 并查看配置:`client.collections.get('Documents')`,`documents.config.get()`。
- Chroma 安装:`pip install chromadb`。
- Chroma 初始化:持久化用 `chromadb.PersistentClient(path='./chroma_db')`;内存用 `chromadb.EphemeralClient()`。
- Chroma 创建或获取 collection:`client.get_or_create_collection(name='documents', metadata={'description': 'Document collection for semantic search', 'hnsw:space': 'cosine'})`。
- Chroma 列出 collections 并查看数量:`client.list_collections()`,`collection.count()`。
- Pinecone 创建 serverless 索引:`ServerlessSpec(cloud='aws', region='us-east-1')`,自动扩缩、按用量付费。
- Pinecone 创建 pod-based 索引:`PodSpec(environment='us-east-1-aws', pod_type='p1.x1', pods=2, replicas=2, shards=1)`,metric 用 `dotproduct`。
- Pinecone 创建 sparse 索引:`dimension=None, metric='dotproduct', spec=ServerlessSpec(...)`。
- Pinecone 管理索引:`pc.list_indexes()` 打印 `name/status.state/host`;`pc.describe_index('production-search')` 查看 dimension/metric/status;`pc.delete_index('test-index')` 删除。
- Pinecone 高吞吐索引配置:`PodSpec(pod_type='p2.x1', pods=4, replicas=3)`。
- Pinecone 大规模存储配置:`PodSpec(pod_type='s1.x1', pods=8, shards=4)`。
- Pinecone 成本优化开发配置:用 `ServerlessSpec`,只为使用量付费。
- Pinecone 单条 upsert:`index.upsert(vectors=[{'id': vector_id, 'values': [...], 'metadata': {...}}], namespace='documents')`。
- Pinecone 批量 upsert:`batch_size=100`,累积 vectors,达到 batch_size 或最后一条时 `index.upsert(vectors=vectors, namespace='documents')`。
- Pinecone 异步 upsert:`index.upsert(..., async_req=True)`,配合 `asyncio.gather` 并行处理批次。
- Pinecone sparse vector upsert:vectors 中包含 `values` 稠密向量和 `sparse_values` 的 `indices`(token IDs)与 `values`(TF-IDF 权重)。
- Pinecone hybrid query:`index.query(vector=dense_vector, sparse_vector={...}, top_k=10, namespace='hybrid', include_metadata=True)`。
- Weaviate 插入单对象:`documents.data.insert(properties={...})`,返回 `doc_uuid`。
- Weaviate 批量插入:`with documents.batch.dynamic() as batch: batch.add_object(properties={...})`。
- Weaviate 插入自定义向量:`documents.data.insert(properties={...}, vector=[...])`。
- Weaviate 更新对象:`documents.data.update(uuid=doc_uuid, properties={'title': 'Updated Title'})`。
- Weaviate 删除对象:`documents.data.delete_by_id(uuid=doc_uuid)`。
- Chroma 添加文档自动嵌入:`collection.add(documents=[...], metadatas=[...], ids=[...])`。
- Chroma 添加自定义嵌入:`collection.add(embeddings=[...], metadatas=[...], ids=[...])`。
- Chroma 更新文档:`collection.update(ids=[...], documents=[...], metadatas=[...])`。
- Chroma 删除文档:`collection.delete(ids=[...])`。
- Chroma 按 ID 获取文档:`collection.get(ids=[...], include=['documents', 'metadatas', 'embeddings'])`。
- Pinecone 基本相似搜索:先用 OpenAI 生成 query embedding,再 `index.query(vector=query_embedding, top_k=10, namespace='documents', include_values=False, include_metadata=True)`,处理 `results.matches` 的 id/score/metadata。
- Pinecone 按 ID 查询相似项:`index.query(id='existing-doc-id', top_k=10, namespace='documents', include_metadata=True)`,用于 find similar items。
- Pinecone 多向量搜索:`index.query(queries=[embedding1, embedding2, embedding3], top_k=5, namespace='documents', include_metadata=True)`,遍历每个查询结果。
- Weaviate near_text 搜索:`documents.query.near_text(query='...', limit=10, return_metadata=MetadataQuery(distance=True, certainty=True))`。
- Weaviate near_vector 搜索:`documents.query.near_vector(near_vector=[...], limit=10)`。
- Weaviate near_object 搜索:`documents.query.near_object(near_object='uuid-of-reference-object', limit=10)`。
- Chroma 文本查询:`collection.query(query_texts=['...'], n_results=10, include=['documents', 'metadatas', 'distances'])`。
- Chroma 自定义 embedding 查询:`collection.query(query_embeddings=[[...]], n_results=10)`。
- Pinecone 元数据过滤:用 `$eq`、`$ne`、`$gte`/`$lte`、`$in`、`$exists`、`$and`/`$or`、`$gt`/`$gte` 等 filter 操作符,并在 `index.query` 中传 `filter=...`。
- Pinecone 时间过滤模式:`search_recent_documents` 计算 `cutoff_date = (datetime.now() - timedelta(days=days)).isoformat()`,过滤 `created_at` 的 `$gte`。
- Pinecone 权限过滤模式:`search_with_permissions` 用 `$or` 组合 `owner_id` `$eq`、`shared_with` `$in`、`public` `$eq`、`required_roles` `$in`。
- Pinecone 多租户过滤模式:`search_tenant_documents` 过滤 `tenant_id` `$eq`,可选叠加 `category` `$eq`。
- Pinecone 分面搜索模式:`faceted_search` 根据 facets 把 list 构造成 `$in`、单值构造成 `$eq`,再用 `$and` 组合。
- Weaviate 元数据过滤:用 `Filter.by_property('category').equal('education')`、`.greater_than(2020)`、`.contains_any([...])`,并用 `&` 和 `|` 组合复杂条件。
- Chroma 元数据过滤:在 `collection.query` 中用 `where={'category': 'education'}`、`$and`、`$or`、`$gte`、`$in` 等条件。
- Pinecone 自定义稀疏向量生成:`create_sparse_vector` 用正则 `\w+` 小写分词,`Counter` 统计 TF,用 `hash(word) % 10000` 建词汇表,取 top-k terms,返回 `indices` 和归一化 `values`。
- Pinecone hybrid search 函数:`hybrid_search` 同时生成 dense embedding 和 sparse vector,调用 `index.query(vector=..., sparse_vector=..., top_k=..., include_metadata=True)`,alpha 控制稠密权重。
- Weaviate hybrid 搜索:`documents.query.hybrid(query='...', limit=10, alpha=0.5, fusion_type='rankedFusion' 或 'relativeScore')`,可叠加 filters 或 custom vector。
- 自定义 BM25+Vector 混合搜索:初始化 `BM25Okapi(tokenized_docs)`,搜索时先 vector search 取 `top_k*2`,再 BM25 `get_scores`,归一化后用 `alpha * vec_score + (1-alpha) * bm25_score` 融合并排序。
- Pinecone namespace upsert/query:在 `index.upsert` 和 `index.query` 中传 `namespace='production'`。
- Pinecone namespace 统计:`index.describe_index_stats()` 遍历 `stats.namespaces` 获取每个 namespace 的 `vector_count`。
- Pinecone 删除 namespace 全部向量:`index.delete(delete_all=True, namespace='test')`。
- Pinecone 多 namespace 架构:定义 production/staging/development/archive,`upsert_with_environment` 选择 namespace,`search_across_namespaces` 查询多个 namespace 后按 score 合并。
- Weaviate 多 collection:为 Products/Users/Reviews 分别 `client.collections.create` 并配置 properties/vectorizer。
- Weaviate 跨 collection 引用:创建 Orders collection,加 `ReferenceProperty(name='hasProduct', target_collection='Products')` 和 `byUser` 指向 Users。
- Weaviate 多 collection 搜索:`search_all_collections` 遍历 Products/Users/Reviews,分别 `near_text(query=query, limit=5)`。
- Weaviate 删除 collection:`client.collections.delete('TestCollection')`。
- Chroma 多 collection:创建 documents/images/code,各自 `get_or_create_collection` 带 metadata。
- Chroma 列出所有 collection:遍历 `client.list_collections()` 打印 name/count/metadata。
- Chroma collection 专属操作:对 `docs_collection` 执行 `add(documents=[...], metadatas=[...], ids=[...])`。
- Chroma 删除 collection:`client.delete_collection('test_collection')`。
- Chroma 多 collection 搜索:`search_all_collections` 遍历 `client.list_collections()`,对每个 collection 调 `query(query_texts=[query], n_results=n_results)`。
- 批量操作最佳实践:设 `OPTIMAL_BATCH_SIZE = 100`,`batch_upsert` 按批次调用 `index.upsert` 并打印进度。
- 并行批量 upsert:`parallel_batch_upsert` 用 `ThreadPoolExecutor(max_workers=4)` 对 batch 调 `index.upsert`,统计成功数量。
- 限流:实现 `RateLimiter(max_calls, time_window)`,`wait_if_needed` 控制如 100 calls/minute,再执行 `index.upsert`。
- 批量删除优化:`bulk_delete_by_filter` 先用 dummy vector 和 `top_k=10000` 查询匹配 filter 的 ids,再按 `batch_size=1000` 调 `index.delete(ids=batch, namespace=...)`。
- 查询优化:不需要向量和元数据时设 `include_values=False` 和 `include_metadata=False`。
- 查询优化:使用合适 `top_k`,小 `top_k` 更快,避免不必要 `top_k=1000`。
- 查询优化:尽可能先加 filter 缩小搜索空间,再执行向量搜索。
- 查询优化:批量查询 `index.query(queries=[...], top_k=10, namespace='documents')` 替代多次单条查询。
- 查询缓存:实现 `CachedIndex`,用 `vector_hash` 对 vector/top_k/kwargs 生成 key,缓存 query 结果,cache_size 默认 1000。
- 规模估算:`calculate_index_requirements` 按 `vector_size = dimension * 4`、metadata 估算总存储,用 Pinecone serverless 0.095 美元/GB/月估算,推荐 >10M 用 `s1.x1`,否则 `p1.x1`。
- 分片扩展:`create_sharded_indexes(base_name, num_shards, dimension, metric)` 创建多个索引,`route_to_shard(vector_id, num_shards)` 用 `hash(vector_id) % num_shards`,查询所有 shard 后合并排序。
- 错误处理:实现 `PineconeRetryHandler(max_retries=3, base_delay=1.0)`,`retry_with_backoff` 指数退避重试,封装 `safe_upsert` 和 `safe_query`。
- 监控:定义 `QueryMetrics`,`VectorDBMonitor.track_query` 记录 query_time/result_count/top_score/timestamp/namespace/filter_used,慢查询超过 1 秒告警,`get_stats` 计算 avg/p95/p99 等。
- 数据校验向量:`VectorValidator(expected_dimension)` 的 `validate_vector` 检查 list/ndarray、维度、NaN/Inf、零向量。
- 数据校验元数据:`validate_metadata` 检查 dict、UTF-8 大小不超过 40KB,并检查 required_fields 如 title/category。
- 批量校验:`validate_batch` 返回 valid_vectors 和 errors,只对 valid_vectors 调 `index.upsert`。
- 备份:`VectorDBBackup` 用 `backup_namespace` 生成带 timestamp 的备份文件,支持 gzip 压缩,JSON 保存 namespace/timestamp/vector_count/vectors。
- 恢复:`restore_from_backup` 读取 `.gz` 或 JSON,按 batch_size 分批 `index.upsert` 到 target_namespace。
- 存储成本优化:减少 metadata 大小,只存 title/doc_id/category/created_at 等必要字段,不要把 full_content/description/extra 放进 metadata。
- 存储成本优化:用 selective metadata indexing,只把需要过滤的字段设 `filterable=True`。
- 存储成本优化:定期清理旧向量,`cleanup_old_vectors(days_old=90)` 删除 `created_at` 小于 cutoff 的向量。
- 存储成本优化:用更小维度模型如 `all-MiniLM-L6-v2` 384 维替代 `text-embedding-3-small` 1536 维,降低约 75% 存储但牺牲精度。
- 查询成本优化:合并为 batch queries,减少 API 调用。
- 查询成本优化:选择合适 `top_k`,一般 `top_k=10` 足够。
- 查询成本优化:最小化数据传输,不需要时设 `include_values=False`、`include_metadata=False`。
- 查询成本优化:用 `lru_cache(maxsize=1000)` 或自身缓存缓存重复查询。
- 查询成本优化:按流量选择部署类型,低/可变流量用 serverless,高稳定流量用 pods;`choose_deployment_type` 比较 serverless 成本与 pod 月费。
- 成本监控:实现 `CostMonitor`,记录 operations,维护 pricing:serverless write units 0.0000025、read units 0.00000625、storage 0.095、`p1_x1_pod` 0.096、`p2_x1_pod` 0.240。
- 成本监控:`track_operation` 记录 upsert/query 等操作次数。
- 成本监控:`estimate_monthly_cost` 对 serverless 计算 storage/writes/reads,对 pods 按 730 小时计算。
- 成本监控:`get_cost_report` 输出操作摘要和成本报告。
- 总结选型:生产规模用 Pinecone,知识图谱用 Weaviate,本地开发用 Chroma。
- 总结优化:平衡 embedding 维度、准确率与成本。
- 总结检索:组合向量相似度与结构化过滤。
- 总结混合:组合 dense 和 sparse 向量提升效果。
- 总结扩展:用 batching、caching 和合适索引配置。
- 总结成本:跟踪使用量并选择正确部署类型。
适用边界 · 注意事项
- 不需要语义检索或相似匹配,传统关键词检索或关系数据库即可满足时,不必引入向量数据库。
- 数据量很小且可接受暴力扫描,或只需要本地原型且不想承担云服务与 API 成本时,不必使用 Pinecone 等托管服务。
- 没有可用于生成 embeddings 的模型或 API,且不允许外部 API 或云服务时,需改用本地开源方案并重新评估。