如何高亮返回片段?

解读

“高亮返回片段”在国内 MongoDB 岗位面试里,通常指在查询结果中把命中的关键词或字段值做高亮标记,方便前端直接渲染。MongoDB 原生并不带搜索引擎级别的“高亮”功能,因此面试官想考察的是:

  1. 你是否清楚 MongoDB 的文本索引与 $text 操作符只能返回“匹配度”score,不会给你高亮标签;
  2. 你是否能给出工程级落地套路:用聚合管道二次扫描、正则回填标签,或干脆把高亮任务 offload 到 Elasticsearch/Solr;
  3. 你是否能权衡性能、准确性、研发成本,并给出代码级示例。

知识点

  • 文本索引(text index)与text/text/search的边界:只负责召回,不负责高亮。
  • 聚合管道中 $match + $project + $regexFind/$regexFindAll 的组合用法,可在内存里二次扫描并插入高亮标签。
  • 正则回溯风险:默认 PCRE 引擎在 32 MB 文档大小限制下可能引发 CPU 尖刺,需配合 allowDiskUse:true 及 maxTimeMS 做兜底。
  • 双写架构:MongoDB 存明细、Search 引擎(Elasticsearch/Solr/OpenSearch)做高亮,是国内互联网主流方案,需提及数据一致性策略(MQ 异步、Change Stream 同步、定时对账)。
  • Atlas Search 的 $highlight 路径:如果公司用 Atlas 云服务,可直接用 highlight 子句,但国内私有云部署无法使用,必须说明适用场景。
  • 标签转义:前端渲染前须对 <em> 或 <mark> 做 XSS 过滤,国内安全合规检查必问。

答案

示范给出一个纯 MongoDB 聚合方案,兼顾准确性与性能,适用于 4.2+ 版本:

// 1. 建立文本索引
db.articles.createIndex({ title: "text", content: "text" })

// 2. 查询并高亮关键词“分布式”
const keyword = "分布式"
const highlightTag = ["<em class='highlight'>", "</em>"]

db.articles.aggregate([
  { $match: { $text: { $search: keyword } } },
  { $addFields: {
      titleHighlight: {
        $regexFindAll: {
          input: "$title",
          regex: keyword,
          options: "i"
        }
      },
      contentHighlight: {
        $regexFindAll: {
          input: { $substrCP: ["$content", 0, 300] }, // 只取前 300 字符做摘要
          regex: keyword,
          options: "i"
        }
      }
  }},
  { $addFields: {
      titleHL: {
        $reduce: {
          input: "$titleHighlight",
          initialValue: "$title",
          in: {
            $replaceOne: {
              input: "$$value",
              find: "$$this.match",
              replacement: { $concat: [ highlightTag[0], "$$this.match", highlightTag[1] ] }
            }
          }
        }
      },
      contentHL: {
        $reduce: {
          input: "$contentHighlight",
          initialValue: { $substrCP: ["$content", 0, 300] },
          in: {
            $replaceOne: {
              input: "$$value",
              find: "$$this.match",
              replacement: { $concat: [ highlightTag[0], "$$this.match", highlightTag[1] ] }
            }
          }
        }
      }
  }},
  { $project: {
      _id: 1,
      titleHL: 1,
      contentHL: 1,
      score: { $meta: "textScore" }
  }},
  { $sort: { score: -1 } },
  { $limit: 20 }
])

关键点说明

  1. 先用 $text 过滤,利用索引降低扫描行数;
  2. $regexFindAll 只在召回集上做二次正则,避免全表回溯;
  3. 对长文本先 $substrCP 截取前 300 字符,防止 16 MB BSON 大小限制;
  4. 用 $replaceOne 循环替换,保证大小写不敏感且只替换命中词;
  5. 最终返回 titleHL/contentHL 两个高亮字段,前端可直接 v-html 渲染。

拓展思考

  1. 性能天花板:当并发 QPS > 1 k、单文档 > 1 MB 时,纯 MongoDB 方案 CPU 会飙到 80%+,此时应把高亮逻辑 offload 到 Elasticsearch,并通过 Change Stream + Kafka 保证 MongoDB→ES 的秒级同步。
  2. 多语言同义词:国内内容类 App 常做“同义词高亮”,可在 ES 里配置 synonym_filter,MongoDB 侧仅保留主词,降低索引体积。
  3. 敏感词过滤:高亮前须先过一遍 国审敏感词库,避免把违规词高亮放大;可在聚合管道前加 $match 黑名单,或直接在 Change Stream 阶段打标。
  4. 成本权衡:Atlas Search 按节点计费,国内私有云落地成本≈0.6 元/小时/节点,若数据量 < 500 GB 且查询并发 < 200,纯 MongoDB 聚合即可 cover;超过阈值再考虑双写。