【问题标题】:How to connect Google Cloud Bigquery with NodeJS using APIKey如何使用 APIKey 将 Google Cloud Bigquery 与 NodeJS 连接起来
【发布时间】:2021-05-03 14:32:50
【问题描述】:

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

如何将 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();

【问题讨论】:

    标签: node.js google-cloud-platform google-bigquery google-api-nodejs-client


    【解决方案1】:

    忘记 API 密钥,您不能将其用于 BigQuery(它仍在使用旧版 API,但很少使用)。您需要使用 OAuth2 机制进行身份验证。

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

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

    因此,在您的情况下,您可以像 const bigqueryClient = new BigQuery(); 一样启动 bigquery 库。这意味着您依赖环境凭据连接到 BigQuery。

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

    gcloud auth application-default login
    

    登录并享受!

    但是GCP的安全性还有很长的路要走,这只是个开始,以后有没有选择困难再问

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 1970-01-01
      • 2015-09-21
      • 2019-09-01
      • 1970-01-01
      • 2021-09-15
      • 2019-10-01
      • 1970-01-01
      • 2017-03-06
      相关资源
      最近更新 更多