是否可以从Firebase云功能访问bigquery数据?
还是我们可以编写一个可以直接对bigquery数据执行操作的云函数?

更新:
这是MyCode

const functions = require('firebase-functions');

const bigquery = require('@google-cloud/bigquery');


const admin = require('firebase-admin');


var serviceAccount = require("");


admin.initializeApp(functions.config().firebase);


exports.sendBigQueryData = functions.analytics.event('app_open').onLog(event => {


var bigQuery = BigQuery({ projectId:  });
    bigQuery.query({


        query: 'SELECT CAST(TIMESTAMP_ADD(TIMESTAMP_MICROS(event.timestamp_micros), INTERVAL 330 MINUTE) AS date) AS event_date, count(event.name) AS number_questions FROM ``, UNNEST(event_dim) AS event WHERE event.name="asked_question" GROUP BY event_date ORDER BY event_date DESC'
    }).then(function (results) {


        var ref = admin.database().ref('');

        var rows = results[0]; //get all fetched table rows
        rows.forEach(function(row){ //iterate through each row
            ref.push().set({ //write to the database, under the 'queryresults' node
                column1:row['col1'],
                column2:row['col2']
            });
        });
        //return result
    }).catch(function (error) {
        //return an error
    })
  });


ReferenceError:未定义BigQuery

at exports.sendBigQueryData.functions.analytics.event.onLog.event (/user_code/index.js:11:16)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:695:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

最佳答案

是的,可以从Cloud Function访问bigquery数据。您只需要使用require()导入它:

const functions = require('firebase-functions');
const bigquery = require('@google-cloud/bigquery');


编辑:如果您的云函数没有实时数据库触发器,则还需要添加Admin SDK才能写入数据库:

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


然后在声明的云函数内部运行查询:

var bigQuery = BigQuery({ projectId: 'YOUR-PROJECT-ID' });
    bigQuery.query({
        query: 'YOUR QUERY HERE'
    }).then(function (results) {
        var ref = admin.database().ref('queryresults');

        var rows = results[0]; //get all fetched table rows
        rows.forEach(function(row){ //iterate through each row
            ref.push().set({ //write to the database, under the 'queryresults' node
                column1:row['col1'],
                column2:row['col2']
            });
        });
        //return result
    }).catch(function (error) {
        //return an error
    });

10-01 00:45
查看更多