如何创建 autocomplete 索引?

解读

在国内互联网与政企项目中,搜索框联想(autocomplete) 是高频交互场景,MongoDB 4.2+ 引入的 Atlas Search(基于 Lucene) 提供了开箱即用的 autocomplete 类型索引,可在毫秒级返回前缀/中缀/模糊匹配结果。面试官问“如何创建”,既考察你对 Search Index DDL 的熟练度,也暗含对 分词器、语言环境、同义词、性能调优 的落地经验。回答时务必区分 Atlas Search 索引 与 普通复合索引,并给出 DSL 示例 与 参数含义,否则会被追问“为什么不用正则”。

知识点

  1. 适用场景:仅适用于 Atlas M10 及以上集群 或 自建 Enterprise + MongoDB Connector for Lucene;普通社区版无法使用。
  2. 核心类型:autocomplete 字段类型,内部使用 edge N-gram + 低频词剪枝,支持 Unicode 分词 与 中文(cjk)。
  3. 最小粒度:必须显式指定 tokenization: "edgeGram" 或 "nGram",并配置 minGrams(默认 2)与 maxGrams(默认 7),中文建议 1-10,避免单字被截断。
  4. 多语言:国内业务需同时支持 简体、繁体、拼音、同义词(如“深圳”≈“Shenzhen”),需在 analyzer 里串联 icu_tokenizer + lowercase + synonym_graph。
  5. 性能红线:
    • 单个索引 最大 4 MB / 文档,长文本需 前置截断;
    • maxGrams 与 minGrams 差值 ≤ 8,否则内存爆炸;
    • 必须 覆盖查询(project: {title: 1}),避免回表。
  6. 权限:需要 Atlas Project Owner 或 custom role 含 “searchIndex”* 权限;线下政企机房需 Ops Manager 4.4+ 才有 Search 菜单。

答案

步骤一:在 Atlas Web 控制台 → Search → Create Index → JSON Editor 粘贴:

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "brandName": {
        "type": "autocomplete",
        "tokenization": "edgeGram",
        "minGrams": 1,
        "maxGrams": 10,
        "foldDiacritics": true,
        "analyzer": "lucene.standard"
      }
    }
  }
}

步骤二:点击 Create Index,命名 idx_brand_autocomplete。
步骤三:在 Shell 验证:

db.products.aggregate([
  {
    $search: {
      autocomplete: {
        query: "小米",
        path: "brandName",
        tokenOrder: "any"   // 支持乱序匹配
      }
    }
  },
  { $project: { brandName: 1, _id: 0 } },
  { $limit: 5 }
])

返回结果即完成。
注意:若使用 Node.js 驱动,需 retryWrites=true 且 readPreference=primaryPreferred,避免读写分离导致延迟。

拓展思考

  1. 政企私有化无法使用 Atlas Search 时,可退化为 复合前缀索引 + 正则(^pattern),但需 禁用区分大小写(collation: {locale: "zh", strength: 1})并 限制输入长度 ≤ 20 字符,否则 COLLSCAN 导致 CPU 飙高。
  2. 高并发场景(如 618 大促)需 预热索引:提前用 $searchMeta 统计热点词,写入 Redis BloomFilter 做 二级缓存,将 MongoDB 查询 QPS 从 8w 降至 1.2w。
  3. 多字段联合联想(品牌+品类)可建 nested autocomplete,把对象 {brand: "小米", category: "手机"} 序列化为 "小米 手机" 存入新字段,再用 multi path search,避免 $or 带来的 score 衰减。
  4. 合规要求(等保 3)需开启 Atlas PrivateLink 或 自建 VPC 对等连接,确保 搜索流量不经过公网;同时 Search Index 定义 需纳入 配置库(GitOps),通过 Atlas Admin API + Terraform 实现 索引即代码,方便 灾备切换 时 一键重建。