首页 > 解决方案 > UNIX 时间戳转 Google bigQuery TS 格式

问题描述

我正在使用 google Pub/sub 接收消息并触发云函数,该函数在 BigQuery 中查询消息的数据,问题是在我的消息中我收到 UNIX 时间戳,我需要将此时间戳转换为bigquery 格式,否则该函数无法运行我的查询...

在这部分函数中:

exports.insertBigQuery = async (message, context) => {
  // Decode base64 the PubSub message
  let logData = Buffer.from(message.data, "base64").toString();
  // Convert it in JSON
  let logMessage = JSON.parse(logData);

  const query = createQuery(logMessage);

  const options = {
    query: query,
    location: "US",
  };

  const [job] = await bigquery.createQueryJob(options);
  console.log(`Job ${job.id} started.`);

  // Only wait the end of the job. Theere is no row as answer, it's only an insert
  await job.getQueryResults();
};

我访问消息中的数据。

在我的 bigquery 中查询的函数的这一部分:

function createQuery() {
  const queryString = `INSERT INTO \`mytable\`(myTS, userTS, registerTS) 
VALUES ( @myTS, @userTS, @registerTS);`;

我的问题是我收到带有 UNIX 时间戳的消息,当函数运行时,我的查询给了我一个错误。我找不到任何解决方案,非常感谢任何帮助!提前致谢!

标签: google-bigquerygoogle-cloud-pubsub

解决方案


您可以处理此问题的一种方法是使用该TIMESTAMP_SECONDS函数将您的值包装在插入

INSERT INTO \`mytable\`(myTS, userTS, registerTS) 
VALUES ( TIMESTAMP_SECONDS(@myTS), TIMESTAMP_SECONDS(@userTS), TIMESTAMP_SECONDS(@registerTS));

推荐阅读