> ## 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.

# MemoryVectorStore 集成

> 使用 LangChain JavaScript 集成 MemoryVectorStore

LangChain 提供了一个内存中的、临时的向量存储，它将嵌入存储在内存中，并对最相似的嵌入进行精确的线性搜索。默认的相似度度量是余弦相似度，但可以更改为 [ml-distance](https://mljs.github.io/distance/modules/similarity.html) 支持的任何相似度度量。

由于它是为演示设计的，因此目前还不支持 ID 或删除。

本指南提供了快速入门 `MemoryVectorStore` [向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores.md) 的概述。

## 概述

### 集成细节

| 类 | 包 | Python 支持 | 版本 |
| :- | :- | :-: | :-: |
| `MemoryVectorStore` | [`langchain`](https://www.npmjs.com/package/langchain) | ❌ | ![NPM - Version](https://img.shields.io/npm/v/langchain?style=flat-square\&label=%20&) |

## 设置

要使用内存中的向量存储，您需要安装 `langchain` 包：

本指南还将使用 [OpenAI 嵌入](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/openai.md)，这需要您安装 `@langchain/openai` 集成包。如果您希望，也可以使用 [其他支持的嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。

```bash npm theme={null}
npm install langchain @langchain/openai @langchain/core
```

```bash yarn theme={null}
yarn add langchain @langchain/openai @langchain/core
```

```bash pnpm theme={null}
pnpm add langchain @langchain/openai @langchain/core
```

### 凭证

使用内存中的向量存储不需要任何凭证。

如果您在本指南中使用 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 { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";

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

const vectorStore = new MemoryVectorStore(embeddings);
```

## 管理向量存储

### 向向量存储添加项

```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 documents = [document1, document2, document3];

await vectorStore.addDocuments(documents);
```

## 查询向量存储

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

### 直接查询

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

```typescript theme={null}
const filter = (doc) => doc.metadata.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"}]
```

过滤器是可选的，必须是一个输入文档并返回 `true` 或 `false` 的谓词函数，具体取决于文档是否应该返回。

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

```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
  }
]
```

### 最大边际相关性

此向量存储还支持最大边际相关性 (MMR)，这是一种技术，它首先使用经典相似度搜索获取更多结果（由 `searchKwargs.fetchK` 指定），然后重新排序以增加多样性，并返回顶部 `k` 个结果。这有助于防止冗余信息：

```typescript theme={null}
const mmrRetriever = vectorStore.asRetriever({
  searchType: "mmr",
  searchKwargs: {
    fetchK: 10,
  },
  // Optional filter
  filter: filter,
  k: 2,
});

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

```javascript theme={null}
[
  Document {
    pageContent: 'The powerhouse of the cell is the mitochondria',
    metadata: { source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: 'Buildings are made out of brick',
    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)

***


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