【问题标题】:How to stream insert JSON array to BigQuery table in Apache Beam如何在 Apache Beam 中将 JSON 数组流式插入 BigQuery 表
【发布时间】:2019-03-25 12:58:18
【问题描述】:

我的 Apache Beam 应用程序接收 JSON 数组中的消息,但将每一行插入 BigQuery 表。我如何在 ApacheBeam 中支持这个用例?我可以将每一行拆分并一一插入到表中吗?

JSON 消息示例:

[
  {"id": 1, "name": "post1", "price": 10},
  {"id": 2, "name": "post2", "price": 20},
  {"id": 3, "name": "post3", "price": 30}
]

BigQuery 表架构:

[
    {
      "mode": "REQUIRED",
      "name": "id",
      "type": "INT64"
    },
    {
      "mode": "REQUIRED",
      "name": "name",
      "type": "STRING"
    },
    {
      "mode": "REQUIRED",
      "name": "price",
      "type": "INT64"
    }
]

【问题讨论】:

  • 您好 Yoshei 抱歉,但不确定问题的描述。您在询问是否在 apache Bean 中获得 JSON 数组,如何处理它并将逐行插入 bigQuery。所以在你的例子中是 3 行?
  • 是的,正如我描述的问题

标签: json google-bigquery apache-beam


【解决方案1】:

这是我的解决方案。我将 JSON 字符串转换为 List 一次,然后 c.output 一个接一个。我的代码在 Scala 中,但你可以在 Java 中做同样的事情。

    case class MyTranscationRecord(id: String, name: String, price: Int)
    case class MyTranscation(recordList: List[MyTranscationRecord])
    class ConvertJSONTextToMyRecord extends DoFn[KafkaRecord[java.lang.Long, String], MyTranscation]() {
      private val logger: Logger = LoggerFactory.getLogger(classOf[ConvertJSONTextToMyRecord])
      @ProcessElement
      def processElement(c: ProcessContext): Unit = {
        try {
          val mapper: ObjectMapper = new ObjectMapper()
            .registerModule(DefaultScalaModule)
          val messageText = c.element.getKV.getValue
          val transaction: MyRecord = mapper.readValue(messageText, classOf[MyTranscation])
          logger.info(s"successfully converted to an EPC transaction = $transaction")
          for (record <- transaction.recordList) {
              c.output(record)
          }
        } catch {
          case e: Exception =>
            val message = e.getLocalizedMessage + e.getStackTrace
            logger.error(message)
        }
      }
    }

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-12-15
    相关资源
    最近更新 更多