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

Firestore Python SDK中count()聚合查询的实现方法咨询

Firestore Python SDK 实现count聚合查询的正确方式

Firestore官方Python SDK完全支持count聚合查询,你之前的代码仅调用count()但未执行查询,所以无法得到结果。以下是两种正确的实现方式:

方法一:直接使用count聚合查询并执行

from google.cloud import firestore

# 初始化Firestore客户端
db = firestore.Client()
# 构建筛选查询
query = db.collection('videos').where('status', '==', 'pending')
# 创建count聚合查询并执行获取结果
count_result = query.count().get()
# 提取计数数值
total = count_result[0][0]
print(f"状态为pending的视频文档数量: {total}")

方法二:通过AggregationQuery构建聚合

from google.cloud import firestore
from google.cloud.firestore_v1.aggregation import AggregationQuery

db = firestore.Client()
query = db.collection('videos').where('status', '==', 'pending')
# 初始化聚合查询对象
agg_query = AggregationQuery(query)
# 添加count聚合规则,可指定别名便于结果提取
agg_query.add_count(alias='pending_videos_count')
# 执行查询
result = agg_query.get()
# 通过别名获取计数
total = result[0].get('pending_videos_count')
print(f"状态为pending的视频文档数量: {total}")

注意事项

  • 确保你的google-cloud-firestore SDK版本在2.11.0及以上,这是count聚合功能正式支持的最低版本。版本过低的话,执行以下命令升级:
pip install --upgrade google-cloud-firestore

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:21:03