提问者:小点点

通过Google Cloud数据流将PubSub消息插入BigQuery


我想使用谷歌云数据流将来自主题的PubSub消息数据插入到BigQuery表中。一切都很好,但在BigQuery表中,我可以看到不可读的字符串,如 " ߈���". 这是我的管道:

p.apply(PubsubIO.Read.named("ReadFromPubsub").topic("projects/project-name/topics/topic-name"))
.apply(ParDo.named("Transformation").of(new StringToRowConverter()))
.apply(BigQueryIO.Write.named("Write into BigQuery").to("project-name:dataset-name.table")
     .withSchema(schema)
     .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED))

我简单的StringToRowConverter函数是:

class StringToRowConverter extends DoFn<String, TableRow> {
private static final long serialVersionUID = 0;

@Override
public void processElement(ProcessContext c) {
    for (String word : c.element().split(",")) {
      if (!word.isEmpty()) {
          System.out.println(word);
        c.output(new TableRow().set("data", word));
      }
    }
}
}

这是我通过POST请求发送的消息:

POST https://pubsub.googleapis.com/v1/projects/project-name/topics/topic-name:publish
{
 "messages": [
  {
   "attributes":{
"key": "tablet, smartphone, desktop",
"value": "eng"
   },
   "data": "34gf5ert"
  }
 ]
}

我错过了什么?谢谢!


共2个答案

匿名用户

根据https://cloud.google.com/pubsub/reference/rest/v1/PubsubMessage,pubsub消息的JSON有效负载是base64编码的。Dataflow中的PubsubIO默认使用String UTF8编码器。您提供的示例字符串“34gf5ert”在base64解码后解释为UTF-8字符串时,给出了确切的 "߈���".

匿名用户

这就是我如何打开我的pubsub消息:

@Override
public void processElement(ProcessContext c) {

    String json = c.element();

    HashMap<String,String> items = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>(){}.getType());
    String unpacked = items.get("JsonKey");

希望对你有用。