mcpField
P
pinecone

pinecone

github.com/kalarislabs其他7343 次安装4 天前更新
代码仓库

关于 pinecone

Pinecone 是面向生产级 RAG 和 AI 应用的托管向量数据库技能,介绍索引与向量操作、元数据筛选、命名空间及混合搜索。

主要功能

  1. 01创建和管理索引
  2. 02写入、查询和删除向量
  3. 03按元数据和命名空间筛选
  4. 04结合稠密与稀疏搜索
  5. 05集成 LangChain 和 LlamaIndex

适用场景

  1. 01为 RAG 存储和检索向量
  2. 02按用户或租户隔离记录
  3. 03结合向量与元数据搜索
  4. 04将 Pinecone 接入 LangChain 或 LlamaIndex

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill pinecone

安装后在 Claude Code 中输入/pinecone确认已加载。

附带文件references/deployment.md

详细介绍

Pinecone - 托管式向量数据库

面向生产级 AI 应用的向量数据库。

何时使用 Pinecone

适用场景:

  • 需要托管式、无服务器向量数据库
  • 生产级 RAG 应用
  • 需要自动扩缩容
  • 低延迟至关重要(<100ms)
  • 不希望管理基础设施
  • 需要混合搜索(稠密向量 + 稀疏向量)

指标:

  • 完全托管的 SaaS
  • 可自动扩展至数十亿个向量
  • p95 延迟 <100ms
  • 99.9% 正常运行时间 SLA

可改用以下替代方案:

  • Chroma:可自托管、开源
  • FAISS:离线使用,纯相似度搜索
  • Weaviate:可自托管,功能更多

快速入门

安装
pip install pinecone-client
基本用法
from pinecone import Pinecone, ServerlessSpec

# Initialize
pc = Pinecone(api_key="your-api-key")

# Create index
pc.create_index(
    name="my-index",
    dimension=1536,  # Must match embedding dimension
    metric="cosine",  # or "euclidean", "dotproduct"
    spec=ServerlessSpec(cloud="aws", region="us-east-1")
)

# Connect to index
index = pc.Index("my-index")

# Upsert vectors
index.upsert(vectors=[
    {"id": "vec1", "values": [0.1, 0.2, ...], "metadata": {"category": "A"}},
    {"id": "vec2", "values": [0.3, 0.4, ...], "metadata": {"category": "B"}}
])

# Query
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=5,
    include_metadata=True
)

print(results["matches"])

核心操作

创建索引
# Serverless (recommended)
pc.create_index(
    name="my-index",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(
        cloud="aws",         # or "gcp", "azure"
        region="us-east-1"
    )
)

# Pod-based (for consistent performance)
from pinecone import PodSpec

pc.create_index(
    name="my-index",
    dimension=1536,
    metric="cosine",
    spec=PodSpec(
        environment="us-east1-gcp",
        pod_type="p1.x1"
    )
)
写入向量
# Single upsert
index.upsert(vectors=[
    {
        "id": "doc1",
        "values": [0.1, 0.2, ...],  # 1536 dimensions
        "metadata": {
            "text": "Document content",
            "category": "tutorial",
            "timestamp": "2025-01-01"
        }
    }
])

# Batch upsert (recommended)
vectors = [
    {"id": f"vec{i}", "values": embedding, "metadata": metadata}
    for i, (embedding, metadata) in enumerate(zip(embeddings, metadatas))
]

index.upsert(vectors=vectors, batch_size=100)
查询向量
# Basic query
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=10,
    include_metadata=True,
    include_values=False
)

# With metadata filtering
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=5,
    filter={"category": {"$eq": "tutorial"}}
)

# Namespace query
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=5,
    namespace="production"
)

# Access results
for match in results["matches"]:
    print(f"ID: {match['id']}")
    print(f"Score: {match['score']}")
    print(f"Metadata: {match['metadata']}")
元数据过滤
# Exact match
filter = {"category": "tutorial"}

# Comparison
filter = {"price": {"$gte": 100}}  # $gt, $gte, $lt, $lte, $ne

# Logical operators
filter = {
    "$and": [
        {"category": "tutorial"},
        {"difficulty": {"$lte": 3}}
    ]
}  # Also: $or

# In operator
filter = {"tags": {"$in": ["python", "ml"]}}

命名空间

# Partition data by namespace
index.upsert(
    vectors=[{"id": "vec1", "values": [...]}],
    namespace="user-123"
)

# Query specific namespace
results = index.query(
    vector=[...],
    namespace="user-123",
    top_k=5
)

# List namespaces
stats = index.describe_index_stats()
print(stats['namespaces'])

混合搜索(稠密向量 + 稀疏向量)

# Upsert with sparse vectors
index.upsert(vectors=[
    {
        "id": "doc1",
        "values": [0.1, 0.2, ...],  # Dense vector
        "sparse_values": {
            "indices": [10, 45, 123],  # Token IDs
            "values": [0.5, 0.3, 0.8]   # TF-IDF scores
        },
        "metadata": {"text": "..."}
    }
])

# Hybrid query
results = index.query(
    vector=[0.1, 0.2, ...],
    sparse_vector={
        "indices": [10, 45],
        "values": [0.5, 0.3]
    },
    top_k=5,
    alpha=0.5  # 0=sparse, 1=dense, 0.5=hybrid
)

LangChain 集成

from langchain_pinecone import PineconeVectorStore
from langchain_openai import OpenAIEmbeddings

# Create vector store
vectorstore = PineconeVectorStore.from_documents(
    documents=docs,
    embedding=OpenAIEmbeddings(),
    index_name="my-index"
)

# Query
results = vectorstore.similarity_search("query", k=5)

# With metadata filter
results = vectorstore.similarity_search(
    "query",
    k=5,
    filter={"category": "tutorial"}
)

# As retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 10})

LlamaIndex 集成

from llama_index.vector_stores.pinecone import PineconeVectorStore

# Connect to Pinecone
pc = Pinecone(api_key="your-key")
pinecone_index = pc.Index("my-index")

# Create vector store
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)

# Use in LlamaIndex
from llama_index.core import StorageContext, VectorStoreIndex

storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)

索引管理

# List indices
indexes = pc.list_indexes()

# Describe index
index_info = pc.describe_index("my-index")
print(index_info)

# Get index stats
stats = index.describe_index_stats()
print(f"Total vectors: {stats['total_vector_count']}")
print(f"Namespaces: {stats['namespaces']}")

# Delete index
pc.delete_index("my-index")

删除向量

# Delete by ID
index.delete(ids=["vec1", "vec2"])

# Delete by filter
index.delete(filter={"category": "old"})

# Delete all in namespace
index.delete(delete_all=True, namespace="test")

# Delete entire index
index.delete(delete_all=True)

最佳实践

  1. 使用无服务器模式 - 自动扩缩容,成本效益高
  2. 批量写入 - 效率更高(每批 100-200 个)
  3. 添加元数据 - 启用过滤
  4. 使用命名空间 - 按用户/租户隔离数据
  5. 监控用量 - 查看 Pinecone 控制台
  6. 优化过滤器 - 为常用过滤字段创建索引
  7. 使用免费套餐测试 - 免费提供 1 个索引、100K 个向量
  8. 使用混合搜索 - 提升质量
  9. 设置合适的维度 - 与嵌入模型匹配
  10. 定期备份 - 导出重要数据

性能

操作延迟备注
写入~50-100ms每批
查询(p50)~50ms取决于索引大小
查询(p95)~100msSLA 目标
元数据过滤~+10-20ms额外开销

定价(截至 2025 年)

无服务器:

  • 每百万读取单位 $0.096
  • 每百万写入单位 $0.06
  • 每 GB 存储每月 $0.06

免费套餐:

  • 1 个无服务器索引
  • 100K 个向量(1536 维)
  • 非常适合原型开发

资源

Agent 操作流程

  1. 检查环境。 确认语料库、嵌入模型和向量存储的版本,以及索引的存放位置。
  2. 明确输入。 根据数据或用户确认格式、标识符和参数。任何会改变结果的值都应询问,不要猜测。
  3. 先运行小规模版本。 为小部分数据创建索引,并使用已知的问题-段落对测试检索。
  4. 使用上述说明和参考资料执行完整任务。
  5. 验证结果。 在带标签的数据集上测量 recall@k;回答只能引用检索到的段落。
  6. 报告。 说明运行了什么(版本、命令、参数)、检查了什么,以及还有哪些不确定之处。
如果发生这种情况请这样做
检索返回了无关片段重新检查分块,添加 BM25/混合搜索,或先进行重排序,再考虑更改生成器。
这些说明中的函数、标志或端点在已安装版本中不存在查阅已安装版本自带的文档(help()、--help、官方文档),进行调整并告知用户。切勿编造 API。
必需的输入、标识符或参数不明确询问用户,或在运行前明确说明所作假设。

诚信原则

  • 切勿捏造结果、参数、标识符、引文或统计数据。如果无法运行或验证某项内容,请明确说明。
  • 回答必须基于检索到的文本;如果语料库不包含答案,请说明。
  • 此处与特定版本相关的细节可能已过时:请对照已安装版本的官方文档进行确认。
  • 涉及费用、占用共享 GPU 或云配额、处理个人或患者数据,或无法撤销的操作时,必须先询问。

相关技能

  • faiss:Facebook 的高效稠密向量相似度搜索和聚类库。
  • qdrant-vector-search:适用于 RAG 和语义搜索的高性能向量相似度搜索引擎。
  • chroma:面向 AI 应用的开源嵌入数据库。

评论

支持 Markdown