【问题标题】:How can I get integers from bigquery nodejs api?如何从 bigquery nodejs api 获取整数?
【发布时间】:2016-02-16 07:57:12
【问题描述】:

我正在从 bigquery 中获取数据,我需要将这些数据以整数形式存储在 MongoDB 中,以便我可以在 Mongo 中对该数据执行操作。尽管 bigquery 中列的数据类型是 Integer,但其 nodejs api 在其 Javascript 对象中返回字符串。例如。我得到的结果看起来像 [{row1:'3',row2:'4',row3:'5'},{row1:'13',row2:'14',row3:'15'}...]

typeof 在对象的每个元素上给出字符串。我可以运行一个循环并将每个元素转换为整数,但这在数据集上是不可扩展的。另外,我不希望所有字符串都转换为整数,只有在 bigquery 中存储为整数的字符串。我在 nodejs 中使用 gcloud 模块来获取数据。

【问题讨论】:

  • 更新 gcloud 成功了

标签: javascript node.js mongodb google-bigquery


【解决方案1】:

假设您知道 type 属性在响应中的位置,这样的事情会起作用。

var response = [{type: 'Integer', value: '13'} /* other objects.. */];

var mappedResponse = response.map(function(item) {
  // Put your logic here
  // This implementation just bails
  if (item.type != 'Integer') return item;

  // This just converts the value to an integer, but beware
  // it returns NaN if the value isn't actually a number
  item.value = parseInt(item.value);
  // you MUST return the item after modifying it.
  return item;      
});

这仍然会循环遍历每个项目,但如果它不是我们要查找的内容,则会立即退出。也可以组合多个地图和过滤器来概括这一点。

解决这个问题的唯一方法是首先应用一个过滤器,但这与我们最初的类型检查基本相同

var mappedResponse = response
  // Now we only deal with integers in the map function
  .filter(x => x.type == 'Integer)
  .map(function(item) {
    // This just converts the value to an integer, but beware
    // it returns NaN if the value isn't actually a number
    item.value = parseInt(item.value);
    // you MUST return the item after modifying it.
    return item;      
  });

【讨论】:

    【解决方案2】:

    BigQuery 在通过 API 返回整数时故意将整数编码为字符串,以避免大值的精度损失。目前,唯一的选择是在客户端解析它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2015-07-24
      • 2017-07-28
      • 1970-01-01
      • 2023-03-03
      • 2021-04-29
      相关资源
      最近更新 更多