如何使用APIKey连接Google Cloud Bigquery和NodeJS



我正在尝试使用node 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();

忘记API键,你不能在BigQuery中使用它(它仍然使用旧的API,但很少)。您需要使用OAuth2机制进行身份验证

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

文档中有对身份验证的描述。要走得更快,在谷歌云环境下,你可以依靠服务的服务帐户。在某些服务中,您可以自定义它们。您也可以在您的计算机上使用您自己的凭据,并在外部平台(在本地,在其他云提供商)上使用服务帐户密钥文件。

因此,在您的示例中,您像这样初始化bigquery库const bigqueryClient = new BigQuery();。这意味着您依赖于环境凭据来连接到BigQuery。

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

gcloud auth application-default login

登录并享受!!

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

最新更新