Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ replacements:
FindNearestOptions,
Ordering,
PipelineDataType,
RangeWindowFrame,
SampleOptions,
SearchOptions,
TimeGranularity,
Expand Down Expand Up @@ -221,6 +222,7 @@ replacements:
"PipelineSource",
"PipelineStream",
"Query",
"RangeWindowFrame",
"ReadAfterWriteError",
"SERVER_TIMESTAMP",
"SampleOptions",
Expand Down Expand Up @@ -304,6 +306,7 @@ replacements:
PipelineSource,
PipelineStream,
Query,
RangeWindowFrame,
ReadAfterWriteError,
SampleOptions,
SearchOptions,
Expand Down Expand Up @@ -374,6 +377,7 @@ replacements:
"PipelineSource",
"PipelineStream",
"Query",
"RangeWindowFrame",
"ReadAfterWriteError",
"SERVER_TIMESTAMP",
"SampleOptions",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
PipelineSource,
PipelineStream,
Query,
RangeWindowFrame,
ReadAfterWriteError,
SampleOptions,
SearchOptions,
Expand Down Expand Up @@ -141,6 +142,7 @@
"PipelineSource",
"PipelineStream",
"Query",
"RangeWindowFrame",
"ReadAfterWriteError",
"SERVER_TIMESTAMP",
"SampleOptions",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
FindNearestOptions,
Ordering,
PipelineDataType,
RangeWindowFrame,
SampleOptions,
SearchOptions,
TimeGranularity,
Expand Down Expand Up @@ -198,6 +199,7 @@
"PipelineSource",
"PipelineStream",
"Query",
"RangeWindowFrame",
"ReadAfterWriteError",
"SERVER_TIMESTAMP",
"SampleOptions",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -386,13 +386,47 @@ def _to_dict(self) -> dict[str, Value]:
return {"documents": self._to_pb()}


@dataclass
class RangeWindowFrame(_WindowFrame):
"""Defines a value-based or time-range window frame relative to the current document's sort value.

Example:
>>> from google.cloud.firestore_v1.pipeline_expressions import Field
>>> from google.cloud.firestore_v1.pipeline_types import (
... RangeWindowFrame,
... TimeUnit,
... WindowBound,
... WindowSpec,
... )
>>> window = WindowSpec(
... sort=Field.of("time").ascending(),
... frame=RangeWindowFrame(12, WindowBound.CURRENT, unit=TimeUnit.HOUR),
... )
Comment thread
ohmayr marked this conversation as resolved.
Resolved

Args:
preceding: The lower bound of the frame (a numeric offset, `WindowBound`, or `Expression`).
following: The upper bound of the frame (a numeric offset, `WindowBound`, or `Expression`).
unit: Optional duration unit for time-range frames (e.g., `TimeUnit.DAY`, `TimeGranularity.MONTH`,
`"day"`, or an `Expression`).
"""

preceding: WindowBound | str | int | float | pipeline_expressions.Expression
following: WindowBound | str | int | float | pipeline_expressions.Expression
unit: Optional[
TimeUnit | TimeGranularity | str | pipeline_expressions.Expression
] = None
Comment on lines +413 to +417

@ohmayr ohmayr Nov 18, 2026 •

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.

Design Note — Separate RangeWindowFrame Dataclass & _to_dict():

  • Chosen Design: Keep RangeWindowFrame as a distinct @dataclass from DocumentWindowFrame (inheriting _to_pb() from _WindowFrame and exposing _to_dict() -> {"range": self._to_pb()}), and widen WindowSpec(frame=...) to Optional[DocumentWindowFrame | RangeWindowFrame] = None.
  • Alternatives Considered & Why Rejected:
    • Merging DocumentWindowFrame and RangeWindowFrame into a single class: RangeWindowFrame accepts float offsets and an optional unit (TimeUnit | TimeGranularity | str | Expression), whereas DocumentWindowFrame only accepts integer/symbolic row counts and has no unit. Keeping them separate prevents invalid combinations like passing a time unit or float offset to a document-count frame, while _to_dict() lets WindowSpec._to_pb() remain completely unchanged.


def _to_dict(self) -> dict[str, Value]:
return {"range": self._to_pb()}


class WindowSpec:
"""Configuration for a window in an `AddWindowFields` pipeline stage.

Args:
partition: Field paths or expressions used to partition documents into independent windows.
sort: Orderings specifying how documents are sorted within each partition.
frame: A `DocumentWindowFrame` defining a document-count window frame.
frame: A `DocumentWindowFrame` or `RangeWindowFrame` defining a sliding window frame.
"""

def __init__(
Expand All @@ -404,7 +438,7 @@ def __init__(
| str
] = None,
sort: Optional[Sequence[Ordering] | Ordering] = None,
frame: Optional[DocumentWindowFrame] = None,
frame: Optional[DocumentWindowFrame | RangeWindowFrame] = None,
):
if partition is None:
partition_list = []
Expand All @@ -422,7 +456,7 @@ def __init__(
else:
self.sort = [sort] if isinstance(sort, Ordering) else list(sort)

self.frame: Optional[DocumentWindowFrame] = frame
self.frame: Optional[DocumentWindowFrame | RangeWindowFrame] = frame

def __eq__(self, other: object) -> bool:
if not isinstance(other, WindowSpec):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,80 @@ tests:
title:
fieldReferenceValue: title
name: select
- description: "testAddWindowFields - range frame with time unit"
pipeline:
- Collection: timestamps
- AddWindowFields:
window:
WindowSpec:
sort:
- Ordering:
- Field: time
- ASCENDING
frame:
RangeWindowFrame:
preceding: 12
following: current
unit: hour
fields:
- AliasedExpression:
- Count
- "window_count"
- Select:
- window_count
assert_results:
- window_count: 1
assert_proto:
pipeline:
stages:
- args:
- referenceValue: /timestamps
name: collection
- args:
- mapValue:
fields:
range:
mapValue:
fields:
following:
stringValue: current
preceding:
integerValue: '12'
unit:
stringValue: hour
sort:
arrayValue:
values:
- mapValue:
fields:
direction:
stringValue: ascending
expression:
fieldReferenceValue: time
- mapValue:
fields:
window_count:
functionValue:
name: count
name: add_window_fields
- args:
- mapValue:
fields:
window_count:
fieldReferenceValue: window_count
name: select
- description: "testAddWindowFields - error on range frame without sort"
pipeline:
- Collection: books
- AddWindowFields:
window:
WindowSpec:
frame:
RangeWindowFrame:
preceding: unbounded
following: current
fields:
- AliasedExpression:
- Count
- "window_count"
assert_error: ".*range.*"
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
)
from google.cloud.firestore_v1.pipeline_types import (
DocumentWindowFrame,
RangeWindowFrame,
TimeGranularity,
TimeUnit,
WindowBound,
WindowSpec,
)
Expand Down Expand Up @@ -1083,13 +1086,38 @@ def test_document_window_frame_to_pb(self):
assert frame._to_dict() == {"documents": pb}
assert frame == DocumentWindowFrame(1, "current")
assert frame != DocumentWindowFrame(2, WindowBound.CURRENT)
assert frame != RangeWindowFrame(1, WindowBound.CURRENT)

expr_pb = DocumentWindowFrame(Field.of("offset"), "unbounded")._to_pb()
assert expr_pb.map_value.fields == {
"preceding": Value(field_reference_value="offset"),
"following": Value(string_value="unbounded"),
}

@pytest.mark.parametrize(
"unit,expected_unit",
[
(TimeUnit.DAY, "day"),
(TimeGranularity.MONTH, "month"),
("hour", "hour"),
(Constant.of("minute"), "minute"),
],
)
def test_range_window_frame_to_pb(self, unit, expected_unit):
no_unit_pb = RangeWindowFrame(10, 20)._to_pb()
assert no_unit_pb.map_value.fields == {
"preceding": Value(integer_value=10),
"following": Value(integer_value=20),
}
frame = RangeWindowFrame(10.5, WindowBound.UNBOUNDED, unit)
pb = frame._to_pb()
assert pb.map_value.fields == {
"preceding": Value(double_value=10.5),
"following": Value(string_value="unbounded"),
"unit": Value(string_value=expected_unit),
}
assert frame._to_dict() == {"range": pb}

def test_window_spec_coercions(self):
order = Field.of("rating").descending()
assert WindowSpec().partition == []
Expand Down Expand Up @@ -1128,6 +1156,17 @@ def test_window_spec_repr_and_equality(self):
sort=Field.of("rating").descending(),
frame=DocumentWindowFrame(0, WindowBound.CURRENT),
)
range_spec = WindowSpec(
sort=Field.of("published").ascending(),
frame=RangeWindowFrame(-5, 5, "day"),
)
assert repr(range_spec) == (
"WindowSpec("
"sort=[Field.of('published').ascending()], "
"frame=RangeWindowFrame(preceding=-5, following=5, unit='day')"
")"
)
assert spec != range_spec
assert spec != empty
assert spec != object()

Expand All @@ -1143,6 +1182,12 @@ def test_window_spec_to_pb(self):
"sort": Value(array_value={"values": [order._to_pb()]}),
"documents": doc_frame._to_pb(),
}
range_frame = RangeWindowFrame(-5, 5, "day")
range_spec = WindowSpec(sort=order, frame=range_frame)
assert range_spec._to_pb().map_value.fields == {
"sort": Value(array_value={"values": [order._to_pb()]}),
"range": range_frame._to_pb(),
}


class TestAddWindowFields:
Expand Down
Loading