以编程方式使用文档

本指南提供了快速入门 MongoDB Atlas 向量存储的概述。要获取所有 MongoDBAtlasVectorSearch 功能和配置的详细文档,请前往 API 参考.

概述

集成详情

Python 支持版本
MongoDBAtlasVectorSearch@langchain/mongodb!NPM - 版本

设置

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

初始集群配置

要创建 MongoDB Atlas 集群,请访问 MongoDB Atlas 网站 并创建一个账户(如果你还没有的话)。

按提示创建并命名一个集群,然后在 Database下找到它。选择 Browse Collections 并创建一个空白集合或使用提供的示例数据创建。

Note: 手动嵌入模式要求集群必须是 MongoDB 7.0 或更高版本。自动嵌入模式需要 MongoDB 8.2 或更高版本.

创建向量搜索索引

配置集群后,在集合上创建一个向量搜索索引。你可以通过以下方式执行此操作: Atlas, Compass, or MongoDB Shell。索引定义取决于你使用的嵌入模式。

手动嵌入 (MongoDB 7.0+):你在客户端嵌入文档并将向量存储在一个字段中。使用以下定义,根据需要调整 numDimensions 以匹配你的嵌入模型。

{
  "name": "index_name",
  "type": "vectorSearch",
  "definition": {
    "fields": [
      {
        "numDimensions": 1536,
        "path": "embedding",
        "similarity": "euclidean",
        "type": "vector"
      }
    ]
  }
}

自动嵌入 (MongoDB 8.2+):MongoDB 使用 Voyage AI 模型在服务端生成嵌入。使用 autoEmbed 字段类型并指定模型:

{
  "name": "index_name",
  "type": "vectorSearch",
  "definition": {
    "fields": [
      {
        "type": "autoEmbed",
        "modality": "text",
        "path": "textContent",
        "model": "voyage-4"
      }
    ]
  }
}

默认情况下,向量存储从一个名为 text 的文本字段读取,并在(手动模式下)将向量写入一个名为 embedding的字段。设置 textKeyembeddingKey 以匹配你的索引。

const vectorStore = new MongoDBAtlasVectorSearch(
  embeddings,                  // omit in auto embedding mode
  {
    collection,
    indexName: "index_name",
    textKey: "textContent",    // document field where raw text is stored
    embeddingKey: "embedding", // matches "path" (omit in auto embedding mode)
  }
);

继续构建索引。

嵌入向量

In **手动嵌入模式**,您需要提供一个嵌入模型并在客户端嵌入文档。本指南使用 OpenAI 嵌入向量 作为示例。您也可以使用 其他支持的嵌入模型.

In **自动嵌入模式**,MongoDB Atlas 在服务端处理嵌入向量的生成。无需客户端嵌入向量包。

安装

Manual embedding

安装核心包以及一个嵌入向量提供者:

    npm install @langchain/mongodb mongodb @langchain/core @langchain/openai
    
    yarn add @langchain/mongodb mongodb @langchain/core @langchain/openai
    
    pnpm add @langchain/mongodb mongodb @langchain/core @langchain/openai
    

Automated embedding

只需安装核心包和 MongoDB 驱动程序:

    npm install @langchain/mongodb mongodb @langchain/core
    
    yarn add @langchain/mongodb mongodb @langchain/core
    
    pnpm add @langchain/mongodb mongodb @langchain/core
    

凭证

完成上述操作后,设置 MONGODB_ATLAS_URI 环境变量,从 Mongo 的仪表板的 Connect 按钮获取。您还需要提供数据库名和集合名:

process.env.MONGODB_ATLAS_URI = "your-atlas-URL";
process.env.MONGODB_ATLAS_COLLECTION_NAME = "your-atlas-collection-name";
process.env.MONGODB_ATLAS_DB_NAME = "your-atlas-db-name";

如果您正在使用 OpenAI 的手动嵌入模式,也需要设置您的 OpenAI 密钥:

process.env.OPENAI_API_KEY = "YOUR_API_KEY";

在自动嵌入模式下,不需要额外的 API 密钥——MongoDB Atlas 使用索引中配置的模型处理嵌入向量的生成。

如果您想获取模型调用的自动追踪,也可以设置您的 LangSmith API 密钥,取消下方注释即可:

// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"

初始化

设置好集群和索引后,初始化向量存储。根据使用的是手动还是自动嵌入,构造函数有两种形式。

Manual embedding

将嵌入向量实例作为第一个参数传入:

    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,
      indexName: "vector_index", // Defaults to "default"
      textKey: "text",           // Defaults to "text"
      embeddingKey: "embedding", // Defaults to "embedding"
    });
    

Automated embedding

仅传入配置对象(无需嵌入向量参数)。

    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 vectorStore = new MongoDBAtlasVectorSearch({
      collection,
      indexName: "default", // Must match the index name in your Atlas cluster
    });
    

管理向量存储

向向量存储添加内容

现在可以向向量存储添加文档了:

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"] });

添加具有相同 id 的文档将更新现有文档。

从向量存储删除内容

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

查询向量存储

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

直接查询

执行简单的相似性搜索可以按如下方式进行:

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

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* Mitochondria are made out of lipids [{"_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("biology", 2, filter);

for (const doc of filteredResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]

返回分数

如果你想执行相似性搜索并获取相应的分数,可以运行:

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)}]`);
}
* [SIM=0.374] The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* [SIM=0.370] Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]

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

你也可以将向量存储转换为 检索器 以便在链中更方便地使用。

const retriever = vectorStore.asRetriever({
  // Optional filter
  filter: filter,
  k: 2,
});
await retriever.invoke("biology");
[
  Document {
    pageContent: 'The powerhouse of the cell is the mitochondria',
    metadata: { _id: '1', source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: 'Mitochondria are made out of lipids',
    metadata: { _id: '3', source: 'https://example.com' },
    id: undefined
  }
]

用于检索增强生成

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

关闭连接

完成操作后请确保关闭客户端实例,以避免过多的资源消耗:

await client.close();

API 参考

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