索引管理 #

索引概述 #

索引是 Pinecone 中存储和搜索向量的基本单元。每个索引都有固定的维度和相似度度量方式。

text
┌─────────────────────────────────────────────────────────────┐
│                    索引核心属性                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Index                                              │   │
│  │  ├── name: 索引名称(唯一标识)                      │   │
│  │  ├── dimension: 向量维度(创建后不可更改)           │   │
│  │  ├── metric: 相似度度量方式                          │   │
│  │  ├── spec: 索引规格(Serverless 或 Pod-based)       │   │
│  │  └── status: 索引状态                                │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

索引类型 #

Serverless 索引 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Serverless 索引                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  特点:                                                     │
│  ✅ 完全托管,自动扩展                                      │
│  ✅ 按使用量付费                                            │
│  ✅ 无需预配置资源                                          │
│  ✅ 适合大多数场景                                          │
│                                                             │
│  适用场景:                                                  │
│  - 开发和测试环境                                           │
│  - 中小规模应用                                             │
│  - 流量波动较大的应用                                       │
│  - 快速原型开发                                             │
│                                                             │
│  支持的云平台和区域:                                        │
│  - AWS: us-east-1, us-west-2, eu-west-1                    │
│  - GCP: us-central1                                        │
│  - Azure: eastus2                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Pod-based 索引 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Pod-based 索引                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  特点:                                                     │
│  ✅ 预配置资源                                              │
│  ✅ 更高的控制度                                            │
│  ✅ 适合高吞吐量场景                                        │
│  ✅ 可预测的性能                                            │
│                                                             │
│  适用场景:                                                  │
│  - 大规模生产环境                                           │
│  - 高吞吐量需求                                             │
│  - 需要稳定性能                                             │
│  - 对延迟敏感的应用                                         │
│                                                             │
│  Pod 类型:                                                  │
│  ┌─────────┬────────────────────────────────────────────┐  │
│  │ 类型    │ 描述                                        │  │
│  ├─────────┼────────────────────────────────────────────┤  │
│  │ p1.x1   │ 基础型,适合开发测试                        │  │
│  │ p1.x2   │ 标准型,适合中小规模生产                    │  │
│  │ p1.x4   │ 增强型,适合大规模生产                      │  │
│  │ p1.x8   │ 高性能型,适合高吞吐量场景                  │  │
│  │ p2.x1   │ 高容量型,存储更多向量                      │  │
│  └─────────┴────────────────────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

类型选择建议 #

text
┌─────────────────────────────────────────────────────────────┐
│                    索引类型选择                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  选择 Serverless 的场景:                                    │
│  ✅ 刚开始使用 Pinecone                                     │
│  ✅ 流量不确定或波动较大                                    │
│  ✅ 不想管理基础设施                                        │
│  ✅ 成本敏感型项目                                          │
│                                                             │
│  选择 Pod-based 的场景:                                     │
│  ✅ 大规模生产环境                                          │
│  ✅ 需要稳定的高吞吐量                                      │
│  ✅ 对延迟有严格要求                                        │
│  ✅ 需要更多控制权                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

创建索引 #

创建 Serverless 索引 #

python
from pinecone import Pinecone, ServerlessSpec

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

pc.create_index(
    name="my-serverless-index",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(
        cloud="aws",
        region="us-east-1"
    )
)

创建 Pod-based 索引 #

python
from pinecone import Pinecone, PodSpec

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

pc.create_index(
    name="my-pod-index",
    dimension=1536,
    metric="cosine",
    spec=PodSpec(
        environment="production",
        pod_type="p1.x1",
        pods=1
    )
)

创建参数详解 #

text
┌─────────────────────────────────────────────────────────────┐
│                    创建参数说明                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  name(必需):                                              │
│  - 索引名称,全局唯一                                       │
│  - 最大 45 个字符                                           │
│  - 只能包含小写字母、数字和连字符                            │
│  - 必须以字母开头                                           │
│                                                             │
│  dimension(必需):                                         │
│  - 向量维度                                                 │
│  - 创建后不可更改                                           │
│  - 必须与嵌入模型输出维度匹配                               │
│  - 常见值:768, 1024, 1536, 3072                            │
│                                                             │
│  metric(可选,默认 cosine):                               │
│  - cosine:余弦相似度(推荐文本)                           │
│  - euclidean:欧几里得距离                                  │
│  - dotproduct:点积                                         │
│                                                             │
│  spec(必需):                                              │
│  - ServerlessSpec 或 PodSpec                                │
│  - 定义索引的部署配置                                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

查看索引 #

列出所有索引 #

python
indexes = pc.list_indexes()

for index in indexes:
    print(f"名称: {index.name}")
    print(f"维度: {index.dimension}")
    print(f"度量: {index.metric}")
    print(f"状态: {index.status}")
    print("---")

查看索引详情 #

python
index_description = pc.describe_index("my-index")

print(f"名称: {index_description.name}")
print(f"维度: {index_description.dimension}")
print(f"度量: {index_description.metric}")
print(f"状态: {index_description.status.ready}")
print(f"向量数量: {index_description.status.total_vector_count}")

检查索引状态 #

python
import time

index_name = "my-index"

while not pc.describe_index(index_name).status.ready:
    print("索引正在初始化...")
    time.sleep(5)

print("索引已就绪!")

更新索引 #

扩展 Pod-based 索引 #

python
pc.configure_index(
    name="my-pod-index",
    spec=PodSpec(
        pod_type="p1.x2",
        replicas=2
    )
)

更新参数说明 #

text
┌─────────────────────────────────────────────────────────────┐
│                    更新参数说明                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Pod-based 索引可更新:                                      │
│  - pod_type:升级 Pod 类型                                  │
│  - replicas:调整副本数量                                   │
│                                                             │
│  Serverless 索引:                                          │
│  - 自动扩展,无需手动配置                                   │
│                                                             │
│  注意:                                                     │
│  ⚠️ 维度和度量方式创建后不可更改                            │
│  ⚠️ 升级 Pod 类型需要一定时间                              │
│  ⚠️ 增加副本会提高成本                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

删除索引 #

删除单个索引 #

python
pc.delete_index("my-index")

print("索引已删除")

安全删除索引 #

python
index_name = "my-index"

try:
    pc.delete_index(index_name)
    print(f"索引 {index_name} 已删除")
except Exception as e:
    print(f"删除失败: {e}")

删除前确认 #

python
index_name = "my-index"

confirm = input(f"确定要删除索引 {index_name} 吗?(yes/no): ")

if confirm.lower() == "yes":
    pc.delete_index(index_name)
    print("索引已删除")
else:
    print("操作已取消")

索引统计 #

获取索引统计 #

python
index = pc.Index("my-index")

stats = index.describe_index_stats()

print(f"向量总数: {stats.total_vector_count}")
print(f"维度: {stats.dimension}")
print(f"命名空间: {stats.namespaces}")

按命名空间统计 #

python
stats = index.describe_index_stats()

for namespace, info in stats.namespaces.items():
    print(f"命名空间: {namespace}")
    print(f"  向量数量: {info.vector_count}")

索引最佳实践 #

命名规范 #

text
┌─────────────────────────────────────────────────────────────┐
│                    索引命名规范                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  推荐命名格式:                                              │
│  - {env}-{project}-{purpose}                               │
│                                                             │
│  示例:                                                     │
│  - prod-ecommerce-products                                 │
│  - dev-blog-articles                                       │
│  - staging-search-documents                                │
│                                                             │
│  命名规则:                                                  │
│  ✅ 使用小写字母                                            │
│  ✅ 使用连字符分隔单词                                      │
│  ✅ 包含环境标识                                            │
│  ✅ 描述索引用途                                            │
│                                                             │
│  避免:                                                     │
│  ❌ 使用特殊字符                                            │
│  ❌ 过长的名称                                              │
│  ❌ 含义不清的缩写                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

维度选择 #

text
┌─────────────────────────────────────────────────────────────┐
│                    维度选择指南                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  根据嵌入模型选择:                                          │
│                                                             │
│  | 嵌入模型                          | 推荐维度 |           │
│  |-----------------------------------|----------|           │
│  | OpenAI text-embedding-3-small     | 1536     |           │
│  | OpenAI text-embedding-3-large     | 3072     |           │
│  | Cohere embed-english-v3.0         | 1024     |           │
│  | sentence-transformers/all-MiniLM  | 384      |           │
│  | BGE-large-en                     | 1024     |           │
│                                                             │
│  注意:                                                     │
│  ⚠️ 维度必须与嵌入模型输出完全匹配                          │
│  ⚠️ 创建后无法更改维度                                      │
│  ⚠️ 维度越高,存储和计算成本越大                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

度量选择 #

text
┌─────────────────────────────────────────────────────────────┐
│                    度量选择指南                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  cosine(余弦相似度):                                      │
│  ✅ 文本语义搜索(推荐)                                    │
│  ✅ 不关心向量长度                                          │
│  ✅ 大多数 NLP 任务                                         │
│                                                             │
│  euclidean(欧几里得距离):                                 │
│  ✅ 图像相似度                                              │
│  ✅ 物理距离计算                                            │
│  ✅ 需要考虑向量长度                                        │
│                                                             │
│  dotproduct(点积):                                        │
│  ✅ 向量已归一化                                            │
│  ✅ 需要最快计算速度                                        │
│  ✅ 推荐系统                                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

索引管理完整示例 #

python
import os
import time
from pinecone import Pinecone, ServerlessSpec

pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))

def create_index_if_not_exists(name, dimension, metric="cosine"):
    if name in pc.list_indexes().names():
        print(f"索引 {name} 已存在")
        return pc.Index(name)
    
    print(f"正在创建索引 {name}...")
    pc.create_index(
        name=name,
        dimension=dimension,
        metric=metric,
        spec=ServerlessSpec(cloud="aws", region="us-east-1")
    )
    
    while not pc.describe_index(name).status.ready:
        print("等待索引就绪...")
        time.sleep(5)
    
    print(f"索引 {name} 创建成功!")
    return pc.Index(name)

def get_index_stats(index):
    stats = index.describe_index_stats()
    print(f"向量总数: {stats.total_vector_count}")
    print(f"维度: {stats.dimension}")
    if stats.namespaces:
        print("命名空间:")
        for ns, info in stats.namespaces.items():
            print(f"  {ns}: {info.vector_count} 向量")

def cleanup_index(name):
    if name in pc.list_indexes().names():
        print(f"正在删除索引 {name}...")
        pc.delete_index(name)
        print(f"索引 {name} 已删除")

if __name__ == "__main__":
    index = create_index_if_not_exists("demo-index", 1536)
    get_index_stats(index)

下一步 #

现在你已经掌握了索引管理,接下来学习 向量操作,了解如何插入、更新和删除向量!

最后更新:2026-04-04