You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB Atlas向量搜索返回全部文档问题排查与解决

问题解决:MongoDB向量搜索返回全部文档而非过滤结果

问题背景

已在MongoDB Atlas创建名为LocationSemanticSearch的向量索引,对应Flask API调用/get-properties接口执行向量搜索时,返回集合内全部文档而非语义匹配的过滤结果。

核心排查点及修复方案

1. 补全文档的向量字段(最关键原因)

当前/add-property接口插入文档时,并未生成并存储索引依赖的addr_embedding_hf向量字段——缺失该字段会导致向量搜索无法进行语义匹配,最终返回全部文档。

修复代码(修改setProperties函数):

# 原代码:property_dict = property.to_dict()
# 修改为:
property_dict = property.to_dict()
# 新增:生成地址的向量嵌入并添加到文档
property_dict["addr_embedding_hf"] = hf.generate_embedding(data.get('address'))

2. 校验查询向量维度与索引匹配

确认hf.generate_embedding(q)生成的向量维度为384维,与索引Schema中numDimensions: 384完全一致。维度不匹配会直接导致向量搜索失效。

可在getProperties函数中添加维度校验:

query_vector = hf.generate_embedding(q)
if len(query_vector) != 384:
    return jsonify({'error': 'Query vector dimension mismatch'}), 400

3. 确认向量索引的集合与配置正确性

  • 确保LocationSemanticSearch索引创建在Apnahood数据库的houses集合上;
  • 索引的path字段addr_embedding_hf与文档中的字段名完全一致(MongoDB字段名大小写敏感)。

4. 优化$vectorSearch参数

  • 确保index参数值与向量索引名称完全匹配;
  • numCandidates值不要超过集合内文档总数,可动态设置避免无效计算:
    "numCandidates": min(300, house_collection.count_documents({})),
    

修复后的完整/get-properties接口

@server_bp.route('/get-properties', methods=['POST'])
def getProperties():
    data = request.get_json()
    q = data.get('query')

    if not q:
        return jsonify({'error': 'Location parameter is required'}), 400

    try:
        query_vector = hf.generate_embedding(q)
        # 校验向量维度
        if len(query_vector) != 384:
            return jsonify({'error': 'Query vector dimension mismatch'}), 400
            
        properties = house_collection.aggregate([{
            "$vectorSearch": {
                "queryVector": query_vector,
                "path": "addr_embedding_hf",
                "limit": 8,
                "index": "LocationSemanticSearch",
                "numCandidates": min(300, house_collection.count_documents({})),
            }
        }])
        properties_list = []
        for property in properties:
            del property["_id"]
            del property["addr_embedding_hf"]
            properties_list.append(property)
        return jsonify(properties_list), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

内容的提问来源于stack exchange,提问作者Dm420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:45:17