Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(paths): add switch to ignore url query strings (#102537)

jake sciotto01980d31acce
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index bacb6ec05e33..fe1591370d8a 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -447,6 +447,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analytics
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
+ PRODUCT_ANALYTICS_PATHS_STRIP_QUERY_STRING: 'paths-strip-query-string', // owner: #team-product-analytics, gates the "Ignore URL query strings" switch on paths insights
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS: 'product-analytics-quarter-year-intervals', // owner: @sampennington #team-product-analytics, gates quarter/year interval selection on insights
PRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analytics
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a14f45d4c40c..fe579b5c6ecc 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -38341,6 +38341,10 @@
"stepLimit": {
"$ref": "#/definitions/integer",
"default": 5
+ },
+ "stripQueryString": {
+ "description": "Remove the query string from page view URLs, so pages that differ only in query parameters become one path item",
+ "type": "boolean"
}
},
"type": "object"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 1bd7cafabbfc..cea5896628a7 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2267,6 +2267,8 @@ export type PathsFilter = {
minEdgeWeight?: PathsFilterLegacy['min_edge_weight']
maxEdgeWeight?: PathsFilterLegacy['max_edge_weight']
showFullUrls?: boolean
+ /** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */
+ stripQueryString?: boolean
/** Relevant only within actors query */
pathStartKey?: string
/** Relevant only within actors query */
diff --git a/posthog/schema.py b/posthog/schema.py
index bca51440389b..4a07f171f648 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6415,6 +6415,13 @@ class PathsFilter(BaseModel):
showFullUrls: bool | None = None
startPoint: str | None = None
stepLimit: int | None = 5
+ stripQueryString: bool | None = Field(
+ default=None,
+ description=(
+ "Remove the query string from page view URLs, so pages that differ only in"
+ " query parameters become one path item"
+ ),
+ )
class PathsV2Anchor(BaseModel):
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 30ade8d9f0b7..3c20ddc6a31e 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -3871,6 +3871,8 @@ export interface PathsFilterApi {
showFullUrls?: boolean | null
startPoint?: string | null
stepLimit?: number | null
+ /** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */
+ stripQueryString?: boolean | null
}
export interface PathsLinkApi {
diff --git a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py
index 97272995daf0..292db6053473 100644
--- a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py
@@ -2,7 +2,10 @@ import itertools
from collections import defaultdict
from datetime import datetime, timedelta
from math import ceil
-from re import escape
+from re import (
+ compile as re_compile,
+ escape,
+)
from typing import Any, Literal, Optional, cast
from posthog.schema import (
@@ -41,6 +44,10 @@ from posthog.models.user import User
from products.product_analytics.backend.hogql_queries.funnels.funnels_query_runner import FunnelsQueryRunner
from products.product_analytics.backend.hogql_queries.funnels.utils import funnel_window_interval_unit_to_sql
+# ClickHouse `cutQueryString` cuts from the first `?` to the next `#`, so it also cuts the
+# parameters of a hash-routed URL. `urlsplit` reads those as fragment and keeps them.
+QUERY_STRING_PATTERN = re_compile(r"\?[^#]*")
+
EVENT_IN_SESSION_LIMIT_DEFAULT = 5
SESSION_TIME_THRESHOLD_DEFAULT_SECONDS = 30 * 60 # 30 minutes
EDGE_LIMIT_DEFAULT = 50
@@ -103,7 +110,9 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):
ast.CompareOperation(
op=ast.CompareOperationOp.NotIn,
left=ast.Field(chain=["path_item"]),
- right=ast.Constant(value=self.query.pathsFilter.excludeEvents),
+ right=ast.Constant(
+ value=[self._strip_query_string(event) for event in self.query.pathsFilter.excludeEvents]
+ ),
)
)
@@ -118,12 +127,20 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):
return event in (self.query.pathsFilter.includeEventTypes or [])
- @staticmethod
- def _strip_trailing_slash(url: Optional[str]) -> Optional[str]:
- # Mirrors the `(.)/$` regex applied to event URLs in `construct_event_hogql`,
- # so that startPoint/endPoint values match the normalized values stored in
- # `compact_path` / `start_filtered_path`. The bare "/" URL is preserved.
- if url and len(url) > 1 and url.endswith("/"):
+ def _strip_query_string(self, path_item: str) -> str:
+ if self.query.pathsFilter.stripQueryString:
+ return QUERY_STRING_PATTERN.sub("", path_item, count=1)
+ return path_item
+
+ def _normalize_target(self, url: Optional[str]) -> Optional[str]:
+ # Mirrors the normalization applied to event URLs in `construct_event_hogql`,
+ # so that startPoint/endPoint values match the values stored in
+ # `compact_path` / `start_filtered_path`: the query string is cut first when
+ # `stripQueryString` is set, then one trailing slash. The bare "/" URL is preserved.
+ if not url:
+ return url
+ url = self._strip_query_string(url)
+ if len(url) > 1 and url.endswith("/"):
return url[:-1]
return url
@@ -135,9 +152,12 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):
event_hogql = parse_expr(self.query.pathsFilter.pathsHogQLExpression)
if self._should_query_event(PAGEVIEW_EVENT):
+ url_hogql: ast.Expr = parse_expr("ifNull(properties.$current_url, '')")
+ if self.query.pathsFilter.stripQueryString:
+ url_hogql = ast.Call(name="cutQueryString", args=[url_hogql])
event_hogql = parse_expr(
- "if(event = {event}, replaceRegexpAll(ifNull(properties.$current_url, ''), '(.)/$', '\\\\1'), {event_hogql})",
- {"event": ast.Constant(value=PAGEVIEW_EVENT), "event_hogql": event_hogql},
+ "if(event = {event}, replaceRegexpAll({url}, '(.)/$', '\\\\1'), {event_hogql})",
+ {"event": ast.Constant(value=PAGEVIEW_EVENT), "url": url_hogql, "event_hogql": event_hogql},
)
if self._should_query_event(SCREEN_EVENT):
@@ -538,8 +558,8 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):
def get_target_clause(self) -> list[ast.Expr]:
if self.query.pathsFilter.startPoint and self.query.pathsFilter.endPoint:
- start_point = self._strip_trailing_slash(self.query.pathsFilter.startPoint)
- end_point = self._strip_trailing_slash(self.query.pathsFilter.endPoint)
+ start_point = self._normalize_target(self.query.pathsFilter.startPoint)
+ end_point = self._normalize_target(self.query.pathsFilter.endPoint)
clauses: list[ast.Expr] = [
ast.Alias(
alias=f"start_target_index",
@@ -594,7 +614,7 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):
)
def paths_per_person_query(self) -> ast.SelectQuery:
- target_point = self._strip_trailing_slash(self.query.pathsFilter.endPoint or self.query.pathsFilter.startPoint)
+ target_point = self._normalize_target(self.query.pathsFilter.endPoint or self.query.pathsFilter.startPoint)
path_tuples_expr = ast.Call(
name="arrayZip",
diff --git a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
index c0a2808a347f..7e2ff497e427 100644
--- a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
@@ -989,6 +989,80 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(with_trailing_slashes.results, baseline.results)
+ @parameterized.expand(
+ [
+ ("plain_target", "/products", "/products"),
+ ("target_with_query_string", "/products", "/products/?color=blue"),
+ ("hash_routed_target", "/#/products", "/#/products?color=blue"),
+ ]
+ )
+ def test_paths_strip_query_string(self, _name: str, base_url: str, start_point: str) -> None:
+ # Query strings must be cut before the trailing slash strip, so that
+ # `/products/?color=red` merges with `/products` and not only with `/products/`.
+ # The start point gets the same treatment, because the selector offers raw URLs.
+ _create_person(team_id=self.team.pk, distinct_ids=["person_1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person_2"])
+
+ for distinct_id, start_url in (
+ ("person_1", f"{base_url}/?color=red"),
+ ("person_2", f"{base_url}?sort=price"),
+ ):
+ for url in (start_url, "/checkout"):
+ _create_event(
+ properties={"$current_url": url},
+ distinct_id=distinct_id,
+ event="$pageview",
+ team=self.team,
+ )
+
+ separate = PathsQueryRunner(
+ query={"kind": "PathsQuery", "pathsFilter": {"startPoint": start_point}},
+ team=self.team,
+ ).run()
+ assert isinstance(separate, CachedPathsQueryResponse)
+ self.assertEqual(separate.results, [])
+
+ merged = PathsQueryRunner(
+ query={"kind": "PathsQuery", "pathsFilter": {"startPoint": start_point, "stripQueryString": True}},
+ team=self.team,
+ ).run()
+ assert isinstance(merged, CachedPathsQueryResponse)
+ self.assertEqual(len(merged.results), 1)
+ self.assertTrue(
+ merged.results[0].dict().items() >= {"source": f"1_{base_url}", "target": "2_/checkout", "value": 2}.items()
+ )
+
+ def test_paths_strip_query_string_excludes_events(self) -> None:
+ # Exclusions come from the same picker as the start point, so they need the same cut.
+ _create_person(team_id=self.team.pk, distinct_ids=["person_1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person_2"])
+
+ for distinct_id in ("person_1", "person_2"):
+ for url in ("/products?color=red", "/spam?ref=ad", "/checkout"):
+ _create_event(
+ properties={"$current_url": url},
+ distinct_id=distinct_id,
+ event="$pageview",
+ team=self.team,
+ )
+
+ response = PathsQueryRunner(
+ query={
+ "kind": "PathsQuery",
+ "pathsFilter": {
+ "includeEventTypes": ["$pageview"],
+ "stripQueryString": True,
+ "excludeEvents": ["/spam?ref=ad"],
+ },
+ },
+ team=self.team,
+ ).run()
+ assert isinstance(response, CachedPathsQueryResponse)
+ self.assertEqual(len(response.results), 1)
+ self.assertTrue(
+ response.results[0].dict().items() >= {"source": "1_/products", "target": "2_/checkout", "value": 2}.items()
+ )
+
def test_paths_in_window(self):
_create_person(team_id=self.team.pk, distinct_ids=["person_1"])
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index c33cc3ae3440..e72c7b3d2c7a 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2831,6 +2831,8 @@ export interface PathsFilterApi {
showFullUrls?: boolean | null
startPoint?: string | null
stepLimit?: number | null
+ /** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */
+ stripQueryString?: boolean | null
}
export interface PathsLinkApi {
diff --git a/products/product_analytics/frontend/insights/paths/editor/PathsAdvanced.tsx b/products/product_analytics/frontend/insights/paths/editor/PathsAdvanced.tsx
index 690fc5ea6c3b..4ec4d84ee0c4 100644
--- a/products/product_analytics/frontend/insights/paths/editor/PathsAdvanced.tsx
+++ b/products/product_analytics/frontend/insights/paths/editor/PathsAdvanced.tsx
@@ -4,7 +4,9 @@ import { useState } from 'react'
import { LemonInput, LemonSwitch } from '@posthog/lemon-ui'
import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { AvailableFeature, EditorFilterProps, PathEdgeParameters } from '~/types'
@@ -16,7 +18,9 @@ export function PathsAdvanced({ insightProps, ...rest }: EditorFilterProps): JSX
const { pathsFilter } = useValues(pathsDataLogic(insightProps))
const { updateInsightFilter } = useActions(pathsDataLogic(insightProps))
- const { edgeLimit, minEdgeWeight, maxEdgeWeight, showFullUrls } = pathsFilter || {}
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ const { edgeLimit, minEdgeWeight, maxEdgeWeight, showFullUrls, stripQueryString } = pathsFilter || {}
const [localEdgeParameters, setLocalEdgeParameters] = useState<PathEdgeParameters>({
edgeLimit,
@@ -130,6 +134,22 @@ export function PathsAdvanced({ insightProps, ...rest }: EditorFilterProps): JSX
Display complete URLs instead of truncated versions. Useful for comparing paths side-by-side.
</div>
</div>
+
+ {(featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_STRIP_QUERY_STRING] || stripQueryString) && (
+ <div>
+ <LemonSwitch
+ checked={!!stripQueryString}
+ onChange={(checked) => updateInsightFilter({ stripQueryString: checked })}
+ label="Ignore URL query strings"
+ bordered
+ fullWidth
+ />
+ <div className="text-muted text-xs mt-1">
+ Treat page views that differ only in the query string as the same step. For example,
+ /products?color=red and /products both count as /products.
+ </div>
+ </div>
+ )}
</div>
)
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f7c80a0fb315..2f88a0eefbff 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4729,6 +4729,8 @@ export namespace Schemas {
showFullUrls?: boolean | null;
startPoint?: string | null;
stepLimit?: number | null;
+ /** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */
+ stripQueryString?: boolean | null;
}
export interface PathsLink {