记录一下那天晚上的排查过程。Atlas 7.0 集群上按文档建了 search index,字段类型 vector、path embedding、numDimensions 1024、similarity cosine,pymongo 4.7 调 aggregate 的 $vectorSearch 报 PlanExecutor error during aggregation :: caused by :: index not found,刷新页面索引状态仍是 BUILDING。
刚开始盯着「索引建在另一个 database.collection 上」,折腾了半个多小时,排掉了。
这类报错背后常见的原因有几处,逐个排除就行。索引还在构建,$vectorSearch 要求状态 READY。也可能是聚合里写的 index 名与创建时的大小写不一致。
少数情况下是免费层集群所在区域不支持向量索引。
动手时先列出集合上的搜索索引与状态
python -c "from pymongo import MongoClient;c=MongoClient('mongodb+srv://u:p@x/test');print(list(c['test']['chunks'].list_search_indexes()))"
再往下按返回的 name 原样写进聚合
python -c "from pymongo import MongoClient;c=MongoClient('mongodb+srv://u:p@x/test');print(list(c['test']['chunks'].aggregate([{'\$vectorSearch':{'index':'vec_idx','path':'embedding','queryVector':[0.1]*1024,'numCandidates':100,'limit':5}}])))"
索引迟迟不 READY 就删除重建
python -c "from pymongo import MongoClient;c=MongoClient('mongodb+srv://u:p@x/test');c['test']['chunks'].drop_search_index('vec_idx')"
等前面都确认过,再重建时显式指定相似度与维度
python -c "from pymongo import MongoClient;from pymongo.operations import SearchIndexModel;c=MongoClient('mongodb+srv://u:p@x/test');c['test']['chunks'].create_search_index(SearchIndexModel({'fields':[{'type':'vector','path':'embedding','numDimensions':1024,'similarity':'cosine'}]},name='vec_idx'))"
改完先别撤,确认这几项。list_search_indexes 返回 status READY,$vectorSearch 能返回五条并带 searchScore,聚合不再抛 index not found。
容易忽略的是,Atlas 的向量索引是异步构建的,数据量大时要等十几分钟,代码里最好加一个状态轮询再放流量,别把 BUILDING 当成索引不存在去反复重建。线上能稳定复现的问题都不算难,难的是只在大流量下才出现的那种。
