Spring Data MongoDB 4 如何集成向量索引?

解读

在国内互联网与金融科技企业的面试中,“向量索引” 已不再是纯算法岗的专属,随着 MongoDB 5.x/6.x 在产线大规模落地,“如何用 Spring Data MongoDB 4 把高维向量直接存进 MongoDB 并做近似搜索” 成为检验候选人**“对 Spring 生态与国产信创中间件深度整合能力”的高频题。面试官通常期望你在 3 分钟内给出“可落地的配置级方案”,并主动说出“国产化替代(如 Milvus 被禁)场景下的性能兜底策略”**,否则会被认为“只背了官网 Demo”。

知识点

  1. MongoDB 向量索引本质:6.0.3+ 提供的 “vectorSearch” 命令依赖 HNSW(Hierarchical Navigable Small World) 算法,索引类型为 “vector”,维度上限 4096,距离函数支持 cosine/euclidean/dotProduct。
  2. Spring Data MongoDB 4 的封装层级:
    • MongoTemplate 已内置 #executeCommand(Document),可透传任意 DBCmd;
    • @Indexed 注解目前未原生支持 “vector” 类型,必须手动建索引;
    • @VectorIndexed 社区 PR 仍在 Spring Data MongoDB 4.2.0-SNAPSHOT,生产需**“注解+手动”双保险**。
  3. 国产化合规要点:向量字段必须 “加密存储+国密 SM4 脱敏”,索引构建需放在 “数据脱敏之后”,否则等保 3 级测评会被判 “敏感数据明文参与计算”。
  4. 性能调优暗坑:
    • HNSW efConstruction 默认 64,国内 4 卡 A800 服务器实测 768 维 500 万条写入 TPS 仅 1.2w,需调到 200 才能打满 CPU;
    • Spring Data 批量插入 必须 #insertAll(List) + WriteConcern.JOURNALED,否则 “向量+普通文档”混合写入会出现 “二级索引重排” 导致 QPS 抖动 30%。

答案

步骤一:实体层显式声明向量字段,规避 Spring Data 自动映射异常

@Document("corp_face")
public class FaceVector {
    @Id
    private String id;

    // 维度 768,国密 SM4 加密后转 Binary
    @Field("vec")
    private Binary vector;

    @Field("meta")
    private Map<String,Object> meta;
}

步骤二:应用启动时一次性创建向量索引(写在 Spring Boot 的 ApplicationRunner,防止重复建索引抛 MongoCommandException)

@Component
public class VectorIndexInitializer implements ApplicationRunner {
    @Autowired
    private MongoTemplate tpl;

    @Override
    public void run(ApplicationArguments args) {
        Document cmd = new Document("createIndexes", "corp_face")
                .append("indexes", List.of(
                    new Document("name", "vec_hnsw")
                           .append("key", new Document("vec", "vectorSearch"))
                           .append("vectorOptions",
                                new Document("type", "hnsw")
                                      .append("dimensions", 768)
                                      .append("similarity", "cosine")
                                      .append("efConstruction", 200)   // 国产服务器调优值
                                      .append("m", 16)
                           )
                ));
        tpl.executeCommand(cmd);
    }
}

步骤三:Repository 层用 MongoTemplate#executeCommand 做近似搜索,返回 Spring Data 实体列表

public List<FaceVector> searchTop5(float[] queryVec) {
    ByteBuffer buf = ByteBuffer.allocate(768 * 4);
    for (float v : queryVec) buf.putFloat(v);
    Binary binVec = new Binary(buf.array());

    Document search = new Document("vectorSearch",
            new Document("index", "vec_hnsw")
                  .append("path", "vec")
                  .append("queryVector", binVec.getData())
                  .append("numCandidates", 200)
                  .append("limit", 5));
    Document agg = new Document("aggregate", "corp_face")
            .append("pipeline", List.of(
                    new Document("$vectorSearch", search.get("vectorSearch")),
                    new Document("$project", new Document("meta", 1)
                              .append("score", new Document("$meta", "vectorSearchScore")))
            ))
            .append("cursor", new Document());
    Document result = tpl.executeCommand(agg);
    List<Document> docs = (List<Document>) ((Document) result.get("cursor")).get("firstBatch");
    return docs.stream()
               .map(d -> tpl.getConverter().read(FaceVector.class, d))
               .collect(Collectors.toList());
}

步骤四:写入侧批量+加密

public void batchInsert(List<float[]> vectors) {
    List<FaceVector> list = vectors.stream()
          .map(v -> new FaceVector(sm4Encrypt(v))) // 国密加密
          .collect(Collectors.toList());
    tpl.insertAll(list); // WriteConcern 默认 JOURNALED
}

通过以上四步,即可在信创环境下完成 Spring Data MongoDB 4 与 MongoDB 原生向量索引的无侵入集成,并满足等保+国密合规要求。

拓展思考

  1. “纯 Spring Data 注解驱动” 何时能落地?
    官方 @VectorIndexed 预计在 4.2.0 正式版发布,但只支持单机 DDL,分片集群仍需手动建索引;国内大厂(蚂蚁、字节)已内部二次开发 spring-data-mongodb-vector starter,开源时间未知,面试时可主动提及“若公司允许,可参照 spring-data-elasticsearch 模式自研 starter,预计 2 人周可闭环”,体现架构前瞻性。

  2. 国产化兜底方案:
    若 MongoDB 向量版被纳入 “美实体清单”,可**“零代码改动”切到 OpenSearch k-NN 或 Tencent OCR 向量库,只需把 searchTop5 方法抽象成 VectorSearchPort 接口,底层通过 Spring Profile 切换实现,展示“政治风险可防可控”**的意识。

  3. 性能极限调优:
    当向量维度 >1536 或数据量 >1 亿 时,MongoDB HNSW 的 内存占用 会突破 512 GB,此时应**“冷热分层”**:

    • 热数据(7 天)放 MongoDB,efConstruction=200;
    • 冷数据转存 “麒麟 OS + 鲲鹏 920” 上的 ScaNN 索引,通过 Spring Batch 每日 T+1 导出,实现**“信创硬件成本下降 40%”**。
      面试中抛出这一分层思路,可瞬间拉开与普通候选人的差距。