资讯动态

MongoDB 全文索引与向量搜索:Atlas Search、文本检索与 RAG 场景应用

发布时间:2026/9/10 10:51:17 来源:尧图企业网站定制
MongoDB 全文索引与向量搜索Atlas Search、文本检索与 RAG 场景应用MongoDB Atlas Search 提供了强大的全文索引和向量搜索能力支持自然语言处理和语义检索。本文详细介绍如何利用 Atlas Search 构建高效的文本检索系统并将其应用于 RAG检索增强生成场景提升大语言模型回答的准确性和相关性。1. MongoDB Atlas Search 概述与基本概念MongoDB Atlas Search 是 MongoDB Atlas 云服务平台上的全文搜索功能基于 Apache Lucene 构建。它提供了丰富的查询操作符和聚合管道功能支持对文本、数值、日期等多种数据类型的高效搜索。Atlas Search 的核心概念包括索引Index定义如何在集合上构建搜索功能包括字段映射、分析器设置等查询管道Query Pipeline由多个搜索阶段组成每个阶段处理特定的搜索任务分析器Analyzer处理文本的分词、过滤和标准化操作符Operators用于定义搜索条件和结果排序Atlas Search 支持的搜索类型包括文本搜索text search关键词匹配、短语搜索、模糊匹配等向量搜索vector search基于向量相似度的语义搜索数值和日期搜索范围查询、比较查询等地理空间搜索基于位置的查询Atlas Search 的优势无缝集成与 MongoDB 数据库无缝集成无需额外的搜索引擎高性能利用 Lucene 的强大搜索能力提供亚毫秒级的响应时间丰富的功能支持复杂查询、聚合、排序等功能可扩展性自动适应数据增长支持水平扩展易于使用提供直观的 API 和管理界面2. 全文索引创建与使用创建全文索引是使用 Atlas Search 的第一步。索引定义了如何在文档上构建搜索功能包括要索引的字段、使用的分析器、搜索配置等。2.1 创建搜索索引通过 Atlas UI 或 MongoDB API 创建搜索索引// 创建搜索索引的示例 { mappings: { dynamic: false, fields: { description: { type: document, fields: [ { type: string, analyzer: lucene.standard }, { type: token, analyzer: lucene.english } ] }, title: { type: string, analyzer: lucene.standard }, category: { type: string } } } }2.2 执行全文搜索使用$search聚合管道进行全文搜索// 基本全文搜索示例 db.collection.aggregate([ { $search: { text: { query: MongoDB 数据库, path: description } } }, { $project: { title: 1, description: 1, score: { $meta: searchScore } } } ]);2.3 高级全文搜索功能Atlas Search 提供了多种高级搜索功能// 复合查询示例 db.collection.aggregate([ { $search: { compound: { must: [ { text: { query: MongoDB, path: title } }, { text: { query: 数据库, path: description } } ], should: [ { text: { query: Atlas, path: category } } ], minimumShouldMatch: 1 } } }, { $sort: { score: { $meta: searchScore } } } ]);2.4 全文搜索最佳实践选择合适的分析器根据语言和需求选择不同的文本分析器合理设计索引结构避免过度索引提高查询性能使用$project限制返回字段减少网络传输数据量添加排序和分页优化用户体验监控查询性能使用 Atlas 的性能分析工具优化查询3. 向量搜索实现与优化向量搜索是 Atlas Search 的重要功能之一它允许基于语义相似性进行搜索而不仅仅是关键词匹配。3.1 创建向量搜索索引// 向量搜索索引配置 { mappings: { fields: [ { type: vector, numDimensions: 1536, // 向量维度根据嵌入模型确定 path: embedding, similarity: cosine // 相似度计算方法 } ] } }3.2 执行向量搜索// 向量搜索示例 db.collection.aggregate([ { $vectorSearch: { queryVector: [0.1, 0.2, ...], // 查询向量 path: embedding, // 向量字段路径 numCandidates: 100, // 候选数量 limit: 10, // 返回结果数量 similarity: 0.7 // 相似度阈值 } }, { $project: { title: 1, content: 1, score: { $meta: vectorSearchScore } } } ]);3.3 混合搜索文本向量结合文本搜索和向量搜索提高检索的准确性和相关性// 混合搜索示例 db.collection.aggregate([ { $search: { compound: { must: [ { text: { query: MongoDB Atlas, path: [title, description] } } ], should: [ { vector: { queryVector: [0.1, 0.2, ...], path: embedding, numCandidates: 100 } } ] } } }, { $addFields: { textScore: { $meta: searchScore }, vectorScore: { $meta: vectorSearchScore } } }, { $addFields: { combinedScore: { $avg: [$textScore, $vectorScore] } } }, { $sort: { combinedScore: -1 } }, { $limit: 10 } ]);3.4 向量搜索优化策略向量维度选择根据嵌入模型选择合适的向量维度相似度算法选择余弦相似度cosine适合方向相似性欧氏距离euclidean适合绝对距离点积dotProduct适合已归一化向量候选数量调整平衡查询精度和性能索引结构优化考虑使用 HNSW 等近似最近邻算法定期更新向量确保向量数据与实际内容一致4. 文本检索与 RAG 场景应用Atlas Search 的文本检索和向量搜索能力使其成为实现 RAG检索增强生成的理想选择。4.1 RAG 架构概述RAG 系统通常包含以下组件文档存储与索引文档检索系统检索结果处理语言模型生成Atlas Search 可以作为 RAG 系统中的检索组件提供高效的文档检索能力。4.2 文档索引与处理流程原始文档文档预处理文本分块生成文本嵌入存储到MongoDB创建Atlas Search索引用户查询查询处理向量搜索文本搜索合并结果排序与过滤返回相关文档4.3 RAG 实现示例// 文档索引函数 async function indexDocument(doc) { // 1. 文本分块 const chunks chunkText(doc.content, 500); // 2. 生成嵌入向量 const embeddings await generateEmbeddings(chunks); // 3. 存储到 MongoDB const documents chunks.map((chunk, i) ({ title: doc.title, content: chunk, embedding: embeddings[i], metadata: { source: doc.source, chunkIndex: i, totalChunks: chunks.length } })); await db.collection(documents).insertMany(documents); // 4. 确保搜索索引已创建 await createSearchIndex(); } // 检索函数 async function retrieveDocuments(query, limit 5) { // 生成查询嵌入 const queryEmbedding await generateEmbeddings([query]); // 执行混合搜索 const results await db.collection(documents).aggregate([ { $search: { compound: { must: [ { text: { query: query, path: [content, title], fuzzy: {} } } ], should: [ { vector: { queryVector: queryEmbedding[0], path: embedding, numCandidates: 100 } } ] } } }, { $addFields: { textScore: { $meta: searchScore }, vectorScore: { $meta: vectorSearchScore } } }, { $addFields: { combinedScore: { $avg: [$textScore, $vectorScore] } } }, { $sort: { combinedScore: -1 } }, { $limit: limit } ]).toArray(); return results; } // RAG 查询处理函数 async function processRAGQuery(userQuery) { // 1. 检索相关文档 const relevantDocs await retrieveDocuments(userQuery); // 2. 构建提示 const prompt buildPrompt(userQuery, relevantDocs); // 3. 生成回答 const response await generateResponse(prompt); return { answer: response, sources: relevantDocs }; }4.4 RAG 场景优化策略文档分块策略根据内容相关性进行智能分块保持语义完整性避免关键信息被截断考虑重叠分块确保连续性嵌入模型选择根据语言特点选择合适的模型中文、英文等考虑模型大小与性能的平衡评估模型在不同任务上的表现检索策略优化调整文本搜索与向量搜索的权重实现多阶段检索提高精度添加过滤条件提高相关性结果排序优化结合多种评分因素考虑文档新鲜度和重要性实现个性化排序缓存策略对常见查询实现缓存对相似查询实现近似匹配定期更新缓存数据5. 实战示例与最佳实践5.1 最小可用示例以下是一个完整的最小示例展示如何使用 Atlas Search 实现简单的 RAG 系统// 初始化 MongoDB 客户端 const { MongoClient } require(mongodb); // 连接到 Atlas 集群 const client new MongoClient(process.env.MONGODB_URI); await client.connect(); const db client.db(rag_db); const collection db.collection(documents); // 创建搜索索引 async function createSearchIndex() { try { await collection.dropSearchIndex(default); } catch (e) { // 忽略索引不存在的错误 } const index { mappings: { fields: [ { type: vector, numDimensions: 1536, path: embedding, similarity: cosine }, { type: document, fields: [ { type: string, analyzer: lucene.english, search: { analyzer: lucene.english }, stored: true } ], path: content } ] } }; await collection.createSearchIndex(index); } // 索引文档 async function indexDocument(title, content) { // 生成嵌入向量这里使用模拟函数实际应调用嵌入服务 const embedding generateMockEmbedding(content); await collection.insertOne({ title, content, embedding, indexedAt: new Date() }); } // 搜索文档 async function searchDocuments(query) { // 生成查询嵌入 const queryEmbedding generateMockEmbedding(query); const results await collection.aggregate([ { $search: { compound: { must: [ { text: { query: query, path: content, fuzzy: {} } } ], should: [ { vector: { queryVector: queryEmbedding, path: embedding, numCandidates: 100 } } ] } } }, { $addFields: { textScore: { $meta: searchScore }, vectorScore: { $meta: vectorSearchScore } } }, { $addFields: { combinedScore: { $avg: [$textScore, $vectorScore] } } }, { $sort: { combinedScore: -1 } }, { $limit: 5 } ]).toArray(); return results; } // 模拟嵌入函数实际应用中应替换为真实的嵌入服务 function generateMockEmbedding(text) { // 这里返回一个模拟向量实际应调用如 OpenAI、Sentence-BERT 等服务 return Array(1536).fill(0).map(() Math.random()); } // 使用示例 async function main() { // 创建索引 await createSearchIndex(); // 索引示例文档 await indexDocument(MongoDB 简介, MongoDB 是一个开源的 NoSQL 数据库使用文档存储模型支持灵活的数据结构。); await indexDocument(Atlas Search 功能, Atlas Search 是 MongoDB Atlas 上的全文搜索功能支持文本搜索和向量搜索。); await indexDocument(向量搜索应用, 向量搜索可用于语义搜索、推荐系统和 RAG 应用场景。); // 执行搜索 const results await searchDocuments(MongoDB 的搜索功能); console.log(搜索结果:, results); // 关闭连接 await client.close(); } main().catch(console.error);5.2 最佳实践与注意事项索引设计只索引需要搜索的字段避免过度索引合理设置向量维度与嵌入模型匹配选择合适的相似度计算方法查询优化使用limit和sort控制返回结果合理设置numCandidates平衡性能和精度使用$project减少返回数据量性能监控使用 Atlas 的性能分析工具监控查询性能定期检查索引大小和碎片情况监控资源使用情况及时调整安全考虑实施适当的访问控制对敏感数据实施加密定期备份重要数据成本优化根据查询频率调整索引策略使用压缩减少存储成本选择合适的实例类型和配置错误处理实现重试机制处理临时故障对异常情况进行日志记录提供有意义的错误信息通过遵循这些最佳实践可以构建高效、可靠、经济实用的 MongoDB 全文索引与向量搜索系统充分发挥 Atlas Search 在文本检索和 RAG 场景中的优势。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价