如何从bigquery nodejs api获取整数?

时间:2016-02-16 07:57:12

标签: javascript node.js mongodb google-bigquery

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

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

2 个答案:

答案 0 :(得分:2)

假设你知道响应中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;      
  });

答案 1 :(得分:1)

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