Skip to content

Create batch_process_storage.py sample - #14993

Open
cbonnie wants to merge 1 commit into
mainfrom
cbonnie-patch-1
Open

cbonnie wants to merge 1 commit into
mainfrom
cbonnie-patch-1

Conversation

@cbonnie

@cbonnie cbonnie commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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.

Description

Fixes # http://b/589715201

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

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.
@cbonnie
cbonnie requested review from a team as code owners November 23, 2026 16:31
@snippet-bot

snippet-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added the samples Issues that are directly related to samples. label Nov 23, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a new Apache Beam pipeline snippet in Python (batch_process_storage.py) that reads CSV data from Google Cloud Storage, aggregates sales amounts by product, and writes the results back to GCS. The review feedback highlights a potential issue where parsing CSV lines using a simple split(',') without error handling could crash the pipeline on malformed rows. To make the pipeline more resilient, the reviewer suggests refactoring parse_record to yield parsed records safely within a try-except block, importing Iterable for typing, and updating the pipeline step to use beam.FlatMap instead of beam.Map.


# [START dataflow_batch_process_storage]
import argparse
from typing import List, Optional, Tuple

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

Import Iterable from typing to support the updated type signature for parse_record when yielding elements.

Suggested change
from typing import List, Optional, Tuple
from typing import Iterable, List, Optional, Tuple

Comment on lines +24 to +27
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)

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

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant