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

Python Firestore使用not-in排除指定document_id报错的解决方法

解决Firestore使用FieldPath.document_id()执行not-in查询的错误

错误原因

当使用FieldPath.document_id()(对应内部字段__name__)进行not-in过滤时,Firestore要求过滤值必须是文档的Reference/Key对象,而非纯字符串ID,直接传入字符串数组会触发__key__ filter value must be a Key错误。

解决方法

将每个需排除的文档ID转换为对应子集合下的DocumentReference对象,再传入not-in条件:

修改后的代码

from firebase_admin import firestore
from google.cloud.firestore_v1.field_path import FieldPath

blocked_ids = ['123123','232323']

db = firestore.AsyncClient()
# 获取目标子集合引用
query_ref = db.collection('items').document('some-id-here').collection('other-items')
# 将字符串ID转为对应集合的DocumentReference
blocked_refs = [query_ref.document(doc_id) for doc_id in blocked_ids]
# 执行查询(注意需调用.get()获取结果)
query = query_ref.where(FieldPath.document_id(), "not-in", blocked_refs)
items = await query.get()

补充说明

  • FieldPath.document_id()映射的是文档键的名称部分,但Firestore在处理基于文档ID的过滤时,内部需要完整的文档键信息,因此必须传入对应集合下的文档引用对象。
  • 原代码中直接await query_ref.where(...)是错误的,where()返回的是Query对象,需调用.get()方法才能触发异步查询并获取结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:08