首页 > 解决方案 > 使用 Cloud Functions 将大数据从 BigQuery 导入 Firestore

问题描述

我正在使用 Cloud Functions 将 BigQuery 数据集表中的大数据导入 Firestore,对于大约 500 条记录的小型数据表来说一切都很好。但问题在于大数据,例如,大约 40,000 条记录的表。从 500 个文档的 Firebase 配额限制,他们建议使用我使用过的批量写入,但它仍然只插入 500 个文档,在日志中,我看到已经创建了 500 多个文档(我已经记录了自动生成的 ID)但我不能在 Firestore 中查看它们。我已将enter code here超时配置为 540 秒。帮我看看我的代码,看看我哪里出错了。谢谢

const {BigQuery} = require("@google-cloud/bigquery");
const firebaseConfig =  require('firebase-admin');

firebaseConfig.initializeApp();

const firestoreDb = firebaseConfig.firestore();

var batchCommits = [];

var batch = firestoreDb.batch();

var counter = 0;

exports.fetchAdminTwo = (req,res) =>{
 var bigQuery = new BigQuery({ projectId: 'XXXXXXXXXXX' });

 var sqlStatement = 'SELECT id, id_admin1, description_en, description_fr, description_es, latitude, longitude FROM `fao-empres-re.empres_data.admin2`;';

 console.log('Triggering bigquery to execute sql statement');

 return bigQuery.query({query:sqlStatement}).then(results =>{
     var adminList = results[0];
     console.log('Query results:',adminList);

     res.send(adminList);

     adminList.forEach((admin,i) =>{
         var collectionRef = firestoreDb.collection('ref-admins-two').doc();
         batch.set(collectionRef,admin);
         console.log('Doc ID:',collectionRef.id,'Count:',counter++);
         if ((i + 1) % 500 === 0) {
             console.log(`Batch count: ${i + 1}`);
             batchCommits.push(batch.commit());
             batch = firestoreDb.batch();
             }
     });
     batchCommits.push(batch.commit());
     return Promise.all(batchCommits);

}).catch(error =>{
    console.log("Query error:",error);
    });

}

标签: javascriptgoogle-cloud-firestoregoogle-cloud-functionsgoogle-api-nodejs-clientgoogle-admin-sdk

解决方案


在您的代码中,您不会在接收下一个 500 批次之前将 batchCommit 重置为空数组。像这样修改你的代码。

if ((i + 1) % 500 === 0) {
             console.log(`Batch count: ${i + 1}`);
             batchCommits.push(batch.commit());
             batch = firestoreDb.batch();
             batchCommits = [];
             }
=

推荐阅读