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

求Firebase扩展Stream Collections to BigQuery转换函数示例及详细文档

Firestore转BigQuery转换函数示例与说明

Firebase扩展「Stream Collections to BigQuery」的转换函数用于将Firestore文档JSON转换为适配BigQuery表结构的格式,以下是实用示例和关键说明:

基础字段映射示例

适用于扁平结构文档,直接映射字段并处理数据类型、默认值:

function transform(doc) {
  const data = doc.data();
  
  return {
    document_id: doc.id,
    created_at: data.createdAt?.toISOString() || null,
    user_id: data.userId,
    order_amount: Number(data.orderAmount) || 0,
    status: data.status || 'pending'
    // 敏感字段直接忽略,不加入返回对象
  };
}

嵌套结构展开示例

将Firestore中的嵌套对象展开为BigQuery的顶层字段,同时可保留原嵌套结构:

function transform(doc) {
  const data = doc.data();
  
  return {
    document_id: doc.id,
    // 展开用户信息
    user_name: data.user?.name || 'Unknown',
    user_email: data.user?.email || null,
    // 展开收货地址
    shipping_city: data.shippingAddress?.city || null,
    shipping_postcode: data.shippingAddress?.postcode || null,
    // 保留原嵌套结构(若BigQuery表定义为RECORD类型)
    original_user_profile: data.user
  };
}

数组字段处理示例

清理并格式化Firestore数组,转换为BigQuery兼容的数组格式:

function transform(doc) {
  const data = doc.data();
  
  // 过滤无效元素并格式化每个数组项
  const formattedProducts = (data.products || []).map(item => ({
    product_id: item.id,
    product_name: item.name || 'Unnamed',
    quantity: Number(item.quantity) || 1
  })).filter(product => product.product_id);

  return {
    document_id: doc.id,
    order_id: data.orderId,
    products: formattedProducts,
    total_product_count: formattedProducts.length
  };
}

核心注意事项

  • 返回对象不能包含undefined值,需用null或默认值替代,否则BigQuery会拒绝接收
  • 数据类型适配:Firestore的Timestamp需转为ISO字符串或Unix时间戳;字符串类型的数字要转为Number类型
  • 可获取文档元数据:通过doc.ref.path获取完整文档路径,doc.updateTime获取最后更新时间等
  • 错误处理:建议加入异常捕获,避免单个文档转换失败中断整个数据流:
    function transform(doc) {
      try {
        const data = doc.data();
        // 转换逻辑
        return { /* ... */ };
      } catch (error) {
        console.error(`文档${doc.id}转换失败:`, error);
        return { document_id: doc.id, transform_error: error.message };
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:55:23