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

为何我的Firestore向量嵌入搜索无返回结果?

问题:Firestore向量查询无结果返回(无报错)

背景信息

已按照Firebase文档创建复合向量索引:

gcloud alpha firestore indexes composite create \
--project=[Insert Project Name Here]
--collection-group=elements --query-scope=COLLECTION \
--field-config=vector-config='{"dimension":"1536","flat": "{}"}',field-path=embedding

索引创建成功,可通过gcloud firestore indexes composite describe [Insert Index Name Here]查看。

使用以下onCall云函数执行向量查询:

export const vectorSearch = functions.https.onCall(async (data, context) => {
  const { query, quantity } = data;

  if (!query) {
    throw new functions.https.HttpsError('failed-precondition', 'query is required');
  }

  if (!quantity) {
    throw new functions.https.HttpsError('failed-precondition', 'quantity is required');
  }

  try {
    console.log(`Creating embedding for ${query}`)
    const embeddingResponse = await openai.embeddings.create({
      model: "text-embedding-3-small",
      input: query,
      encoding_format: "float",
    });

    const embedding = embeddingResponse.data[0].embedding;
    console.log(`Embedding:`, embedding)

    const vectorQuery: VectorQuery = firestore.collection('elements').findNearest('embedding', FieldValue.vector(embedding), {
      limit: quantity,
      distanceMeasure: 'COSINE'
    });

    const snapshot: VectorQuerySnapshot = await vectorQuery.get();
    console.log(`Snapshot:`, snapshot)

    const formattedData: any = {};
    snapshot.docs.forEach((doc) => {
      formattedData[doc.id] = doc.data();
    });

    return { docs: formattedData };
  } catch (error) {
    console.error('Error querying database:', error);
    throw new functions.https.HttpsError('internal', 'Error querying database');
  }
});

问题描述

调用该函数时,目标集合elements下存在文档,但未返回任何结果,且无报错信息。预期应返回quantity参数指定数量的文档,请问原因是什么?


可能的原因及排查方向
  • 索引维度与存储向量维度不匹配
    创建索引时指定的维度为1536,需确认elements集合中文档的embedding字段向量维度是否一致。若维度不匹配,查询将无法匹配结果。可直接在Firestore控制台查看文档的embedding字段值,或在云函数中添加日志打印单个文档的embedding长度。

  • 向量索引未完全生效
    Firestore复合向量索引创建成功后,需一定时间完成数据同步(文档量越大耗时越久)。可等待一段时间后重试,或通过gcloud firestore indexes composite describe命令确认索引状态是否为READY。

  • 查询向量与存储向量相似度极低
    使用COSINE距离时,若查询向量与所有存储向量的相似度趋近于0,Firestore可能不会返回结果。可在云函数中添加日志,打印查询向量与已知文档向量的余弦相似度,验证匹配可能性。

  • 安全规则限制查询权限
    检查Firestore安全规则是否允许云函数访问elements集合。云函数默认使用服务账号权限,但严格的安全规则可能导致无法读取文档。可临时放宽规则测试(测试后需恢复):

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    
  • 向量构造或数据格式错误
    确认FieldValue.vector(embedding)是否正确构造了Firestore支持的向量类型,可打印其结构并与Firestore存储的向量格式对比。同时检查OpenAI返回的embedding是否为有效的1536维浮点数组。

  • 集合路径拼写错误
    确认云函数中firestore.collection('elements')指向的是正确的集合,无拼写错误或路径层级错误(比如误将子集合当作根集合)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:11:21