Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions dataflow/snippets/batch_process_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/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
import csv
from typing import List, Optional, Tuple
Comment thread
iennae marked this conversation as resolved.
Resolved
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 = next(csv.reader([line]))
return product, float(amount)
Comment on lines +21 to +24

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Parsing CSV lines directly using split(',') without error handling can crash the entire pipeline if there are empty lines, headers, or malformed rows (e.g., raising ValueError during unpacking or float conversion).

Using a generator that yields results only on successful parsing, combined with beam.FlatMap, makes the pipeline resilient to malformed input.

Suggested change
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 parse_record(line: str) -> Iterable[Tuple[str, float]]:
"""Parses a CSV line into a (product, amount) tuple."""
try:
parts = line.split(",")
if len(parts) >= 3:
yield parts[1], float(parts[2])
except ValueError:
pass

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, but I'm keeping parse_record as is on purpose. This is a docs snippet, so the goal is to show the core read → parse → aggregate → write pattern as clearly as possible.

  • The header row is already handled by ReadFromText(..., skip_header_lines=1), and the sample assumes well-formed input.

  • except ValueError: pass would silently drop bad rows and produce wrong totals with no signal. I'd rather not teach readers that pattern. In production you'd send bad records to a dead-letter output, which is beyond the scope of this snippet.

  • len(parts) >= 3 would also quietly accept rows with extra columns, which hides a different kind of bad data.

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=(
"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",
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use beam.FlatMap instead of beam.Map to support the generator-based parse_record function, which filters out malformed or empty rows gracefully.

Suggested change
| "Parse" >> beam.Map(parse_record)
| "Parse" >> beam.FlatMap(parse_record)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not adopting: FlatMap is only needed if parse_record becomes a generator, which I'm declining (see the thread on that function). Since parse_record returns exactly one (product, amount) tuple per line, beam.Map is the right transform.

| "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]
Loading