Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(trends): Added smoothing to new trends query runner #19578

Merged
merged 8 commits into from
Jan 5, 2024
Merged
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
28 changes: 28 additions & 0 deletions posthog/hogql_queries/insights/trends/query_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,34 @@ def _inner_select_query(self, inner_query: ast.SelectQuery | ast.SelectUnionQuer
),
)

if (
self.query.trendsFilter is not None
and self.query.trendsFilter.smoothing_intervals is not None
and self.query.trendsFilter.smoothing_intervals > 1
):
rolling_average = ast.Alias(
alias="count",
expr=ast.Call(
name="floor",
args=[
ast.WindowFunction(
name="avg",
args=[ast.Call(name="sum", args=[ast.Field(chain=["total"])])],
over_expr=ast.WindowExpr(
order_by=[ast.OrderExpr(expr=ast.Field(chain=["day_start"]), order="ASC")],
frame_method="ROWS",
frame_start=ast.WindowFrameExpr(
frame_type="PRECEDING",
frame_value=int(self.query.trendsFilter.smoothing_intervals - 1),
),
frame_end=ast.WindowFrameExpr(frame_type="CURRENT ROW"),
),
)
],
),
)
query.select = [rolling_average]

query.group_by = []
query.order_by = []

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1100,3 +1100,17 @@ def test_properties_filtering_with_materialized_columns_and_empty_string_as_prop
)

assert response.results[0]["data"] == [1]

def test_smoothing(self):
self._create_test_events()

response = self._run_trends_query(
"2020-01-09",
"2020-01-20",
IntervalType.day,
[EventsNode(event="$pageview")],
TrendsFilter(smoothing_intervals=7),
None,
)

assert response.results[0]["data"] == [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]
Loading