如何使用 APIKey 将 Google Cloud Bigquery 与 NodeJS 连接

Rom*_*hah 5 node.js google-bigquery google-api-nodejs-client google-cloud-platform

我正在尝试使用 Node js 在 google bigquaey 中插入、删除、搜索和更新。我已经跟进了google中的所有文档。但没有提到如何连接 - 所以我创建了这个,--

如何将 GCP BigQuery 与 NodeJS 连接。我刚来这地方。任何帮助都会起作用。

我写的代码 -

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

const mainFunction = () => {
    insertIntoBigQuery("John", "john@gmail.com", "+1-23232344231");
}

async function insertIntoBigQuery(name, email, phone) {
// const insertIntoBigQuery = async(name, email, phone) => {
    const bigqueryClient = new BigQuery();
    // The SQL query to run
    const sqlQuery = "INSERT INTO `p4tyu78.Backend_testing.Test1` VALUES ("+name+ "," +email+","+ phone+")";

    const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
    };

    // Run the query
    const [rows] = await bigqueryClient.query(options);

    console.log('Rows:');
    rows.forEach(row => console.log(`${row.subject}: ${row.num_duplicates}`));
}

const updateIntoBigQuery = () => {
    
}

const deleteFromBigQuery = () => {
    
}

const searchFromBigQuery = async() => {
    const bigqueryClient = new BigQuery();
    // The SQL query to run
    const sqlQuery = "SELECT * from `p4tyu78.Backend_testing.Test1`";

    const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
    };

    // Run the query
    const [rows] = await bigqueryClient.query(options);

    console.log('Rows:');
    rows.forEach(row => console.log(`${row.subject}: ${row.num_duplicates}`));
}

mainFunction();
Run Code Online (Sandbox Code Playgroud)

gui*_*ere 3

忘记 API 密钥,您无法将其用于 BigQuery(它仍然可以与旧 API 一起使用,但很少)。您需要使用OAuth2机制进行身份验证。

当您使用 Google Cloud API 时,您需要在 API 请求的标头中添加访问令牌。但在您的情况下,您不直接执行这些 API 调用,而是使用客户端库。

您在文档中有有关身份验证的描述。为了更快,在 Google Cloud 环境中,您可以依赖服务服务帐户。在某些服务中您可以自定义它们。您还可以在计算机上使用您自己的凭据,以及外部平台(在本地、其他云提供商上)上的服务帐户密钥文件。

因此,就您而言,您可以像这样启动 bigquery 库const bigqueryClient = new BigQuery();。这意味着您依赖环境凭据来连接到 BigQuery。

在您的环境中,要使用您自己的凭据,您可以使用 gcloud CLI 并运行此命令

gcloud auth application-default login
Run Code Online (Sandbox Code Playgroud)

登录并享受!

但安全性在GCP上还有很长的路要走,这只是一个开始,如果您在选择上遇到困难,请稍后再询问