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

如何用GCP C# Firestore客户端筛选含Manual类型文档的Audit记录

解决方案

要筛选出包含至少一个Manual类型文档的Audit记录,可以利用Firestore的数组对象字段查询功能,通过C#客户端的WhereEqualTo方法指定数组元素的属性条件。

完整代码示例

[FirestoreData]
[FirestoreCollectionName("Audit")]
public class Audit
{
    [FirestoreProperty]
    public string Id { get; set; } // 修正为public,确保Firestore能正常序列化/反序列化
    
    [FirestoreProperty]
    public List<Document> Documents { get; set; }
}

[FirestoreData]
public class Document
{
    [FirestoreProperty]
    public string Abbrev { get; set; }    
    
    [FirestoreProperty]
    public DocType Type { get; set; }    
}

public enum DocType
{
    Instruction,
    Manual,
    Other
}

// 初始化Firestore客户端
var db = FirestoreDb.Create(my_project_id);
CollectionReference auditRef = db.Collection("Audit");

// 核心查询:筛选Documents列表中存在Type为Manual的Audit记录
Query query = auditRef.WhereEqualTo("Documents.Type", DocType.Manual);
QuerySnapshot snapshot = await query.GetSnapshotAsync();

// 遍历处理查询结果
foreach (DocumentSnapshot doc in snapshot.Documents)
{
    Audit audit = doc.ConvertTo<Audit>();
    // 此处添加你的业务逻辑
}

关键说明

  • 字段路径规则:使用"Documents.Type"作为查询字段路径,Firestore会自动遍历Documents数组中的每个元素,判断是否存在Type属性等于Manual的元素。
  • 访问修饰符修正:原代码中Audit类的Id属性为私有,Firestore无法完成序列化/反序列化,需改为public才能正确映射数据。
  • 索引说明:单个条件的此类查询无需手动创建复合索引,Firestore自动索引即可支持;若后续添加多条件组合查询,可能需要在Firestore控制台创建对应复合索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:55:25