> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.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` [向量存储](/oss/javascript/integrations/vectorstores) 的概览。

## 概览

### 集成详情

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

## 设置

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

本指南还将使用 [OpenAI 嵌入](/oss/javascript/integrations/embeddings/openai)，这需要你安装 `@langchain/openai` 集成包。如果你愿意，也可以使用[其他支持的嵌入模型](/oss/javascript/integrations/embeddings)。

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install langchain @langchain/openai @langchain/core
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add langchain @langchain/openai @langchain/core
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add langchain @langchain/openai @langchain/core
  ```
</CodeGroup>

### 凭证

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

如果你在本指南中使用 OpenAI 嵌入，你还需要设置你的 OpenAI 密钥：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

如果你想获得模型调用的自动跟踪，你也可以通过取消注释以下内容来设置你的 [LangSmith](/langsmith/home) API 密钥：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* 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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* [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"}]
```

### 通过转换为检索器进行查询

你也可以将向量存储转换为 [检索器](/oss/javascript/langchain/retrieval)，以便在你的链中更轻松地使用：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const retriever = vectorStore.asRetriever({
  // 可选过滤器
  filter: filter,
  k: 2,
});

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

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[
  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={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const mmrRetriever = vectorStore.asRetriever({
  searchType: "mmr",
  searchKwargs: {
    fetchK: 10,
  },
  // 可选过滤器
  filter: filter,
  k: 2,
});

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

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[
  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 应用](/oss/javascript/langchain/rag)。
* [代理式 RAG](/oss/javascript/langgraph/agentic-rag)
* [检索文档](/oss/javascript/langchain/retrieval)

***

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/vectorstores/memory.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
