如何从GCP存储桶读取Apache Beam中的多个文件

问题描述 投票:0回答:1

我正在尝试使用Apache Beam在GCP中的多个文件上读取并应用一些子集。我准备了两个仅对一个文件有效的管道,但是在多个文件上尝试它们时失败。除此之外,如果可能的话,我会很方便地将我的管道合并为一个管道,或者有一种方法可以对它们进行编排以使它们按顺序工作。现在管道在本地工作,但最终目标是使用Dataflow运行它们。

我是textio.ReadFromText和textio.ReadAllFromText,但在有多个文件的情况下,我俩都不起作用。

def toJson(file):
    with open(file) as f:
        return json.load(f)


 with beam.Pipeline(options=PipelineOptions()) as p:
       files = (p
        | beam.io.textio.ReadFromText("gs://my_bucket/file1.txt.gz", skip_header_lines = 0)
        | beam.io.WriteToText("/home/test",
                   file_name_suffix=".json", num_shards=1 , append_trailing_newlines = True))

 with beam.Pipeline(options=PipelineOptions()) as p:
lines = (p  
            | 'read_data' >> beam.Create(['test-00000-of-00001.json'])
            | "toJson" >> beam.Map(toJson)
            | "takeItems" >> beam.FlatMap(lambda line: line["Items"])
            | "takeSubjects" >> beam.FlatMap(lambda line: line['data']['subjects'])
            | beam.combiners.Count.PerElement()
            | beam.io.WriteToText("/home/items",
                   file_name_suffix=".txt", num_shards=1 , append_trailing_newlines = True))

这两个管道对于单个文件很好地工作,但是我有数百个相同格式的文件,并且希望利用并行计算的优势。

是否有一种方法可以使该管道适用于同一目录下的多个文件?

是否可以在单个管道中执行此操作,而不是创建两个不同的管道? (将文件从存储桶中写入工作节点并不方便。)

非常感谢!

python python-3.x apache-beam dataflow apache-beam-io
1个回答
0
投票

我解决了如何使它适用于多个文件,但无法使其在单个管道中运行。我使用了循环,然后使用了beam.Flatten选项。

这是我的解决方法:

file_list = ["gs://my_bucket/file*.txt.gz"]
res_list = ["/home/subject_test_{}-00000-of-00001.json".format(i) for i in range(len(file_list))]

with beam.Pipeline(options=PipelineOptions()) as p:
    for i,file in enumerate(file_list):
       (p 
        | "Read Text {}".format(i) >> beam.io.textio.ReadFromText(file, skip_header_lines = 0)
        | "Write TExt {}".format(i) >> beam.io.WriteToText("/home/subject_test_{}".format(i),
                   file_name_suffix=".json", num_shards=1 , append_trailing_newlines = True))

pcols = []
with beam.Pipeline(options=PipelineOptions()) as p:
   for i,res in enumerate(res_list):
         pcol = (p   | 'read_data_{}'.format(i) >> beam.Create([res])
            | "toJson_{}".format(i) >> beam.Map(toJson)
            | "takeItems_{}".format(i) >> beam.FlatMap(lambda line: line["Items"])
            | "takeSubjects_{}".format(i) >> beam.FlatMap(lambda line: line['data']['subjects']))
        pcols.append(pcol)
   out = (pcols
    | beam.Flatten()
    | beam.combiners.Count.PerElement()
    | beam.io.WriteToText("/home/items",
                   file_name_suffix=".txt", num_shards=1 , append_trailing_newlines = True))
© www.soinside.com 2019 - 2024. All rights reserved.