如何从 bigquery nodejs api 获取整数?

How can I get integers from bigquery nodejs api?

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

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

假设您知道类型 属性 在响应中的位置,这样的事情就可以了。

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;      
  });

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