Skip to content

Commit

Permalink
feat(trends): Added smoothing to new trends query runner (PostHog#19578)
Browse files Browse the repository at this point in the history
* Added smoothing to new trends query runner

* Update query snapshots

* Update query snapshots

* Fixed tests

* Update query snapshots

* Updated the name to rolling average

* Fixed snaoshots

* Update query snapshots

---------

Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and jacobwgillespie committed Jan 12, 2024
1 parent ab807fd commit 0ae0364
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
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 @@ -1144,3 +1144,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]

0 comments on commit 0ae0364

Please sign in to comment.