> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# PineconeStore 集成

> 使用 LangChain JavaScript 集成 PineconeStore。

[Pinecone](https://www.pinecone.io/) 是一个向量数据库，为全球一些顶尖公司的 AI 应用提供支持。

本指南提供了快速入门 Pinecone [向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores.md) 的概述。有关所有 `PineconeStore` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/javascript/langchain-pinecone/PineconeStore)。

## 概述

### 集成细节

| 类 | 包 | [PY 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/pinecone.md) | 下载量 | 版本 |
| :- | :- | :-: | :-: | :-: |
| [`PineconeStore`](https://reference.langchain.com/javascript/langchain-pinecone/PineconeStore) | [`@langchain/pinecone`](https://www.npmjs.com/package/@langchain/pinecone) | ✅ | ![NPM - 下载量](https://img.shields.io/npm/dm/@langchain/pinecone?style=flat-square\&label=%20&) | ![NPM - 版本](https://img.shields.io/npm/v/@langchain/pinecone?style=flat-square\&label=%20&) |

## 安装

要使用 Pinecone 向量存储，请创建一个 Pinecone 账户，初始化一个索引，并安装 `@langchain/pinecone`、`@langchain/core` 以及 [官方 Pinecone SDK](https://www.npmjs.com/package/@pinecone-database/pinecone)（`@pinecone-database/pinecone` v5.x），以初始化 `PineconeStore` 的客户端。

本指南以 [OpenAI 嵌入](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/openai.md) 为示例。您可以使用 [其他支持的嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。

```bash npm theme={null}
npm install @langchain/pinecone @langchain/openai @langchain/core @pinecone-database/pinecone@5
```

```bash yarn theme={null}
yarn add @langchain/pinecone @langchain/openai @langchain/core @pinecone-database/pinecone@5
```

```bash pnpm theme={null}
pnpm add @langchain/pinecone @langchain/openai @langchain/core @pinecone-database/pinecone@5
```

### 凭证

注册 [Pinecone](https://www.pinecone.io/) 账户并创建索引。确保维度与您要使用的嵌入匹配（OpenAI 的默认值是 `text-embedding-3-small` 的 1536）。完成后，设置 `PINECONE_INDEX`、`PINECONE_API_KEY` 和（可选的）`PINECONE_ENVIRONMENT` 环境变量：

```typescript theme={null}
process.env.PINECONE_API_KEY = "your-pinecone-api-key";
process.env.PINECONE_INDEX = "your-pinecone-index";

// Optional
process.env.PINECONE_ENVIRONMENT = "your-pinecone-environment";
```

如果本指南使用 OpenAI 嵌入，请设置您的 OpenAI 密钥：

```typescript theme={null}
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

如果您希望自动跟踪模型调用，可以通过取消注释下方设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```typescript theme={null}
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

```typescript theme={null}
import { PineconeStore } from "@langchain/pinecone";
import { OpenAIEmbeddings } from "@langchain/openai";

import { Pinecone as PineconeClient } from "@pinecone-database/pinecone";

const embeddings = new OpenAIEmbeddings({
  model: "text-embedding-3-small",
});

const pinecone = new PineconeClient();
// Will automatically read the PINECONE_API_KEY and PINECONE_ENVIRONMENT env vars
const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX!);

const vectorStore = await PineconeStore.fromExistingIndex(
  embeddings,
  {
    pineconeIndex,
    // Maximum number of batch requests to allow at once. Each batch is 1000 vectors.
    maxConcurrency: 5,
    // You can pass a namespace here too
    // namespace: "foo",
  }
);
```

## 管理向量存储

### 向向量存储添加项

```typescript theme={null}
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "The powerhouse of the cell is the mitochondria",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "Buildings are made out of brick",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "Mitochondria are made out of lipids",
  metadata: { source: "https://example.com" }
};

const document4: Document = {
  pageContent: "The 2024 Olympics are in Paris",
  metadata: { source: "https://example.com" }
}

const documents = [document1, document2, document3, document4];

await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });
```

```text theme={null}
[ '1', '2', '3', '4' ]
```

**注意：** 添加文档后，需要稍等片刻才能进行查询。

### 从向量存储删除项

```typescript theme={null}
await vectorStore.delete({ ids: ["4"] });
```

## 查询向量存储

一旦您的向量存储创建完成，并且相关文档已添加，您很可能希望在链或智能体运行期间对其进行查询。

### 直接查询

执行简单的相似度搜索可以按以下方式完成：

```typescript theme={null}
// Optional filter
const filter = { source: "https://example.com" };

const similaritySearchResults = await vectorStore.similaritySearch("biology", 2, filter);

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
```

```text theme={null}
* The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* Mitochondria are made out of lipids [{"source":"https://example.com"}]
```

如果您想执行相似度搜索并获取相应的分数，可以运行：

```typescript theme={null}
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2, filter)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
```

```text theme={null}
* [SIM=0.165] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.148] Mitochondria are made out of lipids [{"source":"https://example.com"}]
```

### 将向量存储转换为检索器

您还可以将向量存储转换为 [检索器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)，以便在您的链中更方便地使用。

```typescript theme={null}
const retriever = vectorStore.asRetriever({
  // Optional filter
  filter: filter,
  k: 2,
});

await retriever.invoke("biology");
```

```javascript theme={null}
[
  Document {
    pageContent: 'The powerhouse of the cell is the mitochondria',
    metadata: { source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: 'Mitochondria are made out of lipids',
    metadata: { source: 'https://example.com' },
    id: undefined
  }
]
```

### 用于检索增强生成

有关如何使用此向量存储进行检索增强生成（RAG）的指南，请参阅以下部分：

* [使用 LangChain 构建 RAG 应用](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/rag.md).
* [智能体 RAG](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/agentic-rag.md)
* [检索文档](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)

***

## API 参考

有关所有 `PineconeStore` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/javascript/langchain-pinecone/PineconeStore)。

***

> 官方原文：[src/oss/javascript/integrations/vectorstores/pinecone.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/vectorstores/pinecone.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.