Skip to main content
兼容性:仅适用于 Node.js。你仍然可以通过将 runtime 变量设置为 nodejs 来创建使用 MongoDB 的 Next.js API 路由,如下所示:export const runtime = "nodejs";更多信息,请参阅 Next.js 文档中的边缘运行时
本指南提供了快速入门 MongoDB Atlas 向量存储 的概述。有关 MongoDBAtlasVectorSearch 所有功能和配置的详细文档,请参阅 API 参考

概述

集成详情

设置

要使用 MongoDB Atlas 向量存储,你需要配置一个 MongoDB Atlas 集群并安装 @langchain/mongodb 集成包。

初始集群配置

要创建 MongoDB Atlas 集群,请访问 MongoDB Atlas 网站,如果没有账户请先创建一个。 按照提示创建并命名一个集群,然后在 Database 下找到它。选择 Browse Collections 并创建一个空白集合或使用提供的示例数据。 注意:创建的集群必须是 MongoDB 7.0 或更高版本。

创建索引

配置集群后,你需要在要搜索的集合字段上创建索引。 切换到 Atlas Search 选项卡并点击 Create Search Index。确保选择 Atlas Vector Search - JSON Editor,然后选择适当的数据库和集合,并将以下内容粘贴到文本框中:
{
  "fields": [
    {
      "numDimensions": 1536,
      "path": "embedding",
      "similarity": "euclidean",
      "type": "vector"
    }
  ]
}
注意,维度属性应与你使用的嵌入维度匹配。例如,Cohere 嵌入有 1024 维,而默认的 OpenAI 嵌入有 1536 维: 注意:默认情况下,向量存储期望索引名称为 default,索引集合字段名称为 embedding,原始文本字段名称为 text。你应该使用与索引名称集合模式匹配的字段名初始化向量存储,如下所示。 最后,继续构建索引。

嵌入

本指南还将使用 OpenAI 嵌入,这需要你安装 @langchain/openai 集成包。你也可以使用 其他支持的嵌入模型

安装

安装以下包:
npm install @langchain/mongodb mongodb @langchain/openai @langchain/core

凭证

完成上述步骤后,从 Mongo 仪表板的 Connect 按钮设置 MONGODB_ATLAS_URI 环境变量。你还需要数据库名称和集合名称:
process.env.MONGODB_ATLAS_URI = "your-atlas-URL";
process.env.MONGODB_ATLAS_COLLECTION_NAME = "your-atlas-db-name";
process.env.MONGODB_ATLAS_DB_NAME = "your-atlas-db-name";
如果你在本指南中使用 OpenAI 嵌入,还需要设置你的 OpenAI 密钥:
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
如果你想获取模型调用的自动追踪,还可以通过取消注释以下内容来设置 LangSmith API 密钥:
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"

实例化

按照上述步骤设置集群后,你可以按如下方式初始化向量存储:
import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
import { OpenAIEmbeddings } from "@langchain/openai";
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_ATLAS_URI || "");
const collection = client.db(process.env.MONGODB_ATLAS_DB_NAME)
  .collection(process.env.MONGODB_ATLAS_COLLECTION_NAME);

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

const vectorStore = new MongoDBAtlasVectorSearch(embeddings, {
  collection: collection,
  indexName: "vector_index", // Atlas 搜索索引的名称。默认为 "default"
  textKey: "text", // 包含原始内容的集合字段名称。默认为 "text"
  embeddingKey: "embedding", // 包含嵌入文本的集合字段名称。默认为 "embedding"
});

管理向量存储

向向量存储添加项目

你现在可以将文档添加到向量存储:
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "细胞的动力源是线粒体",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "建筑物由砖块构成",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "线粒体由脂质构成",
  metadata: { source: "https://example.com" }
};

const document4: Document = {
  pageContent: "2024 年奥运会在巴黎举行",
  metadata: { source: "https://example.com" }
}

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

await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });
[ '1', '2', '3', '4' ]
注意:添加文档后,需要短暂延迟才能查询。 添加具有相同 id 的文档将更新现有文档。

从向量存储删除项目

await vectorStore.delete({ ids: ["4"] });

查询向量存储

创建向量存储并添加相关文档后,你可能希望在链或代理运行时查询它。

直接查询

执行简单的相似性搜索如下:
const similaritySearchResults = await vectorStore.similaritySearch("生物学", 2);

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* 细胞的动力源是线粒体 [{"_id":"1","source":"https://example.com"}]
* 线粒体由脂质构成 [{"_id":"3","source":"https://example.com"}]

过滤

MongoDB Atlas 支持对其他字段进行预过滤。这要求你通过更新最初创建的索引来定义计划过滤的元数据字段。示例如下:
{
  "fields": [
    {
      "numDimensions": 1024,
      "path": "embedding",
      "similarity": "euclidean",
      "type": "vector"
    },
    {
      "path": "source",
      "type": "filter"
    }
  ]
}
上面,fields 中的第一项是向量索引,第二项是要过滤的元数据属性。属性的名称是 path 键的值。因此,上述索引允许我们搜索名为 source 的元数据字段。 然后,在你的代码中可以使用 MQL 查询操作符 进行过滤。 以下示例说明了这一点:
const filter = {
  preFilter: {
    source: {
      $eq: "https://example.com",
    },
  },
}

const filteredResults = await vectorStore.similaritySearch("生物学", 2, filter);

for (const doc of filteredResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* 细胞的动力源是线粒体 [{"_id":"1","source":"https://example.com"}]
* 线粒体由脂质构成 [{"_id":"3","source":"https://example.com"}]

返回分数

如果你想执行相似性搜索并获取相应的分数,可以运行:
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("生物学", 2, filter)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
* [SIM=0.374] 细胞的动力源是线粒体 [{"_id":"1","source":"https://example.com"}]
* [SIM=0.370] 线粒体由脂质构成 [{"_id":"3","source":"https://example.com"}]

转换为检索器查询

你也可以将向量存储转换为 检索器,以便在链中更轻松地使用。
const retriever = vectorStore.asRetriever({
  // 可选过滤器
  filter: filter,
  k: 2,
});
await retriever.invoke("生物学");
[
  Document {
    pageContent: '细胞的动力源是线粒体',
    metadata: { _id: '1', source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: '线粒体由脂质构成',
    metadata: { _id: '3', source: 'https://example.com' },
    id: undefined
  }
]

用于检索增强生成

有关如何使用此向量存储进行检索增强生成 (RAG) 的指南,请参阅以下部分:

关闭连接

完成后请确保关闭客户端实例,以避免资源过度消耗:
await client.close();

API 参考

有关 MongoDBAtlasVectorSearch 所有功能和配置的详细文档,请参阅 API 参考