如何在Genkit Firestore检索器中先按uid过滤再执行向量匹配?
在Genkit Firestore检索器中实现预过滤后向量搜索
Genkit的defineFirestoreRetriever目前没有直接内置的预过滤配置参数,但可以通过两种实用方案实现先过滤特定uid文档,再执行向量近邻搜索的需求:
方案一:创建带固定过滤条件的检索器
如果你的过滤条件(比如固定uid=123)是静态不变的,可以在定义检索器时,传入一个已添加where过滤的Firestore集合引用,而非直接传入集合名称:
const firestore = getFirestore(); // 先构建带uid过滤的集合引用 const filteredArticlesCollection = firestore.collection('articles').where('uid', '==', '123'); const firestoreRetriever = defineFirestoreRetriever({ name: 'firestore-articles-filtered-by-uid', firestore: firestore, collection: filteredArticlesCollection, // 传入过滤后的集合引用 contentField: 'fullText', vectorField: 'embeddings', embedder: textEmbeddingGecko, distanceMeasure: 'COSINE', metadataFields: ['path'] });
后续调用这个检索器时,会自动先过滤uid=123的文档,再执行向量搜索。
方案二:动态传入过滤条件(推荐)
如果需要每次检索时动态指定uid,更灵活的方式是自定义检索逻辑,手动结合Firestore的过滤和向量查询:
// 自定义检索函数,支持动态传入目标uid async function filteredRetrieve(query, targetUid, options = { k: 1, limit: 10 }) { const firestore = getFirestore(); // 生成查询文本的嵌入向量 const embeddingResult = await textEmbeddingGecko.embedQuery(query); const queryEmbedding = embeddingResult.embedding; // 构建查询:先过滤uid,再执行向量近邻搜索 const querySnapshot = await firestore.collection('articles') .where('uid', '==', targetUid) .orderBy('embeddings', 'ASC') // COSINE距离下,ASC对应更相似的结果在前 .limit(options.limit) .findNearest('embeddings', queryEmbedding, { distanceMeasure: 'COSINE', k: options.k }); // 将Firestore结果转换为Genkit检索器的标准返回格式 return querySnapshot.docs.map(doc => ({ content: doc.get('fullText'), metadata: { path: doc.ref.path, uid: doc.get('uid') }, score: doc.get('embeddings').distance })); } // 调用示例 const docs = await filteredRetrieve('你的查询内容', '123', { k: 1, limit: 10 });
这种自定义方式完全可控,能灵活调整过滤条件和向量查询的组合逻辑,适配动态场景。
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

