From 189cfab89213254cf17a405f284790d2fe4ae76c Mon Sep 17 00:00:00 2001 From: Bonnie Chan <52431539+cbonnie@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:30:20 -0500 Subject: [PATCH 1/2] Create batch_process_storage.py sample Add a new code sample for a batch pipeline that reads CSV sales records from Cloud Storage with ReadFromText, totals sales per product with CombinePerKey, and writes the results back to Cloud Storage with WriteToText. --- dataflow/snippets/batch_process_storage.py | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 dataflow/snippets/batch_process_storage.py diff --git a/dataflow/snippets/batch_process_storage.py b/dataflow/snippets/batch_process_storage.py new file mode 100644 index 00000000000..90dc009ad21 --- /dev/null +++ b/dataflow/snippets/batch_process_storage.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START dataflow_batch_process_storage] +import argparse +from typing import List, Optional, Tuple + +import apache_beam as beam +from apache_beam.options.pipeline_options import PipelineOptions + + +def parse_record(line: str) -> Tuple[str, float]: + """Parses a CSV line into a (product, amount) tuple.""" + _, product, amount = line.split(",") + return product, float(amount) + + +def run(argv: Optional[List[str]] = None) -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", + required=True, + help="Bucket path or glob, such as gs://bucket/input/*.csv", + ) + parser.add_argument( + "--output", + required=True, + help="Bucket path prefix, such as gs://bucket/output/sales", + ) + known_args, pipeline_args = parser.parse_known_args(argv) + + with beam.Pipeline(options=PipelineOptions(pipeline_args)) as pipeline: + ( + pipeline + | "ReadFromGCS" + >> beam.io.ReadFromText(known_args.input, skip_header_lines=1) + | "Parse" >> beam.Map(parse_record) + | "SumByProduct" >> beam.CombinePerKey(sum) + | "Format" >> beam.MapTuple(lambda product, total: f"{product},{total:.2f}") + | "WriteToGCS" + >> beam.io.WriteToText( + known_args.output, + file_name_suffix=".csv", + header="product,total_sales", + ) + ) + + +if __name__ == "__main__": + run() +# [END dataflow_batch_process_storage] From a9d7a98300c58fd301bdcbdfae195f983ae83fc7 Mon Sep 17 00:00:00 2001 From: Bonnie Chan <52431539+cbonnie@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:39:35 -0500 Subject: [PATCH 2/2] Update batch_process_storage.py Add expected input in docstring. Parse rows with the `csv` module. --- dataflow/snippets/batch_process_storage.py | 24 ++++++++++++---------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/dataflow/snippets/batch_process_storage.py b/dataflow/snippets/batch_process_storage.py index 90dc009ad21..db3c9ba2101 100644 --- a/dataflow/snippets/batch_process_storage.py +++ b/dataflow/snippets/batch_process_storage.py @@ -12,27 +12,32 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - # [START dataflow_batch_process_storage] import argparse +import csv from typing import List, Optional, Tuple - import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions - - def parse_record(line: str) -> Tuple[str, float]: """Parses a CSV line into a (product, amount) tuple.""" - _, product, amount = line.split(",") + _, product, amount = next(csv.reader([line])) return product, float(amount) - - def run(argv: Optional[List[str]] = None) -> None: + """Calculates total sales for each product from CSV files. + Each input file must start with a header row, which the pipeline skips. + Every other row must have three columns: order ID, product, and amount. + Fields can be quoted, such as "widget, large", but can't contain line + breaks. A blank line, a missing field, or a non-numeric amount causes the + job to fail. + """ parser = argparse.ArgumentParser() parser.add_argument( "--input", required=True, - help="Bucket path or glob, such as gs://bucket/input/*.csv", + help=( + "CSV files with a header row and three columns: order ID, product, " + "amount. Use a bucket path or glob, such as gs://bucket/input/*.csv" + ), ) parser.add_argument( "--output", @@ -40,7 +45,6 @@ def run(argv: Optional[List[str]] = None) -> None: help="Bucket path prefix, such as gs://bucket/output/sales", ) known_args, pipeline_args = parser.parse_known_args(argv) - with beam.Pipeline(options=PipelineOptions(pipeline_args)) as pipeline: ( pipeline @@ -56,8 +60,6 @@ def run(argv: Optional[List[str]] = None) -> None: header="product,total_sales", ) ) - - if __name__ == "__main__": run() # [END dataflow_batch_process_storage]