简体   繁体   English

使用Java将JSON流式传输到BigQuery

[英]Streaming JSON into BigQuery using Java

I am trying to stream data into BigQuery using the Java driver similar to the tutorial on this page which inserts data into a BigQuery table from a map. 我正在尝试使用类似于本页面上的教程的Java驱动程序将数据流式传输到BigQuery,该教程将数据从地图插入到BigQuery表中。 The v2 of the streaming rest API supports specifying rows as JSON when inserting so I was wondering if I can stream JSON to bigquery using the Java driver rather than having to use a map like the below example. Streaming Rest API的v2支持在插入时将行指定为JSON,因此我想知道是否可以使用Java驱动程序将JSON流式传输至bigquery,而不必像下面的示例那样使用映射。

Map<String, Object> rowContent = new HashMap<>();
rowContent.put("booleanField", true);
// Bytes are passed in base64
rowContent.put("bytesField", "Cg0NDg0="); // 0xA, 0xD, 0xD, 0xE, 0xD in base64
// Records are passed as a map
Map<String, Object> recordsContent = new HashMap<>();
recordsContent.put("stringField", "Hello, World!");
rowContent.put("recordField", recordsContent);
InsertAllResponse response = bigquery.insertAll(InsertAllRequest.newBuilder(tableId)
    .addRow("rowId", rowContent)
    // More rows can be added in the same RPC by invoking .addRow() on the builder
    .build());

ie is there some way to run bigquery.insertAll but pass in a json string rather than a Map? 即有什么方法可以运行bigquery.insertAll但传递一个json字符串而不是一个Map?

Ended up using Jackson to convert JSON string to Map using ObjectMapper class and then uploading using the same way as the example on Google's site for streaming to BigQuery in Java. 最终使用Jackson通过ObjectMapper类将JSON字符串转换为Map,然后使用与Google网站上的示例相同的方式进行上传,以流式传输到Java中的BigQuery。

BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
TableId tableId = TableId.of("dataset_name", "table_name");
try {
  HashMap<String,Object> mapResult = new ObjectMapper().readValue(json_string, HashMap.class);
  InsertAllResponse response = bigquery.insertAll(InsertAllRequest.newBuilder(tableId)
    .addRow(UUID.randomUUID().toString(), mapResult)
    .build());
  if (response.hasErrors()) {
    // If any of the insertions failed, this lets you inspect the errors
    for (Entry<Long, List<BigQueryError>> entry : response.getInsertErrors().entrySet()) {
      System.out.println(entry);
    }
  }
} catch (IOException e) {
  // Failed to Map JSON String
  System.out.println(e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM