如何从bigquery nodejs api获取整数

How can I get integers from bigquery nodejs api?

本文关键字:api 获取 整数 nodejs bigquery      更新时间:2023-09-26

我正在从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 返回整数时故意将整数编码为字符串,以避免大值的精度损失。目前,唯一的选择是在客户端解析它们。