java - 使用 Apache Beam 将重复的字符串写入 BigQuery
问题描述
我有一个包含Strings
看起来像的数据流JSONArrays
。我想解析这些字符串并使用 Apache Beam 写入 BigQuery 表,但在写入重复字符串时出现错误。
这是我将字符串转换为TableRow
:
String dataString = "[{\"EMAIL\": [\"zog@yahoo.com\"]}]";
JSONArray jsonArray = new JSONArray(dataString);
TableRow tableRow = new TableRow();
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray emailArray = new JSONArray(jsonArray.getJSONObject(i).get("EMAIL").toString());
tableRow.set("EMAIL", emailArray); //Results in error
}
这是我的 BigQuery 架构的样子:
[
{
"name": "EMAIL",
"type": "STRING",
"mode": "REPEATED"
}
]
我已经设法使用 Python 将类似的重复字符串写入 BigQuery 表,但无法使用 Apache Beam 来完成。我想我没有将正确的键值对保存在TableRow
. 我现在得到的错误是:
java.io.IOException: Insert failed: [{"errors":[{"debugInfo":"","location":"email","message":"This field is not a record.","reason":"invalid"}],"index":0}]
我需要有关如何在不创建记录的情况下将类似的重复字符串保存到 BigQuery 的帮助,并且希望获得任何建议或建议。提前致谢。
解决方案
看来你想创建
- 一行包含串联的电子邮件地址字符串,或
- 每封电子邮件一行,或
- 具有重复字段的一行。
请注意,您的ValidFrom
字段似乎是 type STRING
,而不是重复字段,除非它包含在分层架构中的重复字段中。
在您提供的示例代码中,您正在创建一个JSONArray
并将其放入STRING
字段中,我认为这会导致问题,因为类型不兼容。如果要将其保留为普通STRING
字段,可以使用下面的解决方案 1。
还要确保您在 BigQuery 中的列名称与您的代码中的名称相匹配,我看到您同时使用了ValidFrom
和EMAIL
(尽管可能是您发布的代码中的错误)。
解决方案 1:一行字符串字段
如果您想在 BigQuery 中添加一行包含连接 String
字段的行,可以使用以下命令:
// Initialize your final row
TableRow tableRow = new TableRow();
// Find email addresses
String [] emails = ... // your extraction logic
// Build a concatenated string of emails
String allEmails = String.join(";", emails);
// Add the string field to the row
tableRow.set('EMAILS', allEmails);
解决方案 2:带有字符串字段的多行
如果您想插入多行,您可以创建多个表行:
// Find email addresses
String [] emails = ... // your extraction logic
// Build a row per email
for(String email: emails) {
// Initialize your final row
TableRow tableRow = new TableRow();
tableRow.set('EMAIL', email);
// TODO: do something with the row (add to list, or ...)
}
解决方案 3:一行包含 REPEATED 字段
如果您想在 BigQuery 中添加一个包含字段的行,REPEATED STRING
您可以使用以下命令:
// Initialize your final row
TableRow tableRow = new TableRow();
// Find email addresses
String [] emails = ... // your extraction logic
// Build the repeated field
List<String> emailCells = new ArrayList<>();
for(String email: emails) {
emailCells.add(email);
}
// Add the repeated field to the row
tableRow.set('EMAILS', emailCells);
如果这不是您的目标,请提供更多详细信息。
推荐阅读
- python - 如何将 PHP 中的 http_build_query 转换为表单数据的 python 等效项
- amazon-web-services - 将 DynamoDB 的 updateItem 与数值一起使用
- flutter - 如何将未来对象列表中的值附加到简单的对象列表中
- powershell - 如何在PowerShell中将包括符号链接在内的文件夹结构扩展到真实文件和文件夹(无链接)?
- javascript - Bootstrap 4轮播在jQuery的循环中添加项目不起作用
- highcharts - 带有粗线的 Highcharts - 在 0 值时,该线是半隐藏的
- javascript - 从 NavLink 获取状态道具
- java - 相对于 MaterialToolbar 设置状态栏颜色?
- php - 三元运算符中的两个任务 - PHP
- arrays - C 通过 strlen() 设置数组大小