安装与配置 #

注册 Pinecone 账号 #

步骤 1:访问官网 #

text
┌─────────────────────────────────────────────────────────────┐
│                    注册流程                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 访问 Pinecone 官网                                       │
│     https://www.pinecone.io                                 │
│                                                             │
│  2. 点击 "Sign Up" 或 "Get Started"                         │
│                                                             │
│  3. 选择注册方式:                                           │
│     - Google 账号                                           │
│     - GitHub 账号                                           │
│     - 邮箱注册                                               │
│                                                             │
│  4. 完成邮箱验证                                             │
│                                                             │
│  5. 登录 Pinecone 控制台                                     │
│     https://app.pinecone.io                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

步骤 2:获取 API Key #

text
┌─────────────────────────────────────────────────────────────┐
│                    获取 API Key                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 登录 Pinecone 控制台                                     │
│     https://app.pinecone.io                                 │
│                                                             │
│  2. 点击左侧菜单 "API Keys"                                  │
│                                                             │
│  3. 查看或创建 API Key                                       │
│                                                             │
│  你会看到:                                                  │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Environment: us-east-1-aws                         │   │
│  │  API Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx      │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  注意:                                                     │
│  ⚠️ API Key 只显示一次,请妥善保存                          │
│  ⚠️ 不要将 API Key 提交到代码仓库                           │
│  ⚠️ 生产环境使用独立的 API Key                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

安装 SDK #

Python SDK #

bash
pip install pinecone
text
┌─────────────────────────────────────────────────────────────┐
│                    Python SDK 安装                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  基础安装:                                                  │
│  pip install pinecone                                       │
│                                                             │
│  指定版本:                                                  │
│  pip install pinecone==3.0.0                                │
│                                                             │
│  使用 poetry:                                               │
│  poetry add pinecone                                        │
│                                                             │
│  使用 conda:                                                │
│  conda install -c conda-forge pinecone-client              │
│                                                             │
│  验证安装:                                                  │
│  python -c "import pinecone; print(pinecone.__version__)"  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Node.js SDK #

bash
npm install @pinecone-database/pinecone
text
┌─────────────────────────────────────────────────────────────┐
│                    Node.js SDK 安装                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  使用 npm:                                                  │
│  npm install @pinecone-database/pinecone                    │
│                                                             │
│  使用 yarn:                                                 │
│  yarn add @pinecone-database/pinecone                       │
│                                                             │
│  使用 pnpm:                                                 │
│  pnpm add @pinecone-database/pinecone                       │
│                                                             │
│  验证安装:                                                  │
│  node -e "const {Pinecone} = require('@pinecone-database/pinecone'); console.log('OK')" │
│                                                             │
└─────────────────────────────────────────────────────────────┘

配置环境变量 #

方式一:使用 .env 文件(推荐) #

bash
PINECONE_API_KEY=your-api-key-here
PINECONE_ENVIRONMENT=us-east-1-aws
python
import os
from dotenv import load_dotenv

load_dotenv()

api_key = os.getenv("PINECONE_API_KEY")

方式二:直接设置环境变量 #

bash
export PINECONE_API_KEY="your-api-key-here"
export PINECONE_ENVIRONMENT="us-east-1-aws"

方式三:代码中直接传入 #

python
from pinecone import Pinecone

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

初始化客户端 #

Python 初始化 #

python
from pinecone import Pinecone, ServerlessSpec

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

print(pc.list_indexes())

Node.js 初始化 #

javascript
const { Pinecone } = require('@pinecone-database/pinecone');

const pc = new Pinecone({
  apiKey: 'your-api-key'
});

console.log(await pc.listIndexes());

TypeScript 初始化 #

typescript
import { Pinecone } from '@pinecone-database/pinecone';

const pc = new Pinecone({
  apiKey: process.env.PINECONE_API_KEY!
});

创建第一个索引 #

使用 Python 创建索引 #

python
from pinecone import Pinecone, ServerlessSpec

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

index_name = "my-first-index"

if index_name not in pc.list_indexes().names():
    pc.create_index(
        name=index_name,
        dimension=1536,
        metric="cosine",
        spec=ServerlessSpec(
            cloud="aws",
            region="us-east-1"
        )
    )

index = pc.Index(index_name)

print(f"索引 {index_name} 创建成功!")

使用 Node.js 创建索引 #

javascript
const { Pinecone } = require('@pinecone-database/pinecone');

const pc = new Pinecone({
  apiKey: process.env.PINECONE_API_KEY
});

async function createIndex() {
  const indexName = 'my-first-index';
  
  const existingIndexes = await pc.listIndexes();
  if (!existingIndexes.indexes.find(i => i.name === indexName)) {
    await pc.createIndex({
      name: indexName,
      dimension: 1536,
      metric: 'cosine',
      spec: {
        serverless: {
          cloud: 'aws',
          region: 'us-east-1'
        }
      }
    });
  }
  
  const index = pc.index(indexName);
  console.log(`索引 ${indexName} 创建成功!`);
}

createIndex();

第一个完整示例 #

Python 完整示例 #

python
import os
from pinecone import Pinecone, ServerlessSpec

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

index_name = "quickstart"

if index_name not in pc.list_indexes().names():
    pc.create_index(
        name=index_name,
        dimension=2,
        metric="cosine",
        spec=ServerlessSpec(cloud="aws", region="us-east-1")
    )

index = pc.Index(index_name)

index.upsert(
    vectors=[
        ("vec1", [1.0, 1.0], {"genre": "drama"}),
        ("vec2", [1.0, 0.0], {"genre": "action"}),
        ("vec3", [0.0, 1.0], {"genre": "comedy"}),
    ]
)

print("向量插入成功!")

results = index.query(
    vector=[1.0, 1.0],
    top_k=3,
    include_metadata=True
)

print("查询结果:")
for match in results.matches:
    print(f"ID: {match.id}, Score: {match.score:.4f}, Metadata: {match.metadata}")

Node.js 完整示例 #

javascript
const { Pinecone } = require('@pinecone-database/pinecone');

async function main() {
  const pc = new Pinecone({
    apiKey: process.env.PINECONE_API_KEY
  });

  const indexName = 'quickstart';

  const existingIndexes = await pc.listIndexes();
  if (!existingIndexes.indexes.find(i => i.name === indexName)) {
    await pc.createIndex({
      name: indexName,
      dimension: 2,
      metric: 'cosine',
      spec: {
        serverless: {
          cloud: 'aws',
          region: 'us-east-1'
        }
      }
    });
  }

  const index = pc.index(indexName);

  await index.upsert([
    { id: 'vec1', values: [1.0, 1.0], metadata: { genre: 'drama' } },
    { id: 'vec2', values: [1.0, 0.0], metadata: { genre: 'action' } },
    { id: 'vec3', values: [0.0, 1.0], metadata: { genre: 'comedy' } }
  ]);

  console.log('向量插入成功!');

  const results = await index.query({
    vector: [1.0, 1.0],
    topK: 3,
    includeMetadata: true
  });

  console.log('查询结果:');
  results.matches.forEach(match => {
    console.log(`ID: ${match.id}, Score: ${match.score.toFixed(4)}, Metadata:`, match.metadata);
  });
}

main();

常见问题排查 #

连接问题 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常见连接问题                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  问题 1:API Key 无效                                       │
│  错误:Unauthorized                                         │
│  解决:检查 API Key 是否正确复制                            │
│                                                             │
│  问题 2:网络连接失败                                        │
│  错误:Connection refused                                   │
│  解决:检查网络连接和防火墙设置                              │
│                                                             │
│  问题 3:索引不存在                                          │
│  错误:Index not found                                      │
│  解决:确认索引名称和区域正确                                │
│                                                             │
│  问题 4:索引正在初始化                                      │
│  错误:Index not ready                                      │
│  解决:等待索引初始化完成(通常 1-2 分钟)                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

调试技巧 #

python
import logging

logging.basicConfig(level=logging.DEBUG)

from pinecone import Pinecone

pc = Pinecone(
    api_key="your-api-key",
    debug=True
)

下一步 #

现在你已经完成了 Pinecone 的安装和配置,接下来学习 索引管理,深入了解如何创建和管理索引!

最后更新:2026-04-04