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(marketing): combine paid and organic search in ad performance (#106989)

Javier Bahamondes82ac607a8003
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.md
index 800e64e2a5cf..3946dfe9298e 100644
--- a/docs/internal/web-analytics-query-serving.md
+++ b/docs/internal/web-analytics-query-serving.md
@@ -66,6 +66,36 @@ request
A miss costs one live-path serve; the background warm makes the next identical request a bucket hit.
The dashboard "enqueues precompute" as a side effect; it never waits on it.
+## Marketing search performance
+
+`MarketingAnalyticsSearchQuery` reads synced ad-platform tables through HogQL and the query result cache, independently of the web-event serving tiers above.
+Google Ads requires the `keyword` and `keyword_stats` tables for keywords, and `landing_page_stats` for landing pages; Bing Ads supports keywords through `keyword_performance_report`.
+Google Search Console uses `search_analytics_by_query` or `search_analytics_by_page` for aggregate views, with `search_analytics_by_query_page` as a fallback and for exact query-to-page and page-to-query details.
+The query only selects one GSC table per source, so syncing both aggregate and detailed tables does not multiply metrics.
+The integration and channel filters keep paid and organic rows separate.
+GSC does not report spend or conversions; these values remain null.
+Organic position is weighted by impressions in each period, while CTR uses summed clicks divided by summed impressions.
+Traffic shows position instead of cost for organic-only selections; mixed selections can add position with the Show position checkbox.
+Comparison colors show increases in impressions as positive and increases in cost, CPC, CPA or position as negative.
+Query and page breakdowns can omit low-volume queries and differ from property totals.
+The Search performance section sits below the campaign table in Ad performance, behind `marketing-analytics-organic-keywords` in both dashboards.
+It shares the integration, date and comparison filters with the campaign table.
+The integration filter and Add source menu list Google Search Console separately under Organic search.
+Empty filtered results offer Clear filters; unfiltered views suggest connecting missing Google Ads or Google Search Console sources.
+Connected sources with missing tables show a sync setup action instead of a reconnect prompt.
+Source discovery loads every page of connected integrations before applying the filter.
+The date and comparison controls select the current and comparison periods.
+Organic query and page details retain the selected integration sources.
+Paid keyword and page details use the available GSC sources to find organic results for the same text or URL.
+Cached results are partitioned by warehouse table, view, and source permissions.
+Metrics group targeted keywords by platform, match type and account currency; spend is never added across currencies.
+Conversions retain the ad platform's attribution, while CTR, CPC and CPA use the summed metrics in each period.
+Comparison includes keywords present in either period and applies the top-100 limit after matching the periods.
+The query type tag is `marketing_analytics_search_query`.
+
+Source connection links use `returnLabel=Marketing analytics`, including search setup suggestions and details.
+The `warehouse source connect completed` event records this label after the creation API succeeds, so connections started here can be attributed to Marketing analytics.
+
## Per-runner dispatch
### WebOverviewQuery (`web_overview.py`)
@@ -189,6 +219,7 @@ Conversion goal property filters accept event, person, session and cohort filter
Marketing Analytics query errors show a query ID when the request has one.
Use that ID to find the failed request in the query log.
+Search performance uses the same error banner, including in query and landing-page details.
The error's query ID takes precedence over the current request ID; a previous successful response is not a source for the error ID.
Errors outside the query path, such as configuration failures, may have no query ID.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 53a8ad02e8ad..88bc8ea9ad40 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11734,6 +11734,90 @@ snapshots:
hash: v1.k794b7964.71ad45e65a5513ff7088e026d8ffb2bf891fb1effddb0e9dbd95ba78b597c3b1.0e6bNu95d2bH_NlZmGGW7oiHJ__aHNSxqzRcxMUA4xM
scenes-app-marketing-analytics-freshness--fresh--light:
hash: v1.k794b7964.b8d9453c270c310350d2bcf30cdb54cae4da19b8877e8d3206160478eb2dda94.dJpt6MIMxg7mOxiHC6PoqwTGwMfiGrln7SheHTKHTcU
+ scenes-app-marketing-analytics-search-performance--awaiting-sync--dark:
+ hash: v1.k794b7964.9d8eec78fb7621fa32363daf0190898cb58113226a3b97ab564057c12399d1ce.gC-HZMskxryXdiDccRsq7kft4ozwhNtMhMU1cX9__2o
+ scenes-app-marketing-analytics-search-performance--awaiting-sync--light:
+ hash: v1.k794b7964.9a6ee81e77cfe8c5a3b432480754b1e1d68f8bd6e26744fc9281728dd33e2299.WE2_FirF5AFc0ouzNiOtwr_BsrMZ8WqrkpTHYSXCspY
+ scenes-app-marketing-analytics-search-performance--comparison--dark:
+ hash: v1.k794b7964.de77865816c9cd27388687b2ec104f69a0940f558f33eeb71209f88972fb39e6.myT4UFo_7h3EJKHq1MYkev21vFTvp4RNgINtO1ksSq4
+ scenes-app-marketing-analytics-search-performance--comparison--light:
+ hash: v1.k794b7964.3a07a766dc08ac96ba406cb6153891d8f10b584310988fe5b3b32e4a811913ca.kX6QW9MEMPD1GbEM0t9RqInZmYf_NxROL-dajwye5R0
+ scenes-app-marketing-analytics-search-performance--connected--dark:
+ hash: v1.k794b7964.7e7cba08fd2a92d8d592f8b94029add87188f12456022474be3ffd55062c8f22.N-4ZkymPxMsT663wMCBB7Ii29kEfTEDcE3ZCYfKzG2M
+ scenes-app-marketing-analytics-search-performance--connected--light:
+ hash: v1.k794b7964.bd0086bce9bb1022159713ae37406c793dbf66e7566874f54a2e0cc0e4018147.h_kAiuk7GSEAW0fPzPdeVlkWtxcjIb8-rCRiaLJgURo
+ scenes-app-marketing-analytics-search-performance--empty--dark:
+ hash: v1.k794b7964.34461d7967f4b8ce1ffd14ec9dcb15417e2c7c97009986b68db1f95bd5c7a06e.uUv6tzgsVcG49QjJBcE7cLiqZ1xBdttc79pMmH5ipoU
+ scenes-app-marketing-analytics-search-performance--empty--light:
+ hash: v1.k794b7964.e2eb2d1d5fd47902bd3d051bb36865f72f7b4c29fe41503b30ba9742a12be1db.WcPH098LFmfS_UEVPe1pWom_AB4rOMCEKqL8-sBDG3g
+ scenes-app-marketing-analytics-search-performance--empty-google-ads--dark:
+ hash: v1.k794b7964.c9b5ec6c2246b144b2f26cd1c523528a973264c7f5f7858c6463f386fd30ea3e.3tVsUjDGQzl71QxRX9IuINaZuRmIZ13uWNGEmFSXuXU
+ scenes-app-marketing-analytics-search-performance--empty-google-ads--light:
+ hash: v1.k794b7964.005ecc67553df9f22035aac5510de167d408e22dab217e11a9d2943208c27340.YV6Ds9HZ81jq1GMORJU7Ba97jIMaiDzQdribdFSTK3I
+ scenes-app-marketing-analytics-search-performance--empty-organic--dark:
+ hash: v1.k794b7964.5064ba1b4ed115f916aaa26730dfdaa98544b2e007560f682562e8809f19d2f8.wX92jPGk1eiM18RdObXQH0A_KxwPzQMVv9i1zGUr-AQ
+ scenes-app-marketing-analytics-search-performance--empty-organic--light:
+ hash: v1.k794b7964.4b63d3789d298fdf1c3b0821abf21d09d8dab2e94b3ffd5777b2c82ea60aacb7.22ODULeUbrPxnek6uiaZfciJ8X293GeWC36sks4M5P8
+ scenes-app-marketing-analytics-search-performance--filtered-empty--dark:
+ hash: v1.k794b7964.5a9f71b9e8dc9daea87186d4cd050d8dd117ea189fabdc7a5f3db1b201c8eca7.9EVyaH52ohgljYugkbLOfanaz8ATeZIrH79ckbpDhyc
+ scenes-app-marketing-analytics-search-performance--filtered-empty--light:
+ hash: v1.k794b7964.3b2e75a06d33ff24f87e5ec37d3b43a6f7b6b8a415f29f279da4374ab6da9203.6bY2c2Mv49_GgRBPd4W1iVP55YB4Uh2suIHNOGuvIB8
+ scenes-app-marketing-analytics-search-performance--flag-off--dark:
+ hash: v1.k794b7964.0abe2d58ee70ac24582205caacee0e0b09831b9f04687d5ee1d9ec28f7f99be8.23pCSt9pA4N6R0id0jXh6Z0GpGSmmifTz1Ur090dRnY
+ scenes-app-marketing-analytics-search-performance--flag-off--light:
+ hash: v1.k794b7964.9336af8fdbf0c10e0dadbdc398517b3856ad19eae7ff0f580ddd507e4202b57b.92lmvS4XqmLPpRq2h7e7R_7p8x2ZpdvIaIAKZRL4lQU
+ scenes-app-marketing-analytics-search-performance--landing-pages--dark:
+ hash: v1.k794b7964.62ba6335df58e3073ae81e43aacbbd8fa1c77f7265c489e863f5e622358af4ea.FmrnlcNqxK5iLB3-xr613EDWIG4BcMBYFKUr98gTVvo
+ scenes-app-marketing-analytics-search-performance--landing-pages--light:
+ hash: v1.k794b7964.4deaf12c332971e15f972d0dec3fbd0c3e3343325a536e50dee92934d14f82ff.nigxzpdupH3jx2rXs9f2DD35x1rF8S_8f74GpuxF9Lg
+ scenes-app-marketing-analytics-search-performance--legacy-scene--dark:
+ hash: v1.k794b7964.e1a1cd0478c83cc6c150eb12c9837bd7b7fd7d872705e139d2b08de1bf018a58.OhnJFpYwlPc4WV77AvPUqIkDwfDvl95fp_WVW7-YMYc
+ scenes-app-marketing-analytics-search-performance--legacy-scene--light:
+ hash: v1.k794b7964.dc413b12807c31404bcdd873241896e93be4370709c5ee835a0c87b56036a915.UpUU6ytDVZGvNerlIWADPg5rePR6zuK5jJTggzp86Wo
+ scenes-app-marketing-analytics-search-performance--loading--dark:
+ hash: v1.k794b7964.4ba1991cfbec1d2f9021f4136422b78677c16c06e82e842ada1675285697ba17.PEoFpBSF83Z_XSvI-3lbtBiiR88CkBMDyeYIGfwRBAU
+ scenes-app-marketing-analytics-search-performance--loading--light:
+ hash: v1.k794b7964.6fa7ec534c2d437ef8e4b3eea0cf9a4dae6f563d83845c244e7606713ad45ad2.q3RCwJnX9_AvFC--GxFS1hzZE_yBb6ZYaZN13FGskqk
+ scenes-app-marketing-analytics-search-performance--mixed-with-position--dark:
+ hash: v1.k794b7964.e681bf200d6449ce85ffd47136501877275e2e1a97d5e123fd83115530655530.JMAKwF3_NHTX2GUk5tltwknAFGkQfJ9hMzRrkckKTB8
+ scenes-app-marketing-analytics-search-performance--mixed-with-position--light:
+ hash: v1.k794b7964.6d20b67a5a88bf169da70120076817051563636d6af8da313684c073f6566340.CXgPKeJ3XF6HTb5g-UtwebIrLdSHaf4C2sMoNXgsCjo
+ scenes-app-marketing-analytics-search-performance--narrow--dark:
+ hash: v1.k794b7964.c5787918b5a15cda4554b6aecfc2698d055071431c3f5b7840260d729bf17a8e.qVa2781gXbGtsKtYdDOEWYD25JdqPFBhA6NyxMm8I4A
+ scenes-app-marketing-analytics-search-performance--narrow--light:
+ hash: v1.k794b7964.f637172b9288f0dfc71ca19ab958b18e1753555fddad99bbc9ad4b86e31ce4bb.8VLmbtNtwb_RGD6pNLkxbn7xrq4iOiw-mEO3w1AXtU4
+ scenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--dark:
+ hash: v1.k794b7964.0c4717a3153f03b74a312e8e79100ec690a2ac8a1d8d85cb7c421f5067e51c7d.sxdLEuVX_WLCLstsn7cuNtEezNpbqOAursDJLb5dw4g
+ scenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--light:
+ hash: v1.k794b7964.ef8abc62d8e9547d67820fb48ffbf25d1aa0ba0af9ce11cf417f3d7baa74407c.IQ6fSvFK1NvWDUrnpGHITZ-EoiRtjjHKBjQkRsMBFOc
+ scenes-app-marketing-analytics-search-performance--new-dashboard-scene--dark:
+ hash: v1.k794b7964.954ab6db3a1ea9f1415f77621758c5f581de41404c78a7d62043405917601fee.E7v-3te32i4yZ_sjxn4ZB3BkNYEgE0jkTqqC8rixlW0
+ scenes-app-marketing-analytics-search-performance--new-dashboard-scene--light:
+ hash: v1.k794b7964.3d4ecb3ad7e6f61f79ef8880ef0da91989ed2a10aad85329a7157ddef86f67e3.Fedmk6GlIgi7vls11B0OzCZh_spofEzcYNa5tfUPoXU
+ scenes-app-marketing-analytics-search-performance--not-connected--dark:
+ hash: v1.k794b7964.fc45f91fd10720c94e64d84bd64d043e472d35c7be2a2c813f98a627fbbd93be.OvmqVf3mYSyJ_wXsOKvp-LWwhymTTD6MbSikTmLg564
+ scenes-app-marketing-analytics-search-performance--not-connected--light:
+ hash: v1.k794b7964.d26e073f6322a6a5408b4b612361749f47d3b4cba38a82caf6210215db7b339a.c0EL08UuZQQZ3H5Euck3vSNLJSImyrOkGtYHoZOLzH4
+ scenes-app-marketing-analytics-search-performance--only-google-ads--dark:
+ hash: v1.k794b7964.5e99b1ab76b75bebe10c2fca4c9967c1f8cb88d51135c3dab693d6543eae552f.KJGtm4WW3yiaCLSEKmiv-1fK4NT7OtY46UitdFbHDIo
+ scenes-app-marketing-analytics-search-performance--only-google-ads--light:
+ hash: v1.k794b7964.5a146e648c99a7640f2ba606c460262fa0f21382418a3e31610ff01f2ae3c7a7.fO49F5DmX_6-6z_SBYOyObOYuURgpqCvd1lvP8K4YS8
+ scenes-app-marketing-analytics-search-performance--organic-detail--dark:
+ hash: v1.k794b7964.fe5f6ebd2a1231c17655affa0d186614cde3df91815e14d11f911541985e4f83.BOf_tOoVHYYhLKTXqW-FtKMnM6RsvxZkkxYxRwFKO6M
+ scenes-app-marketing-analytics-search-performance--organic-detail--light:
+ hash: v1.k794b7964.b6cc067106fba330646ceecf9d0b45682e1ae150e5d10ae7faee2020b27768ef.4wdqjU_68A79aSSZcYCmkZoI5TOSoxuZSXkwRZYDutA
+ scenes-app-marketing-analytics-search-performance--organic-traffic--dark:
+ hash: v1.k794b7964.73bd26e879d93440854f347ed6d2ff5158495ccbd933398588abbf8032945275.MTHT41OlrtA2hiTk_55qnI4eS6LEkM7ku2j_EUlZ_BE
+ scenes-app-marketing-analytics-search-performance--organic-traffic--light:
+ hash: v1.k794b7964.bee955a5a256a88130f02056f26e41c3f6a7d01af3b6db9e6c8f584ae71a4916.N8iyGqfll5D_HYoEPwcK2vlTnY50f56Il6axuJ6mLVY
+ scenes-app-marketing-analytics-search-performance--query-error--dark:
+ hash: v1.k794b7964.a5419c8a09ca30185fc876c1631efb87ce8d017398ebcced2fa8d652e21f2384.GT50JRsrPVWV-OG5VIDpTgX8_wzYvIMrjseLhp24jxY
+ scenes-app-marketing-analytics-search-performance--query-error--light:
+ hash: v1.k794b7964.ecd5c42494875619896ac40e97c94efea4ef51df3cab4f0646a000f005e974e4.LWCo5x4I9pjALUEuT-YmxUgd5rCRDgOMJbCAHUpUzKQ
+ scenes-app-marketing-analytics-search-performance--sources-error--dark:
+ hash: v1.k794b7964.874d4819628e188381b6b9c0c7799b572d512e05a3ef968fd5bce45fe72df26b.34-FVEAK6yWUfN6uBxYIlsg7eEov6vFa4oCCKG82J7s
+ scenes-app-marketing-analytics-search-performance--sources-error--light:
+ hash: v1.k794b7964.159cf8b9647d98ad2c63ce40109229e9ffd0352de1d98167b9446794a947ff21.gupk_qTVysxLVkierQb3CrLvQ4-AtOFEXoQ4yuxHtlU
scenes-app-marketing-analytics-source-status--source-issues--dark:
hash: v1.k794b7964.f387ac40dbf399676c91b2f6de86c2b169e9aaa86205af692abf51a141ead5d7.3PpHqWiSeMKvXuYLv4lU1yM_tqF38xD4NiUkUX6XW2U
scenes-app-marketing-analytics-source-status--source-issues--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7170d2d24e24..b9b037c57aef 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -411,6 +411,7 @@ export const FEATURE_FLAGS = {
MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_NEW_DASHBOARD: 'new-marketing-analytics-dashboard', // owner: @jabahamondes #team-web-analytics — gates the redesigned dashboard and all of its sections
MARKETING_ANALYTICS_OPENAI_ADS: 'marketing-analytics-openai-ads', // owner: @jabahamondes #team-web-analytics
+ MARKETING_ANALYTICS_ORGANIC_KEYWORDS: 'marketing-analytics-organic-keywords', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_RETENTION: 'marketing-analytics-retention', // owner: @jabahamondes #team-web-analytics — gates the legacy Retention explorer tab; the new dashboard ignores it
MARKETING_ANALYTICS_RETURN_METRICS: 'marketing-analytics-return-metrics', // owner: @jabahamondes #team-web-analytics — gates the ROAS column
MARKETING_ANALYTICS_ROKT_ADS: 'marketing-analytics-rokt-ads', // owner: @jabahamondes #team-web-analytics
@@ -428,8 +429,8 @@ export const FEATURE_FLAGS = {
METRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)
METRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entries
METRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics charts
- METRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit mode
METRICS_FUNDAMENTALS: 'metrics-fundamentals', // owner: #team-apm (@jonmcwest, @frankh), gates the Fundamentals tab and the explain API behind it, which check the metrics viewer's own reductions
+ METRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit mode
ML_INFERENCE_DECISIONS: 'ml-inference-decisions', // owner: #team-ai-research, gates the decisions playground; the API checks the same flag server side
NEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-ux
NEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analytics
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index ca24fbd42de2..4a00ba9bc5ff 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1684,6 +1684,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsRetentionQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsSearchQuery"
+ },
{
"$ref": "#/definitions/WebOverviewQuery"
},
@@ -12623,6 +12626,110 @@
],
"type": "object"
},
+ "CachedMarketingAnalyticsSearchQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_scan": {
+ "$ref": "#/definitions/QueryScanSummary",
+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsSearchRow"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "cache_key",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedMarketingAnalyticsTableQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -35793,6 +35900,241 @@
"enum": ["string", "integer", "number", "float", "datetime", "date", "boolean"],
"type": "string"
},
+ "MarketingAnalyticsSearchMetrics": {
+ "additionalProperties": false,
+ "properties": {
+ "clicks": {
+ "type": "number"
+ },
+ "conversions": {
+ "type": ["number", "null"]
+ },
+ "cost": {
+ "type": ["number", "null"]
+ },
+ "cpa": {
+ "type": ["number", "null"]
+ },
+ "cpc": {
+ "type": ["number", "null"]
+ },
+ "ctr": {
+ "type": ["number", "null"]
+ },
+ "impressions": {
+ "type": "number"
+ },
+ "position": {
+ "type": ["number", "null"]
+ }
+ },
+ "required": ["clicks", "impressions", "cost", "conversions", "ctr", "cpc", "cpa"],
+ "type": "object"
+ },
+ "MarketingAnalyticsSearchQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "breakdown": {
+ "enum": ["keyword", "page"],
+ "type": "string"
+ },
+ "compareFilter": {
+ "$ref": "#/definitions/CompareFilter"
+ },
+ "dateRange": {
+ "$ref": "#/definitions/DateRange"
+ },
+ "keyword": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "MarketingAnalyticsSearchQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "page": {
+ "type": "string"
+ },
+ "response": {
+ "$ref": "#/definitions/MarketingAnalyticsSearchQueryResponse"
+ },
+ "search": {
+ "type": "string"
+ },
+ "sources": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsSearchSource"
+ },
+ "type": "array"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["kind", "sources"],
+ "type": "object"
+ },
+ "MarketingAnalyticsSearchQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsSearchRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
+ "MarketingAnalyticsSearchRow": {
+ "additionalProperties": false,
+ "properties": {
+ "clicks": {
+ "type": "number"
+ },
+ "conversions": {
+ "type": ["number", "null"]
+ },
+ "cost": {
+ "type": ["number", "null"]
+ },
+ "cpa": {
+ "type": ["number", "null"]
+ },
+ "cpc": {
+ "type": ["number", "null"]
+ },
+ "ctr": {
+ "type": ["number", "null"]
+ },
+ "currency": {
+ "type": ["string", "null"]
+ },
+ "impressions": {
+ "type": "number"
+ },
+ "keyword": {
+ "type": ["string", "null"]
+ },
+ "matchType": {
+ "type": ["string", "null"]
+ },
+ "page": {
+ "type": ["string", "null"]
+ },
+ "platform": {
+ "enum": ["GoogleAds", "BingAds", "GoogleSearchConsole"],
+ "type": "string"
+ },
+ "position": {
+ "type": ["number", "null"]
+ },
+ "previous": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/MarketingAnalyticsSearchMetrics"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "clicks",
+ "conversions",
+ "cost",
+ "cpa",
+ "cpc",
+ "ctr",
+ "currency",
+ "impressions",
+ "keyword",
+ "matchType",
+ "platform"
+ ],
+ "type": "object"
+ },
+ "MarketingAnalyticsSearchSource": {
+ "additionalProperties": false,
+ "properties": {
+ "keywordTable": {
+ "type": "string"
+ },
+ "queryPageTable": {
+ "type": "boolean"
+ },
+ "sourceType": {
+ "enum": ["GoogleAds", "BingAds", "GoogleSearchConsole"],
+ "type": "string"
+ },
+ "statsTable": {
+ "type": "string"
+ }
+ },
+ "required": ["sourceType", "statsTable"],
+ "type": "object"
+ },
"MarketingAnalyticsTableQuery": {
"additionalProperties": false,
"properties": {
@@ -39082,6 +39424,7 @@
"MarketingAnalyticsAttributionQuery",
"MarketingAnalyticsAttributionPathsQuery",
"MarketingAnalyticsRetentionQuery",
+ "MarketingAnalyticsSearchQuery",
"ExperimentMetric",
"ExperimentQuery",
"ExperimentExposureQuery",
@@ -43976,6 +44319,71 @@
],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MarketingAnalyticsSearchRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
{
"properties": {},
"type": "object"
@@ -49802,6 +50210,9 @@
{
"$ref": "#/definitions/MarketingAnalyticsRetentionQuery"
},
+ {
+ "$ref": "#/definitions/MarketingAnalyticsSearchQuery"
+ },
{
"$ref": "#/definitions/DataVisualizationNode"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index f9380a571aba..1de103128415 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -160,6 +160,7 @@ export enum NodeKind {
MarketingAnalyticsAttributionQuery = 'MarketingAnalyticsAttributionQuery',
MarketingAnalyticsAttributionPathsQuery = 'MarketingAnalyticsAttributionPathsQuery',
MarketingAnalyticsRetentionQuery = 'MarketingAnalyticsRetentionQuery',
+ MarketingAnalyticsSearchQuery = 'MarketingAnalyticsSearchQuery',
// Experiment queries
ExperimentMetric = 'ExperimentMetric',
@@ -245,6 +246,7 @@ export type AnyDataNode =
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -363,6 +365,7 @@ export type QuerySchema =
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
// Interface nodes
| DataVisualizationNode
@@ -8145,6 +8148,50 @@ export interface MarketingAnalyticsRetentionQueryResponse extends AnalyticsQuery
export type CachedMarketingAnalyticsRetentionQueryResponse =
CachedQueryResponse<MarketingAnalyticsRetentionQueryResponse>
+export interface MarketingAnalyticsSearchSource {
+ sourceType: 'GoogleAds' | 'BingAds' | 'GoogleSearchConsole'
+ statsTable: string
+ keywordTable?: string
+ queryPageTable?: boolean
+}
+
+export interface MarketingAnalyticsSearchQuery extends DataNode<MarketingAnalyticsSearchQueryResponse> {
+ kind: NodeKind.MarketingAnalyticsSearchQuery
+ dateRange?: DateRange
+ sources: MarketingAnalyticsSearchSource[]
+ compareFilter?: CompareFilter
+ search?: string
+ breakdown?: 'keyword' | 'page'
+ keyword?: string
+ page?: string
+}
+
+export interface MarketingAnalyticsSearchMetrics {
+ clicks: number
+ impressions: number
+ cost: number | null
+ conversions: number | null
+ ctr: number | null
+ cpc: number | null
+ cpa: number | null
+ position?: number | null
+}
+
+export interface MarketingAnalyticsSearchRow extends MarketingAnalyticsSearchMetrics {
+ keyword: string | null
+ page?: string | null
+ platform: 'GoogleAds' | 'BingAds' | 'GoogleSearchConsole'
+ matchType: string | null
+ currency: string | null
+ previous?: MarketingAnalyticsSearchMetrics | null
+}
+
+export interface MarketingAnalyticsSearchQueryResponse extends AnalyticsQueryResponseBase {
+ results: MarketingAnalyticsSearchRow[]
+}
+
+export type CachedMarketingAnalyticsSearchQueryResponse = CachedQueryResponse<MarketingAnalyticsSearchQueryResponse>
+
export interface WebAnalyticsExternalSummaryRequest {
date_from: string
date_to: string
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index 00a47260471b..8418d6ce359f 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -31,6 +31,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'
import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'
import { marketingAnalyticsEmptyState } from 'products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState'
+import { SearchPerformanceTab } from 'products/marketing_analytics/frontend/search/SearchPerformanceTab'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { LegacyOAuthReconnectBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner'
@@ -282,7 +283,8 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const tabs = [
{ key: MarketingAnalyticsTab.DASHBOARD, label: 'Dashboard', content: dashboard },
- ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] ||
+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
? [
{
key: MarketingAnalyticsTab.AD_PERFORMANCE,
@@ -291,6 +293,11 @@ const MarketingAnalyticsContent = (): JSX.Element => {
<>
<MarketingAnalyticsFilters tabs={<></>} />
<MarketingAnalyticsDashboard />
+ {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS] && (
+ <div className="mt-8">
+ <SearchPerformanceTab />
+ </div>
+ )}
{integrationSettingsModal.integration && (
<IntegrationSettingsModal
integrationName={integrationSettingsModal.integration}
@@ -303,6 +310,10 @@ const MarketingAnalyticsContent = (): JSX.Element => {
</>
),
},
+ ]
+ : []),
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
+ ? [
{
key: MarketingAnalyticsTab.PAGE_VISIBILITY,
label: 'Page visibility',
@@ -360,9 +371,14 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const tabIsRendered = tabs.some((tab) => tab.key === activeTab)
useEffect(() => {
if (!tabIsRendered && !absorbed) {
- setActiveTab(MarketingAnalyticsTab.DASHBOARD)
+ setActiveTab(
+ activeTab === MarketingAnalyticsTab.SEARCH_PERFORMANCE &&
+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
+ ? MarketingAnalyticsTab.AD_PERFORMANCE
+ : MarketingAnalyticsTab.DASHBOARD
+ )
}
- }, [tabIsRendered, absorbed, setActiveTab])
+ }, [tabIsRendered, absorbed, setActiveTab, activeTab, featureFlags])
const selectedTab = tabIsRendered ? activeTab : MarketingAnalyticsTab.DASHBOARD
// Only surface the tab bar once a secondary tab is enabled; otherwise show the dashboard directly.
@@ -376,6 +392,8 @@ const MarketingAnalyticsContent = (): JSX.Element => {
}
const TAB_DESCRIPTIONS: Record<string, string> = {
+ [MarketingAnalyticsTab.SEARCH_PERFORMANCE]:
+ 'Explore paid and organic search performance across keywords, queries and landing pages.',
[MarketingAnalyticsTab.PAGE_VISIBILITY]:
'Explore page traffic, Google search visibility, AI referrals, crawler activity, and conversions.',
[MarketingAnalyticsTab.AD_PERFORMANCE]: 'Compare ad spend, clicks and impressions across your connected platforms.',
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 2d30e12bb122..5138b2ace27b 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -575,6 +575,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.MarketingAnalyticsSearchQuery]: {
+ name: 'Marketing analytics search performance',
+ icon: IconHogQL,
+ inMenu: false,
+ },
[NodeKind.UsageMetricsQuery]: {
name: 'Usage Metrics',
icon: IconPieChart,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
index 22c35e3c736e..9d8b19ab294e 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
@@ -4,6 +4,9 @@ import { useState } from 'react'
import { IconFilter } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonDropdown } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { ExternalDataSchemaStatus } from '~/types'
import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'
@@ -12,12 +15,37 @@ import { MarketingSourceStatus, marketingAnalyticsLogic } from '../../logic/mark
import { StatusIcon } from '../settings/StatusIcon'
export function IntegrationFilter(): JSX.Element {
- const { allAvailableSourcesWithStatus, integrationFilter } = useValues(marketingAnalyticsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { allAvailableSourcesWithStatus, integrationFilter, dataWarehouseSources, isAdPerformance } =
+ useValues(marketingAnalyticsLogic)
const { setIntegrationFilter } = useActions(marketingAnalyticsLogic)
const [showPopover, setShowPopover] = useState(false)
- const selectedIds = integrationFilter.integrationSourceIds || []
- const allSourceIds = allAvailableSourcesWithStatus.map((s) => s.id)
+ const includeOrganic = isAdPerformance && !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
+ const organicSources = includeOrganic
+ ? (dataWarehouseSources?.results ?? [])
+ .filter((source) => source.source_type === 'GoogleSearchConsole')
+ .map((source) => ({
+ id: source.id,
+ name: source.source_type,
+ type: 'native',
+ source_type: source.source_type,
+ prefix: source.description || source.prefix || undefined,
+ status: undefined,
+ statusMessage: undefined,
+ }))
+ : []
+ const availableSources = [...allAvailableSourcesWithStatus, ...organicSources]
+ const groups = includeOrganic
+ ? [
+ { title: 'Ad sources', sources: allAvailableSourcesWithStatus },
+ { title: 'Organic search', sources: organicSources },
+ ]
+ : [{ title: '', sources: availableSources }]
+ const selectedIds = (integrationFilter.integrationSourceIds || []).filter((id) =>
+ availableSources.some((source) => source.id === id)
+ )
+ const allSourceIds = availableSources.map((s) => s.id)
const isAllSelected = selectedIds.length === allSourceIds.length && allSourceIds.length > 0
const isSomeSelected = selectedIds.length > 0 && selectedIds.length < allSourceIds.length
// Absent means included, so only an explicit false hides these rows.
@@ -45,7 +73,7 @@ export function IntegrationFilter(): JSX.Element {
const formatSourceLabel = (source: { name: string; type: string; prefix?: string }): string => {
const prefix = source.prefix ? `${source.prefix} - ` : 'default - '
- return `${prefix}${source.name}`
+ return `${prefix}${source.name.replace(/([a-z])([A-Z])/g, '$1 $2')}`
}
const displayValue = (): string => {
@@ -56,14 +84,14 @@ export function IntegrationFilter(): JSX.Element {
return includeNonIntegrated ? 'All integrations' : 'Integrated only'
}
if (selectedIds.length === 1) {
- const source = allAvailableSourcesWithStatus.find((s) => s.id === selectedIds[0])
+ const source = availableSources.find((s) => s.id === selectedIds[0])
return `${source ? formatSourceLabel(source) : '1 integration'}${suffix}`
}
return `${selectedIds.length} integrations${suffix}`
}
// Don't show the filter if there are no available sources
- if (allAvailableSourcesWithStatus.length === 0) {
+ if (availableSources.length === 0) {
return <></>
}
@@ -85,49 +113,69 @@ export function IntegrationFilter(): JSX.Element {
</span>
</LemonButton>
<div className="border-t border-border my-1" />
- {allAvailableSourcesWithStatus.map((source) => (
- <LemonButton
- key={source.id}
- fullWidth
- size="small"
- onClick={() => handleToggleSource(source.id)}
- className="justify-start"
- >
- <span className="flex items-center gap-2">
- <LemonCheckbox
- checked={selectedIds.includes(source.id)}
- className="pointer-events-none"
- />
- <SourceIcon type={source.name} size="xsmall" disableTooltip />
- <span className="flex-1">{formatSourceLabel(source)}</span>
- {/* We don't show the status icon for Completed sources because it would be too many statuses */}
- {source.status &&
- source.statusMessage &&
- source.status !==
- (ExternalDataSchemaStatus.Completed || MarketingSourceStatus.Success) && (
- <StatusIcon status={source.status} message={source.statusMessage} />
- )}
- </span>
- </LemonButton>
- ))}
- <div className="border-t border-border my-1" />
- <LemonButton
- fullWidth
- size="small"
- onClick={handleToggleNonIntegrated}
- className="justify-start"
- tooltip="Traffic no integration reports cost for, like organic, email, or a source you haven't mapped yet."
- >
- <span className="flex items-center gap-2">
- <LemonCheckbox checked={includeNonIntegrated} className="pointer-events-none" />
- <span className="flex-1">No integration</span>
- </span>
- </LemonButton>
+ {groups
+ .filter((group) => group.sources.length > 0)
+ .map((group) => (
+ <div key={group.title}>
+ {group.title && (
+ <div className="px-2 py-1 text-xs font-semibold text-secondary">{group.title}</div>
+ )}
+ {group.sources.map((source) => (
+ <LemonButton
+ key={source.id}
+ fullWidth
+ size="small"
+ onClick={() => handleToggleSource(source.id)}
+ className="justify-start"
+ >
+ <span className="flex items-center gap-2">
+ <LemonCheckbox
+ checked={selectedIds.includes(source.id)}
+ className="pointer-events-none"
+ />
+ <SourceIcon type={source.name} size="xsmall" disableTooltip />
+ <span className="flex-1">{formatSourceLabel(source)}</span>
+ {/* We don't show the status icon for Completed sources because it would be too many statuses */}
+ {source.status &&
+ source.statusMessage &&
+ source.status !==
+ (ExternalDataSchemaStatus.Completed ||
+ MarketingSourceStatus.Success) && (
+ <StatusIcon status={source.status} message={source.statusMessage} />
+ )}
+ </span>
+ </LemonButton>
+ ))}
+ </div>
+ ))}
+ {!isAdPerformance && (
+ <>
+ <div className="border-t border-border my-1" />
+ <LemonButton
+ fullWidth
+ size="small"
+ onClick={handleToggleNonIntegrated}
+ className="justify-start"
+ tooltip="Traffic no integration reports cost for, like organic, email, or a source you haven't mapped yet."
+ >
+ <span className="flex items-center gap-2">
+ <LemonCheckbox checked={includeNonIntegrated} className="pointer-events-none" />
+ <span className="flex-1">No integration</span>
+ </span>
+ </LemonButton>
+ </>
+ )}
</div>
}
>
- <LemonButton type="secondary" size="small" icon={<IconFilter />} data-attr="integration-filter">
- {displayValue()}
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconFilter />}
+ data-attr="integration-filter"
+ className="max-w-full"
+ >
+ <span className="truncate">{displayValue()}</span>
</LemonButton>
</LemonDropdown>
)
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
index d7d548f0f0bc..c614fe4100e8 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
@@ -11,7 +11,8 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedAr
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
-import { OrganizationMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -27,7 +28,10 @@ import { ConversionGoalModal } from './ConversionGoalModal'
import { IntegrationFilter } from './IntegrationFilter'
export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Element => {
- const { compareFilter, dateFilter, shouldFilterTestAccounts, optionsOpen } = useValues(marketingAnalyticsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { compareFilter, dateFilter, shouldFilterTestAccounts, optionsOpen, isAdPerformance } =
+ useValues(marketingAnalyticsLogic)
+ const showSearch = isAdPerformance && !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
const { currentTeamLoading } = useValues(teamLogic)
const { setCompareFilter, setDates, updateFilterTestAccounts, setOptionsOpen } = useActions(marketingAnalyticsLogic)
// The setting lives on the project, so flipping it changes what everyone sees.
@@ -40,9 +44,9 @@ export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.
<BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }}>
<FilterBar
top={tabs}
- className="[&>div]:flex-wrap"
+ className="[&>div]:flex-wrap [&>div>div]:max-w-full [&>div>div>div]:min-w-0 [&>div>div>div>div]:max-w-full"
left={
- <div className="flex flex-wrap items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2 min-w-0 max-w-full">
<DateFilter
allowTimePrecision
dateFrom={dateFilter.dateFrom}
@@ -59,6 +63,7 @@ export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.
<ReloadAll />
</Shortcut>
<ConversionGoalFilterButton />
+ {showSearch && <IntegrationFilter />}
</div>
}
right={
@@ -89,12 +94,14 @@ export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.
updateCompareFilter={setCompareFilter}
/>
</div>
- <div>
- <div className="text-muted mb-2 text-xs font-semibold uppercase">
- Integrations
+ {!showSearch && (
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">
+ Integrations
+ </div>
+ <IntegrationFilter />
</div>
- <IntegrationFilter />
- </div>
+ )}
<LemonDivider className="my-0" />
{/* Only the event side honors this: ad spend comes from the platforms. */}
<TestAccountFilterSwitch
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index dcd29564cbd2..43b07bdf5087 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -21,6 +21,7 @@ import {
MarketingAnalyticsAggregatedQuery,
MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsTableQuery,
+ MarketingAnalyticsSearchRow,
MarketingAnalyticsOrderBy,
MarketingAnalyticsBaseColumns,
MarketingAnalyticsColumnsSchemaNames,
@@ -29,7 +30,17 @@ import {
WebAnalyticsPropertyFilters,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { ExternalDataSchemaStatus, ExternalDataSource, PropertyFilterType, PropertyOperator } from '~/types'
+import {
+ AccessControlLevel,
+ ExternalDataJobStatus,
+ ExternalDataSchemaStatus,
+ ExternalDataSource,
+ ExternalDataSourceSchema,
+ PropertyFilterType,
+ PropertyOperator,
+} from '~/types'
+
+import { searchPerformanceLogic } from 'products/marketing_analytics/frontend/search/searchPerformanceLogic'
import {
MarketingAnalyticsTab,
@@ -63,6 +74,126 @@ describe('marketingAnalyticsLogic', () => {
localStorage.clear()
})
+ it('keeps the search date range in the URL when restoring a tab', async () => {
+ router.actions.push(urls.marketingAnalyticsApp(), {
+ tab: MarketingAnalyticsTab.SEARCH_PERFORMANCE,
+ date_from: '-28d',
+ compare: 'true',
+ })
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.dateFilter.dateFrom).toBe('-28d')
+ expect(router.values.searchParams).toMatchObject({
+ date_from: '-28d',
+ tab: MarketingAnalyticsTab.SEARCH_PERFORMANCE,
+ })
+ })
+
+ it('keeps a connected Search Console integration selected after refreshing sources', async () => {
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setIntegrationFilter({
+ integrationSourceIds: ['organic', 'deleted'],
+ includeNonIntegrated: false,
+ })
+ await expectLogic(logic, () =>
+ logic.actions.loadSourcesSuccess({
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'organic',
+ source_id: 'example.com',
+ connection_id: 'example-organic',
+ source_type: 'GoogleSearchConsole',
+ schemas: [
+ {
+ name: 'search_analytics_by_query_page',
+ should_sync: true,
+ table: { name: 'organic_query_pages', hogql_name: 'organic_query_pages' },
+ } as ExternalDataSourceSchema,
+ ],
+ status: ExternalDataJobStatus.Completed,
+ prefix: null,
+ description: 'example.com',
+ created_via: 'web',
+ latest_error: null,
+ sync_frequency: '24hour',
+ job_inputs: {},
+ user_access_level: AccessControlLevel.Admin,
+ revenue_analytics_config: { enabled: false, include_invoiceless_charges: false },
+ },
+ ],
+ })
+ ).toFinishAllListeners()
+ expect(logic.values.integrationFilter.integrationSourceIds).toEqual(['organic'])
+ const searchLogic = searchPerformanceLogic()
+ const unmountSearch = searchLogic.mount()
+ try {
+ expect(searchLogic.values.missingSources).toEqual(['GoogleAds'])
+ logic.actions.setCompareFilter({ compare: true })
+ logic.actions.setDates('-28d', null)
+ searchLogic.actions.setChannel('paid')
+ searchLogic.actions.setQuerySearch('missing query')
+ expect(searchLogic.values.hasActiveFilters).toBe(true)
+ expect(searchLogic.values.sources).toEqual([])
+
+ searchLogic.actions.clearFilters()
+ expect(searchLogic.values.hasActiveFilters).toBe(false)
+ expect(searchLogic.values.sources.map((source) => source.id)).toEqual(['organic'])
+ expect(searchLogic.values.query.search).toBe('')
+ expect(logic.values.compareFilter).toEqual({ compare: true })
+ const organicSource = logic.values.dataWarehouseSources!.results[0]
+ await expectLogic(logic, () =>
+ logic.actions.loadSourcesSuccess({
+ count: 2,
+ next: null,
+ previous: null,
+ results: [
+ organicSource,
+ {
+ ...organicSource,
+ id: 'organic-other',
+ schemas: [
+ {
+ ...organicSource.schemas[0],
+ table: {
+ ...organicSource.schemas[0].table!,
+ name: 'other_query_pages',
+ hogql_name: 'other_query_pages',
+ },
+ },
+ ],
+ },
+ ],
+ })
+ ).toFinishAllListeners()
+ logic.actions.setIntegrationFilter({ integrationSourceIds: ['organic'] })
+ searchLogic.actions.selectRow({
+ platform: 'GoogleSearchConsole',
+ keyword: 'analytics',
+ page: null,
+ } as MarketingAnalyticsSearchRow)
+ expect(searchLogic.values.detailQuery?.sources.map((source) => source.statsTable)).toEqual([
+ 'organic_query_pages',
+ ])
+ searchLogic.actions.selectRow({
+ platform: 'GoogleAds',
+ keyword: 'analytics',
+ page: null,
+ } as MarketingAnalyticsSearchRow)
+ expect(searchLogic.values.detailQuery?.sources.map((source) => source.statsTable)).toEqual([
+ 'organic_query_pages',
+ 'other_query_pages',
+ ])
+ } finally {
+ unmountSearch()
+ }
+ })
+
it.each<{
description: string
overrideFromUrl?: boolean
@@ -546,10 +677,7 @@ describe('marketingAnalyticsLogic', () => {
})
it('keeps the selection and drops an unknown key from a filter saved by an older build', async () => {
- localStorage.setItem(
- STORAGE_KEY,
- JSON.stringify({ integrationSourceIds: ['source-1'], includeNonIntegrated: true })
- )
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ integrationSourceIds: ['source-1'], removedOption: true }))
logic = marketingAnalyticsLogic()
logic.mount()
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index b9e2e93b5ed1..8a65b7784720 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -90,6 +90,7 @@ export type NativeSourceHierarchyStatus = {
export enum MarketingAnalyticsTab {
DASHBOARD = 'dashboard',
AD_PERFORMANCE = 'ad-performance',
+ SEARCH_PERFORMANCE = 'search-performance',
PAGE_VISIBILITY = 'page-visibility',
ATTRIBUTION = 'attribution',
RETENTION = 'retention',
@@ -587,9 +588,7 @@ export interface marketingAnalyticsLogicActions {
setInitialized: () => {
value: true
}
- setIntegrationFilter: (integrationFilter: IntegrationFilter) => {
- integrationFilter: IntegrationFilter
- }
+ setIntegrationFilter: (integrationFilter: IntegrationFilter) => { integrationFilter: IntegrationFilter }
setOptionsOpen: (optionsOpen: boolean) => {
optionsOpen: boolean
}
@@ -1110,7 +1109,8 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
(s) => [s.activeTab, s.featureFlags],
(activeTab: MarketingAnalyticsTab, featureFlags: FeatureFlagsSet): boolean =>
activeTab === MarketingAnalyticsTab.AD_PERFORMANCE &&
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
+ (!!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] ||
+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]),
],
includeConversionGoals: [
(s) => [s.isAdPerformance, s.adPerformanceConversionGoals, s.conversion_goals],
@@ -1761,13 +1761,18 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
// Clean up integrationFilter if it contains IDs of sources that no longer exist
const currentFilter = values.integrationFilter
if (currentFilter.integrationSourceIds && currentFilter.integrationSourceIds.length > 0) {
- const availableSourceIds = values.allAvailableSources.map((s) => s.id)
+ const availableSourceIds = [
+ ...values.allAvailableSources.map((s) => s.id),
+ ...(values.dataWarehouseSources?.results ?? [])
+ .filter((source) => source.source_type === 'GoogleSearchConsole')
+ .map((source) => source.id),
+ ]
const validFilterIds = currentFilter.integrationSourceIds.filter((id) =>
availableSourceIds.includes(id)
)
if (validFilterIds.length !== currentFilter.integrationSourceIds.length) {
- actions.setIntegrationFilter({ integrationSourceIds: validFilterIds })
+ actions.setIntegrationFilter({ ...currentFilter, integrationSourceIds: validFilterIds })
}
}
@@ -1791,9 +1796,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
const params: Parameters<typeof actions.syncFromUrl>[0] = {}
const rawTab = searchParams.get('tab')
- if (rawTab && Object.values(MarketingAnalyticsTab).includes(rawTab as MarketingAnalyticsTab)) {
- actions.setActiveTab(rawTab as MarketingAnalyticsTab)
- }
const section = searchParams.get('section') as SetupSection | null
if (section && Object.values(SetupSection).includes(section)) {
@@ -1848,6 +1850,10 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
actions.syncFromUrl(params)
}
+ if (rawTab && Object.values(MarketingAnalyticsTab).includes(rawTab as MarketingAnalyticsTab)) {
+ actions.setActiveTab(rawTab as MarketingAnalyticsTab)
+ }
+
actions.loadSources()
actions.loadDatabase()
}),
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
index a0f1dd5539a0..cf2e8b178f55 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
@@ -647,10 +647,15 @@ describe('marketing analytics utils', () => {
describe('sanitizeIntegrationFilter', () => {
it('drops a key the query schema no longer accepts', () => {
- const stored = { integrationSourceIds: ['abc'], includeNonIntegrated: true }
+ const stored = { integrationSourceIds: ['abc'], removedOption: true }
expect(sanitizeIntegrationFilter(stored)).toEqual({ integrationSourceIds: ['abc'] })
})
+ it.each([true, false])('preserves the non-integrated traffic preference: %s', (includeNonIntegrated) => {
+ const stored = { integrationSourceIds: ['abc'], includeNonIntegrated }
+ expect(sanitizeIntegrationFilter(stored)).toEqual(stored)
+ })
+
it.each([
['selected ids survive', { integrationSourceIds: ['a', 'b'] }, ['a', 'b']],
['empty selection', { integrationSourceIds: [] }, []],
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
index 5cb66f5d9070..86368b532540 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
@@ -1007,9 +1007,13 @@ export function rowMatchesSearch(record: unknown, searchTerm: string): boolean {
})
}
-/** The stored filter is whatever an older build of this page wrote, so keep only the field we still read.
+/** The stored filter is whatever an older build of this page wrote, so keep only the fields we still read.
* A key the query schema no longer accepts makes the backend reject every request the dashboard sends. */
export function sanitizeIntegrationFilter(stored: unknown): IntegrationFilter {
const ids = (stored as IntegrationFilter | null | undefined)?.integrationSourceIds
- return { integrationSourceIds: Array.isArray(ids) ? ids.filter((id) => typeof id === 'string') : [] }
+ const includeNonIntegrated = (stored as IntegrationFilter | null | undefined)?.includeNonIntegrated
+ return {
+ integrationSourceIds: Array.isArray(ids) ? ids.filter((id) => typeof id === 'string') : [],
+ ...(typeof includeNonIntegrated === 'boolean' ? { includeNonIntegrated } : {}),
+ }
}
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 3dfd3bf76f70..c29ca0353f11 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -284,6 +284,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_QUERY
| NodeKind.MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY
| NodeKind.MARKETING_ANALYTICS_RETENTION_QUERY
+ | NodeKind.MARKETING_ANALYTICS_SEARCH_QUERY
):
return {"product": Product.MARKETING_ANALYTICS}
case (
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index fa2900ab3979..2adcaecf006c 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -13,6 +13,7 @@ from posthog.schema import (
FunnelsDataWarehouseNode,
HogQLQuery,
LifecycleDataWarehouseNode,
+ MarketingAnalyticsSearchQuery,
RetentionEntity,
)
@@ -290,8 +291,7 @@ def queried_access_controlled_resources(
return _with_fallback_parents(scopes, bypassed_scopes)
- # Structured insight queries (Trends/Funnels/Lifecycle/...) read warehouse data via a
- # DataWarehouseNode in their tree rather than by table name.
+ # Structured queries can reference warehouse tables without a HogQLQuery in their tree.
return (
_with_fallback_parents({"warehouse_table", "warehouse_view"}, bypassed_scopes)
if _references_data_warehouse(query)
@@ -312,10 +312,11 @@ def _with_fallback_parents(scopes: set[str], bypassed_scopes: frozenset[str]) ->
def _references_data_warehouse(value) -> bool:
- """True if a structured query reads a data-warehouse source via a DataWarehouseNode — or a
- data-warehouse RetentionEntity — anywhere in its tree (series, sub-queries, exclusions, ...)"""
+ """True if a structured query reads warehouse data anywhere in its tree."""
if isinstance(value, (DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode)):
return True
+ if isinstance(value, MarketingAnalyticsSearchQuery):
+ return bool(value.sources)
if isinstance(value, RetentionEntity) and value.type == EntityType.DATA_WAREHOUSE:
return True
if isinstance(value, BaseModel):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index fbbafef04bf0..a4d5a9847de1 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -68,6 +68,7 @@ from posthog.schema import (
InsightActorsQueryOptions,
LifecycleQuery,
MarketingAnalyticsAggregatedQuery,
+ MarketingAnalyticsSearchQuery,
MarketingAnalyticsTableQuery,
MCPHarnessBreakdownQuery,
MCPMissingCapabilitiesQuery,
@@ -578,6 +579,7 @@ RunnableQueryNode = Union[
WebNotableChangesQuery,
SessionAttributionExplorerQuery,
MarketingAnalyticsTableQuery,
+ MarketingAnalyticsSearchQuery,
MarketingAnalyticsAggregatedQuery,
ActorsPropertyTaxonomyQuery,
UsageMetricsQuery,
@@ -1586,6 +1588,15 @@ def get_query_runner(
user=user,
)
+ if kind == NodeKind.MARKETING_ANALYTICS_SEARCH_QUERY:
+ from products.marketing_analytics.backend.hogql_queries.marketing_search_query_runner import (
+ MarketingAnalyticsSearchQueryRunner,
+ )
+
+ return MarketingAnalyticsSearchQueryRunner(
+ query=query, team=team, timings=timings, modifiers=modifiers, limit_context=limit_context, user=user
+ )
+
if kind == NodeKind.MARKETING_ANALYTICS_RETENTION_QUERY:
from products.marketing_analytics.backend.hogql_queries.marketing_retention_query_runner import (
MarketingAnalyticsRetentionQueryRunner,
diff --git a/posthog/schema.py b/posthog/schema.py
index cd755be373eb..c5449e34f920 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -61,6 +61,7 @@ from posthog.schema_enums import (
BillingUsageResponseBreakdownType as BillingUsageResponseBreakdownType,
BingAdsDefaultSources as BingAdsDefaultSources,
BounceRatePageViewMode as BounceRatePageViewMode,
+ Breakdown1 as Breakdown1,
BreakdownAttributionType as BreakdownAttributionType,
BreakdownType as BreakdownType,
CalendarHeatmapMathType as CalendarHeatmapMathType,
@@ -225,6 +226,7 @@ from posthog.schema_enums import (
PersonsOnEventsMode as PersonsOnEventsMode,
PinterestAdsDefaultSources as PinterestAdsDefaultSources,
PlanningStepStatus as PlanningStepStatus,
+ Platform as Platform,
Position as Position,
PrecomputationMode as PrecomputationMode,
PredicateFixAction as PredicateFixAction,
@@ -267,6 +269,7 @@ from posthog.schema_enums import (
SnapchatAdsConversionValueFields as SnapchatAdsConversionValueFields,
SnapchatAdsDefaultSources as SnapchatAdsDefaultSources,
SnapshotSource as SnapshotSource,
+ SourceType as SourceType,
SpanPropertyFilterType as SpanPropertyFilterType,
StartHandling as StartHandling,
Status as Status,
@@ -1985,6 +1988,50 @@ class MarketingAnalyticsDrillDownConfig(BaseModel):
excludesConversionGoals: bool | None = None
+class MarketingAnalyticsSearchMetrics(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ clicks: float
+ conversions: float | None = None
+ cost: float | None = None
+ cpa: float | None = None
+ cpc: float | None = None
+ ctr: float | None = None
+ impressions: float
+ position: float | None = None
+
+
+class MarketingAnalyticsSearchRow(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ clicks: float
+ conversions: float | None = None
+ cost: float | None = None
+ cpa: float | None = None
+ cpc: float | None = None
+ ctr: float | None = None
+ currency: str | None = None
+ impressions: float
+ keyword: str | None = None
+ matchType: str | None = None
+ page: str | None = None
+ platform: Platform
+ position: float | None = None
+ previous: MarketingAnalyticsSearchMetrics | None = None
+
+
+class MarketingAnalyticsSearchSource(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ keywordTable: str | None = None
+ queryPageTable: bool | None = None
+ sourceType: SourceType
+ statsTable: str
+
+
class MarketingIntegrationConfig1(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -2774,7 +2821,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative80(BaseModel):
+class QueryResponseAlternative81(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -6961,7 +7008,7 @@ class QueryResponseAlternative31(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -13928,6 +13975,68 @@ class CachedMarketingAnalyticsRetentionQueryResponse(BaseModel):
)
+class CachedMarketingAnalyticsSearchQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ query_metadata: dict[str, Any] | None = None
+ query_scan: QueryScanSummary | None = Field(
+ default=None,
+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),
+ )
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsSearchRow]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedMarketingAnalyticsTableQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -19802,6 +19911,53 @@ class MarketingAnalyticsRetentionQueryResponse(BaseModel):
)
+class MarketingAnalyticsSearchQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsSearchRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class MarketingAnalyticsTableQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21662,6 +21818,53 @@ class QueryResponseAlternative37(BaseModel):
class QueryResponseAlternative38(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MarketingAnalyticsSearchRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative39(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21714,7 +21917,7 @@ class QueryResponseAlternative38(BaseModel):
)
-class QueryResponseAlternative39(BaseModel):
+class QueryResponseAlternative40(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21767,7 +21970,7 @@ class QueryResponseAlternative39(BaseModel):
)
-class QueryResponseAlternative40(BaseModel):
+class QueryResponseAlternative41(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21820,7 +22023,7 @@ class QueryResponseAlternative40(BaseModel):
)
-class QueryResponseAlternative42(BaseModel):
+class QueryResponseAlternative43(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21878,7 +22081,7 @@ class QueryResponseAlternative42(BaseModel):
)
-class QueryResponseAlternative43(BaseModel):
+class QueryResponseAlternative44(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21946,7 +22149,7 @@ class QueryResponseAlternative43(BaseModel):
)
-class QueryResponseAlternative44(BaseModel):
+class QueryResponseAlternative45(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21999,7 +22202,7 @@ class QueryResponseAlternative44(BaseModel):
)
-class QueryResponseAlternative45(BaseModel):
+class QueryResponseAlternative46(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22051,7 +22254,7 @@ class QueryResponseAlternative45(BaseModel):
)
-class QueryResponseAlternative46(BaseModel):
+class QueryResponseAlternative47(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22112,7 +22315,7 @@ class QueryResponseAlternative46(BaseModel):
)
-class QueryResponseAlternative47(BaseModel):
+class QueryResponseAlternative48(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22167,7 +22370,7 @@ class QueryResponseAlternative47(BaseModel):
)
-class QueryResponseAlternative48(BaseModel):
+class QueryResponseAlternative49(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22219,7 +22422,7 @@ class QueryResponseAlternative48(BaseModel):
)
-class QueryResponseAlternative49(BaseModel):
+class QueryResponseAlternative50(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22271,7 +22474,7 @@ class QueryResponseAlternative49(BaseModel):
)
-class QueryResponseAlternative50(BaseModel):
+class QueryResponseAlternative51(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22336,7 +22539,7 @@ class QueryResponseAlternative50(BaseModel):
)
-class QueryResponseAlternative51(BaseModel):
+class QueryResponseAlternative52(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22396,7 +22599,7 @@ class QueryResponseAlternative51(BaseModel):
)
-class QueryResponseAlternative52(BaseModel):
+class QueryResponseAlternative53(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22447,7 +22650,7 @@ class QueryResponseAlternative52(BaseModel):
)
-class QueryResponseAlternative56(BaseModel):
+class QueryResponseAlternative57(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22498,7 +22701,7 @@ class QueryResponseAlternative56(BaseModel):
)
-class QueryResponseAlternative58(BaseModel):
+class QueryResponseAlternative59(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22550,7 +22753,7 @@ class QueryResponseAlternative58(BaseModel):
)
-class QueryResponseAlternative59(BaseModel):
+class QueryResponseAlternative60(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22607,7 +22810,7 @@ class QueryResponseAlternative59(BaseModel):
)
-class QueryResponseAlternative60(BaseModel):
+class QueryResponseAlternative61(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22662,7 +22865,7 @@ class QueryResponseAlternative60(BaseModel):
)
-class QueryResponseAlternative61(BaseModel):
+class QueryResponseAlternative62(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22711,7 +22914,7 @@ class QueryResponseAlternative61(BaseModel):
)
-class QueryResponseAlternative62(BaseModel):
+class QueryResponseAlternative63(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22765,7 +22968,7 @@ class QueryResponseAlternative62(BaseModel):
)
-class QueryResponseAlternative63(BaseModel):
+class QueryResponseAlternative64(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22812,7 +23015,7 @@ class QueryResponseAlternative63(BaseModel):
)
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22859,7 +23062,7 @@ class QueryResponseAlternative64(BaseModel):
)
-class QueryResponseAlternative65(BaseModel):
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22906,7 +23109,7 @@ class QueryResponseAlternative65(BaseModel):
)
-class QueryResponseAlternative66(BaseModel):
+class QueryResponseAlternative67(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22953,7 +23156,7 @@ class QueryResponseAlternative66(BaseModel):
)
-class QueryResponseAlternative68(BaseModel):
+class QueryResponseAlternative69(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23005,7 +23208,7 @@ class QueryResponseAlternative68(BaseModel):
)
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23057,7 +23260,7 @@ class QueryResponseAlternative70(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23109,7 +23312,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23157,7 +23360,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23204,7 +23407,7 @@ class QueryResponseAlternative73(BaseModel):
)
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23251,7 +23454,7 @@ class QueryResponseAlternative74(BaseModel):
)
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23304,7 +23507,7 @@ class QueryResponseAlternative75(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23355,7 +23558,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23406,7 +23609,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative78(BaseModel):
+class QueryResponseAlternative79(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23457,7 +23660,7 @@ class QueryResponseAlternative78(BaseModel):
)
-class QueryResponseAlternative79(BaseModel):
+class QueryResponseAlternative80(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23508,7 +23711,7 @@ class QueryResponseAlternative79(BaseModel):
)
-class QueryResponseAlternative81(BaseModel):
+class QueryResponseAlternative82(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23558,7 +23761,7 @@ class QueryResponseAlternative81(BaseModel):
)
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23608,7 +23811,7 @@ class QueryResponseAlternative82(BaseModel):
)
-class QueryResponseAlternative83(BaseModel):
+class QueryResponseAlternative84(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23655,7 +23858,7 @@ class QueryResponseAlternative83(BaseModel):
)
-class QueryResponseAlternative84(BaseModel):
+class QueryResponseAlternative85(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23706,7 +23909,7 @@ class QueryResponseAlternative84(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23753,7 +23956,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23800,7 +24003,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23857,7 +24060,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23912,7 +24115,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23959,7 +24162,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24011,7 +24214,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24058,7 +24261,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24105,7 +24308,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24152,7 +24355,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24199,7 +24402,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24250,7 +24453,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24297,7 +24500,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24344,7 +24547,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24391,7 +24594,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24438,7 +24641,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24488,7 +24691,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24535,7 +24738,7 @@ class QueryResponseAlternative104(BaseModel):
)
-class QueryResponseAlternative105(BaseModel):
+class QueryResponseAlternative106(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24597,7 +24800,7 @@ class QueryResponseAlternative105(BaseModel):
)
-class QueryResponseAlternative106(BaseModel):
+class QueryResponseAlternative107(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24644,7 +24847,7 @@ class QueryResponseAlternative106(BaseModel):
)
-class QueryResponseAlternative107(BaseModel):
+class QueryResponseAlternative108(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24691,7 +24894,7 @@ class QueryResponseAlternative107(BaseModel):
)
-class QueryResponseAlternative108(BaseModel):
+class QueryResponseAlternative109(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24738,7 +24941,7 @@ class QueryResponseAlternative108(BaseModel):
)
-class QueryResponseAlternative109(BaseModel):
+class QueryResponseAlternative110(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24785,7 +24988,7 @@ class QueryResponseAlternative109(BaseModel):
)
-class QueryResponseAlternative110(BaseModel):
+class QueryResponseAlternative111(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24832,7 +25035,7 @@ class QueryResponseAlternative110(BaseModel):
)
-class QueryResponseAlternative111(BaseModel):
+class QueryResponseAlternative112(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24879,7 +25082,7 @@ class QueryResponseAlternative111(BaseModel):
)
-class QueryResponseAlternative112(BaseModel):
+class QueryResponseAlternative113(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24926,7 +25129,7 @@ class QueryResponseAlternative112(BaseModel):
)
-class QueryResponseAlternative113(BaseModel):
+class QueryResponseAlternative114(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24974,7 +25177,7 @@ class QueryResponseAlternative113(BaseModel):
)
-class QueryResponseAlternative114(BaseModel):
+class QueryResponseAlternative115(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -28436,6 +28639,24 @@ class MarketingAnalyticsRetentionQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class MarketingAnalyticsSearchQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ breakdown: Breakdown1 | None = None
+ compareFilter: CompareFilter | None = None
+ dateRange: DateRange | None = None
+ keyword: str | None = None
+ kind: Literal["MarketingAnalyticsSearchQuery"] = "MarketingAnalyticsSearchQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ page: str | None = None
+ response: MarketingAnalyticsSearchQueryResponse | None = None
+ search: str | None = None
+ sources: list[MarketingAnalyticsSearchSource]
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class MarketingAnalyticsTableQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -28859,7 +29080,7 @@ class QueryResponseAlternative17(BaseModel):
)
-class QueryResponseAlternative41(BaseModel):
+class QueryResponseAlternative42(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -28912,7 +29133,7 @@ class QueryResponseAlternative41(BaseModel):
)
-class QueryResponseAlternative53(BaseModel):
+class QueryResponseAlternative54(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -31090,7 +31311,7 @@ class PathsV2ActorsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -31570,7 +31791,7 @@ class QueryResponseAlternative20(BaseModel):
)
-class QueryResponseAlternative54(BaseModel):
+class QueryResponseAlternative55(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -31590,7 +31811,7 @@ class QueryResponseAlternative54(BaseModel):
)
-class QueryResponseAlternative55(BaseModel):
+class QueryResponseAlternative56(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -31650,8 +31871,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
- | Any
| QueryResponseAlternative38
+ | Any
| QueryResponseAlternative39
| QueryResponseAlternative40
| QueryResponseAlternative41
@@ -31670,7 +31891,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative54
| QueryResponseAlternative55
| QueryResponseAlternative56
- | QueryResponseAlternative58
+ | QueryResponseAlternative57
| QueryResponseAlternative59
| QueryResponseAlternative60
| QueryResponseAlternative61
@@ -31679,7 +31900,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative64
| QueryResponseAlternative65
| QueryResponseAlternative66
- | QueryResponseAlternative68
+ | QueryResponseAlternative67
| QueryResponseAlternative69
| QueryResponseAlternative70
| QueryResponseAlternative71
@@ -31696,7 +31917,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
- | QueryResponseAlternative87
+ | QueryResponseAlternative85
| QueryResponseAlternative88
| QueryResponseAlternative89
| QueryResponseAlternative90
@@ -31724,6 +31945,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative112
| QueryResponseAlternative113
| QueryResponseAlternative114
+ | QueryResponseAlternative115
]
):
root: (
@@ -31764,8 +31986,8 @@ class QueryResponseAlternative(
| QueryResponseAlternative35
| QueryResponseAlternative36
| QueryResponseAlternative37
- | Any
| QueryResponseAlternative38
+ | Any
| QueryResponseAlternative39
| QueryResponseAlternative40
| QueryResponseAlternative41
@@ -31784,7 +32006,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative54
| QueryResponseAlternative55
| QueryResponseAlternative56
- | QueryResponseAlternative58
+ | QueryResponseAlternative57
| QueryResponseAlternative59
| QueryResponseAlternative60
| QueryResponseAlternative61
@@ -31793,7 +32015,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative64
| QueryResponseAlternative65
| QueryResponseAlternative66
- | QueryResponseAlternative68
+ | QueryResponseAlternative67
| QueryResponseAlternative69
| QueryResponseAlternative70
| QueryResponseAlternative71
@@ -31810,7 +32032,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative82
| QueryResponseAlternative83
| QueryResponseAlternative84
- | QueryResponseAlternative87
+ | QueryResponseAlternative85
| QueryResponseAlternative88
| QueryResponseAlternative89
| QueryResponseAlternative90
@@ -31838,6 +32060,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative112
| QueryResponseAlternative113
| QueryResponseAlternative114
+ | QueryResponseAlternative115
)
@@ -32912,6 +33135,7 @@ class HogQLAutocomplete(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -33047,6 +33271,7 @@ class HogQLMetadata(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
@@ -33199,6 +33424,7 @@ class MaxInsightContext(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33343,6 +33569,7 @@ class QueryRequest(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33479,6 +33706,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33585,6 +33813,7 @@ class QuerySchemaRoot(
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33696,6 +33925,7 @@ class QueryUpgradeRequest(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33807,6 +34037,7 @@ class QueryUpgradeResponse(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
@@ -33963,6 +34194,7 @@ class VisualizationArtifactContent(BaseModel):
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
+ | MarketingAnalyticsSearchQuery
| DataVisualizationNode
| DataTableNode
| SavedInsightNode
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index b7c3a7914b3e..c95fbe052920 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1945,6 +1945,23 @@ class MarketingAnalyticsSchemaFieldTypes(StrEnum):
BOOLEAN = "boolean"
+class Breakdown1(StrEnum):
+ KEYWORD = "keyword"
+ PAGE = "page"
+
+
+class Platform(StrEnum):
+ GOOGLE_ADS = "GoogleAds"
+ BING_ADS = "BingAds"
+ GOOGLE_SEARCH_CONSOLE = "GoogleSearchConsole"
+
+
+class SourceType(StrEnum):
+ GOOGLE_ADS = "GoogleAds"
+ BING_ADS = "BingAds"
+ GOOGLE_SEARCH_CONSOLE = "GoogleSearchConsole"
+
+
class MatchField(StrEnum):
CAMPAIGN_NAME = "campaign_name"
CAMPAIGN_ID = "campaign_id"
@@ -2196,6 +2213,7 @@ class NodeKind(StrEnum):
MARKETING_ANALYTICS_ATTRIBUTION_QUERY = "MarketingAnalyticsAttributionQuery"
MARKETING_ANALYTICS_ATTRIBUTION_PATHS_QUERY = "MarketingAnalyticsAttributionPathsQuery"
MARKETING_ANALYTICS_RETENTION_QUERY = "MarketingAnalyticsRetentionQuery"
+ MARKETING_ANALYTICS_SEARCH_QUERY = "MarketingAnalyticsSearchQuery"
EXPERIMENT_METRIC = "ExperimentMetric"
EXPERIMENT_QUERY = "ExperimentQuery"
EXPERIMENT_EXPOSURE_QUERY = "ExperimentExposureQuery"
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 76522e475328..b2a133270805 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -2242,6 +2242,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
// this measures true connect completion — use it for the real onboarding funnel.
posthog.capture('warehouse source connect completed', {
sourceType: values.selectedConnector.name,
+ returnLabel: values.returnConfig?.returnLabel,
accessMethod: values.source.access_method,
hasWebhookSchemas: values.hasWebhookSchemas,
})
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index 4d8d57be0ed8..96320439d084 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -112,6 +112,7 @@ describe('sourceWizardLogic', () => {
{ enabled: true, category: 'Advertising', attributed: true },
{ enabled: false, category: 'Advertising', attributed: false },
{ enabled: true, category: 'Databases', attributed: false },
+ { enabled: true, category: 'Marketing & email', attributed: false },
] as const)(
'attributes success only for eligible sources: $enabled / $category',
async ({ enabled, category, attributed }) => {
@@ -119,7 +120,12 @@ describe('sourceWizardLogic', () => {
[FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: enabled,
})
const source = buildSourceConfig({
- name: category === 'Advertising' ? 'GoogleAds' : 'Postgres',
+ name:
+ category === 'Advertising'
+ ? 'GoogleAds'
+ : category === 'Marketing & email'
+ ? 'GoogleSearchConsole'
+ : 'Postgres',
category,
})
const logic = sourceWizardLogic({
@@ -135,7 +141,20 @@ describe('sourceWizardLogic', () => {
await expectLogic(logic, () => logic.actions.selectConnector(source)).toFinishAllListeners()
captureMarketingCrossSellClick(MOCK_DEFAULT_TEAM.id, WebStatsBreakdown.InitialChannelType, false)
const attribution = getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)!
+ if (category !== 'Databases') {
+ logic.actions.setReturnConfig(
+ '/project/997/marketing?tab=ad-performance',
+ 'Marketing analytics'
+ )
+ }
await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'warehouse source connect completed',
+ expect.objectContaining({
+ sourceType: source.name,
+ returnLabel: category === 'Databases' ? undefined : 'Marketing analytics',
+ })
+ )
const conversions = jest
.mocked(posthog.capture)
.mock.calls.filter(([name]) => name === 'web analytics marketing cross sell source created')
@@ -178,6 +197,10 @@ describe('sourceWizardLogic', () => {
captureMarketingCrossSellClick(MOCK_DEFAULT_TEAM.id, WebStatsBreakdown.InitialUTMCampaign, false)
const attribution = getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)!
await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+ expect(posthog.capture).not.toHaveBeenCalledWith(
+ 'warehouse source connect completed',
+ expect.anything()
+ )
expect(posthog.capture).not.toHaveBeenCalledWith(
'web analytics marketing cross sell source created',
expect.anything()
diff --git a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
index 6d12977b9872..e4bb908424c8 100644
--- a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
@@ -137,10 +137,19 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([
try {
const res = await api.externalDataSources.list(methodOptions)
breakpoint()
-
+ const results = [...res.results]
+ let next = res.next
+ while (next) {
+ // nosemgrep: prefer-codegen-api -- Follows the pagination URL the server returns.
+ const page = await api.get<PaginatedResponse<ExternalDataSource>>(next, methodOptions)
+ breakpoint()
+ results.push(...page.results)
+ next = page.next
+ }
cache.abortController = null
- return res
+ const response: PaginatedResponse<ExternalDataSource> = { ...res, results, next: null }
+ return response
} catch (error: any) {
// Transient failures shouldn't surface as exceptions:
// - 403: the user has no access to the endpoint
diff --git a/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts b/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
index 83df1201fa4b..295196bf82a7 100644
--- a/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
+++ b/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
@@ -17,6 +17,7 @@ jest.mock('lib/api', () => {
__esModule: true,
...actual,
default: {
+ get: jest.fn(),
externalDataSources: {
list: jest.fn(),
update: jest.fn(),
@@ -45,7 +46,7 @@ describe('sourcesDataLogic', () => {
logic.unmount()
})
- it('loads external data sources from centralized api call', async () => {
+ it('loads every page before publishing external data sources', async () => {
const mockResponse: PaginatedResponse<ExternalDataSource> = {
results: [
{
@@ -68,11 +69,12 @@ describe('sourcesDataLogic', () => {
user_access_level: AccessControlLevel.Manager,
},
],
- next: null,
+ next: '/api/environments/997/external_data_sources/?offset=1',
previous: null,
}
-
+ const secondSource = { ...mockResponse.results[0], id: 'test-2', source_type: 'BingAds' as const }
jest.spyOn(api.externalDataSources, 'list').mockResolvedValue(mockResponse)
+ jest.spyOn(api, 'get').mockResolvedValue({ results: [secondSource], next: null, previous: null })
logic.mount()
@@ -81,11 +83,12 @@ describe('sourcesDataLogic', () => {
})
.toDispatchActions(['loadSources', 'loadSourcesSuccess'])
.toMatchValues({
- dataWarehouseSources: mockResponse,
+ dataWarehouseSources: { ...mockResponse, results: [...mockResponse.results, secondSource], next: null },
dataWarehouseSourcesLoading: false,
})
expect(api.externalDataSources.list).toHaveBeenCalledWith({ signal: expect.any(AbortSignal) })
+ expect(api.get).toHaveBeenCalledWith(mockResponse.next, { signal: expect.any(AbortSignal) })
})
it.each([
@@ -93,7 +96,11 @@ describe('sourcesDataLogic', () => {
['network failure (no HTTP status)', new ApiError('TypeError: Failed to fetch', undefined)],
['aborted request', Object.assign(new Error('aborted'), { name: 'AbortError' })],
])('returns an empty paginated result on %s without surfacing loader failure', async (_label, error) => {
- jest.spyOn(api.externalDataSources, 'list').mockRejectedValue(error)
+ jest.spyOn(api.externalDataSources, 'list').mockResolvedValue({
+ ...emptyResponse,
+ next: '/api/environments/997/external_data_sources/?offset=1',
+ })
+ jest.spyOn(api, 'get').mockRejectedValue(error)
logic.mount()
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py
new file mode 100644
index 000000000000..bcc124230507
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py
@@ -0,0 +1,224 @@
+from datetime import datetime
+from functools import cached_property
+
+from posthog.schema import (
+ CachedMarketingAnalyticsSearchQueryResponse,
+ MarketingAnalyticsSearchMetrics,
+ MarketingAnalyticsSearchQuery,
+ MarketingAnalyticsSearchQueryResponse,
+ MarketingAnalyticsSearchRow,
+ MarketingAnalyticsSearchSource,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
+
+
+class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticsSearchQueryResponse]):
+ query: MarketingAnalyticsSearchQuery
+ response: MarketingAnalyticsSearchQueryResponse
+ cached_response: CachedMarketingAnalyticsSearchQueryResponse
+
+ @cached_property
+ def now(self) -> datetime:
+ return datetime.now()
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ return QueryDateRange(date_range=self.query.dateRange, team=self.team, interval=None, now=self.now)
+
+ @cached_property
+ def comparison_date_range(self) -> QueryDateRange | None:
+ if not self.query.compareFilter or not self.query.compareFilter.compare:
+ return None
+ if self.query.compareFilter.compare_to:
+ return QueryCompareToDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=None,
+ now=self.now,
+ compare_to=self.query.compareFilter.compare_to,
+ )
+ return QueryPreviousPeriodDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=None,
+ now=self.now,
+ )
+
+ def _source_query(
+ self, source: MarketingAnalyticsSearchSource, date_range: QueryDateRange, period: int
+ ) -> ast.SelectQuery | ast.SelectSetQuery:
+ placeholders: dict[str, ast.Expr] = {
+ "period": ast.Constant(value=period),
+ "stats": ast.Field(chain=[*source.statsTable.split(".")]),
+ "date_from": ast.Constant(value=date_range.date_from()),
+ "date_to": ast.Constant(value=date_range.date_to()),
+ }
+ if source.sourceType == "GoogleSearchConsole":
+ if (self.query.keyword is not None or self.query.page is not None) and not source.queryPageTable:
+ raise ValueError("Search details require the query and page table")
+ placeholders.update(
+ {
+ "keyword_value": ast.Constant(value=None)
+ if self.query.breakdown == "page"
+ else parse_expr("nullIf(lower(trim(s.query)), '')"),
+ "page_value": ast.Field(chain=["s", "page"])
+ if self.query.breakdown == "page"
+ else ast.Constant(value=None),
+ "keyword_filter": parse_expr(
+ "lower(trim(s.query)) = {keyword}",
+ placeholders={"keyword": ast.Constant(value=self.query.keyword.strip().lower())},
+ )
+ if self.query.keyword is not None
+ else ast.Constant(value=True),
+ "page_filter": parse_expr(
+ "s.page = {page}", placeholders={"page": ast.Constant(value=self.query.page)}
+ )
+ if self.query.page is not None
+ else ast.Constant(value=True),
+ }
+ )
+ return parse_select(
+ """
+ SELECT {period} AS period, {keyword_value} AS keyword, {page_value} AS page,
+ 'GoogleSearchConsole' AS platform, NULL AS matchType, NULL AS currency,
+ sum(toFloat(clicks)) AS click_count, sum(toFloat(impressions)) AS impression_count,
+ 0 AS total_cost, 0 AS conversion_count,
+ sum(toFloat(s.position) * toFloat(s.impressions)) AS position_total
+ FROM {stats} AS s
+ WHERE toDate(date) >= toDate({date_from}) AND toDate(date) <= toDate({date_to})
+ AND {keyword_filter} AND {page_filter}
+ GROUP BY keyword, page
+ """,
+ placeholders=placeholders,
+ )
+ if self.query.breakdown == "page":
+ if source.sourceType != "GoogleAds":
+ raise ValueError("Landing pages are supported by Google Ads and Google Search Console")
+ return parse_select(
+ """
+ SELECT {period} AS period, NULL AS keyword,
+ nullIf(landing_page_view_unexpanded_final_url, '') AS page,
+ 'GoogleAds' AS platform, NULL AS matchType,
+ nullIf(upper(customer_currency_code), '') AS currency,
+ sum(toFloat(metrics_clicks)) AS click_count,
+ sum(toFloat(metrics_impressions)) AS impression_count,
+ sum(toFloat(metrics_cost_micros)) / 1000000 AS total_cost,
+ sum(toFloat(metrics_conversions)) AS conversion_count, 0 AS position_total
+ FROM {stats}
+ WHERE toDate(segments_date) >= toDate({date_from})
+ AND toDate(segments_date) <= toDate({date_to})
+ AND segments_ad_network_type IN ('SEARCH', 'SEARCH_PARTNERS')
+ GROUP BY page, currency
+ """,
+ placeholders=placeholders,
+ )
+ if source.sourceType == "GoogleAds":
+ if not source.keywordTable:
+ raise ValueError("Google Ads requires a synced keyword table")
+ placeholders["keywords"] = ast.Field(chain=[*source.keywordTable.split(".")])
+ return parse_select(
+ """
+ SELECT {period} AS period, nullIf(lower(trim(k.keyword)), '') AS keyword, NULL AS page, 'GoogleAds' AS platform,
+ nullIf(lower(k.match_type), '') AS matchType,
+ nullIf(upper(s.customer_currency_code), '') AS currency,
+ sum(toFloat(s.metrics_clicks)) AS click_count,
+ sum(toFloat(s.metrics_impressions)) AS impression_count,
+ sum(toFloat(s.metrics_cost_micros)) / 1000000 AS total_cost,
+ sum(toFloat(s.metrics_conversions)) AS conversion_count, 0 AS position_total
+ FROM {stats} AS s
+ LEFT JOIN (
+ SELECT customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id,
+ any(ad_group_criterion_keyword_text) AS keyword,
+ any(ad_group_criterion_keyword_match_type) AS match_type
+ FROM {keywords}
+ GROUP BY customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id
+ ) AS k ON s.customer_id = k.customer_id AND s.campaign_id = k.campaign_id
+ AND s.ad_group_id = k.ad_group_id
+ AND s.ad_group_criterion_criterion_id = k.ad_group_criterion_criterion_id
+ WHERE toDate(s.segments_date) >= toDate({date_from})
+ AND toDate(s.segments_date) <= toDate({date_to})
+ AND s.segments_ad_network_type IN ('SEARCH', 'SEARCH_PARTNERS')
+ GROUP BY keyword, matchType, currency
+ """,
+ placeholders=placeholders,
+ )
+ return parse_select(
+ """
+ SELECT {period} AS period, nullIf(lower(trim(keyword)), '') AS keyword, NULL AS page, 'BingAds' AS platform,
+ nullIf(lower(bid_match_type), '') AS matchType, nullIf(upper(currency_code), '') AS currency,
+ sum(toFloat(clicks)) AS click_count, sum(toFloat(impressions)) AS impression_count,
+ sum(toFloat(spend)) AS total_cost, sum(toFloat(conversions)) AS conversion_count, 0 AS position_total
+ FROM {stats}
+ WHERE toDate(time_period) >= toDate({date_from}) AND toDate(time_period) <= toDate({date_to})
+ GROUP BY keyword, matchType, currency
+ """,
+ placeholders=placeholders,
+ )
+
+ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ source_queries = [self._source_query(source, self.query_date_range, 0) for source in self.query.sources]
+ if self.comparison_date_range:
+ source_queries.extend(
+ self._source_query(source, self.comparison_date_range, 1) for source in self.query.sources
+ )
+ sources = ast.SelectSetQuery.create_from_queries(source_queries, "UNION ALL")
+ return parse_select(
+ """
+ SELECT keyword, page, platform, matchType, currency,
+ coalesce(sumIf(click_count, period = 0), 0) AS clicks, coalesce(sumIf(impression_count, period = 0), 0) AS impressions,
+ if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(total_cost, period = 0), 0)) AS cost,
+ if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(conversion_count, period = 0), 0)) AS conversions,
+ sumIf(click_count, period = 0) / nullIf(sumIf(impression_count, period = 0), 0) AS ctr,
+ if(platform = 'GoogleSearchConsole', NULL, sumIf(total_cost, period = 0) / nullIf(sumIf(click_count, period = 0), 0)) AS cpc,
+ sumIf(total_cost, period = 0) / nullIf(sumIf(conversion_count, period = 0), 0) AS cpa,
+ coalesce(sumIf(click_count, period = 1), 0) AS previous_clicks,
+ coalesce(sumIf(impression_count, period = 1), 0) AS previous_impressions,
+ if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(total_cost, period = 1), 0)) AS previous_cost,
+ if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(conversion_count, period = 1), 0)) AS previous_conversions,
+ sumIf(click_count, period = 1) / nullIf(sumIf(impression_count, period = 1), 0) AS previous_ctr,
+ if(platform = 'GoogleSearchConsole', NULL, sumIf(total_cost, period = 1) / nullIf(sumIf(click_count, period = 1), 0)) AS previous_cpc,
+ sumIf(total_cost, period = 1) / nullIf(sumIf(conversion_count, period = 1), 0) AS previous_cpa,
+ if(platform = 'GoogleSearchConsole', sumIf(position_total, period = 0) / nullIf(sumIf(impression_count, period = 0), 0), NULL) AS position,
+ if(platform = 'GoogleSearchConsole', sumIf(position_total, period = 1) / nullIf(sumIf(impression_count, period = 1), 0), NULL) AS previous_position
+ FROM {sources}
+ WHERE positionCaseInsensitive(coalesce(keyword, page, ''), {search}) > 0
+ GROUP BY keyword, page, platform, matchType, currency
+ ORDER BY clicks DESC, impressions DESC, previous_clicks DESC, platform, keyword, page, matchType, currency
+ LIMIT 100
+ """,
+ placeholders={"sources": sources, "search": ast.Constant(value=(self.query.search or "").strip())},
+ )
+
+ def _calculate(self) -> MarketingAnalyticsSearchQueryResponse:
+ if not self.query.sources:
+ return MarketingAnalyticsSearchQueryResponse(results=[])
+ result = execute_hogql_query(
+ query_type="marketing_analytics_search_query",
+ query=self.to_query(),
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
+ rows = []
+ for row in result.results:
+ values = dict(zip(result.columns or [], row))
+ previous = {
+ metric: values.pop(f"previous_{metric}") for metric in MarketingAnalyticsSearchMetrics.model_fields
+ }
+ rows.append(
+ MarketingAnalyticsSearchRow(
+ **values,
+ previous=MarketingAnalyticsSearchMetrics(**previous) if self.comparison_date_range else None,
+ )
+ )
+ return MarketingAnalyticsSearchQueryResponse(results=rows)
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py
new file mode 100644
index 000000000000..f419be22dd56
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py
@@ -0,0 +1,286 @@
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ Breakdown1,
+ CompareFilter,
+ DateRange,
+ MarketingAnalyticsSearchQuery,
+ MarketingAnalyticsSearchSource,
+)
+
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
+
+from .marketing_search_query_runner import MarketingAnalyticsSearchQueryRunner
+
+
+class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
+ def _table(self, name: str, columns: dict[str, str], csv: str) -> str:
+ with TemporaryDirectory() as directory:
+ path = Path(directory) / f"{name}.csv"
+ path.write_text(csv)
+ table, _, _, _, cleanup = create_data_warehouse_table_from_csv(
+ path, name, columns, f"test_storage_bucket-posthog.marketing_analytics.{name}", self.team
+ )
+ self.addCleanup(cleanup)
+ return table.name
+
+ def test_combines_platforms_without_multiplying_metrics_or_mixing_currencies(self) -> None:
+ keywords = self._table(
+ "search_keywords",
+ {
+ "customer_id": "Int64",
+ "campaign_id": "Int64",
+ "ad_group_id": "Int64",
+ "ad_group_criterion_criterion_id": "Int64",
+ "ad_group_criterion_keyword_text": "String",
+ "ad_group_criterion_keyword_match_type": "String",
+ },
+ "customer_id,campaign_id,ad_group_id,ad_group_criterion_criterion_id,ad_group_criterion_keyword_text,ad_group_criterion_keyword_match_type\n"
+ "1,10,100,7,Hedgehog,EXACT\n1,10,100,7,Hedgehog,EXACT\n"
+ "2,20,200,7,Other keyword,PHRASE\n",
+ )
+ google_stats = self._table(
+ "search_google_stats",
+ {
+ "customer_id": "Int64",
+ "campaign_id": "Int64",
+ "ad_group_id": "Int64",
+ "ad_group_criterion_criterion_id": "Int64",
+ "customer_currency_code": "String",
+ "metrics_clicks": "Float64",
+ "metrics_impressions": "Float64",
+ "metrics_cost_micros": "Float64",
+ "metrics_conversions": "Float64",
+ "segments_date": "Date",
+ "segments_ad_network_type": "String",
+ },
+ "customer_id,campaign_id,ad_group_id,ad_group_criterion_criterion_id,customer_currency_code,metrics_clicks,metrics_impressions,metrics_cost_micros,metrics_conversions,segments_date,segments_ad_network_type\n"
+ "1,10,100,7,USD,10,100,20000000,2,2023-01-10,SEARCH\n"
+ "1,10,100,7,USD,30,900,40000000,0.5,2023-01-11,SEARCH_PARTNERS\n"
+ "1,10,100,7,EUR,5,100,10000000,1,2023-01-10,SEARCH\n"
+ "1,10,100,7,USD,900,9000,90000000,9,2023-01-10,CONTENT\n"
+ "1,10,100,7,USD,20,200,30000000,1.25,2022-12-15,SEARCH\n"
+ "1,10,100,7,USD,8,80,16000000,2,2022-01-10,SEARCH\n"
+ "2,20,200,7,USD,3,100,6000000,1,2023-01-10,SEARCH\n",
+ )
+ bing_stats = self._table(
+ "search_bing_stats",
+ {
+ "keyword": "String",
+ "bid_match_type": "String",
+ "currency_code": "String",
+ "clicks": "Float64",
+ "impressions": "Float64",
+ "spend": "Float64",
+ "conversions": "Float64",
+ "time_period": "Date",
+ },
+ "keyword,bid_match_type,currency_code,clicks,impressions,spend,conversions,time_period\n"
+ "Hedgehog,Exact,USD,4,80,8,1,2023-01-10\n"
+ "Hedgehog,Phrase,USD,1,20,2,0,2023-01-10\n"
+ "Zero,Exact,USD,0,0,0,0,2023-01-10\n"
+ "Previous only,Exact,USD,5,100,10,0.5,2022-12-15\n",
+ )
+ query = MarketingAnalyticsSearchQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ sources=[
+ MarketingAnalyticsSearchSource(sourceType="GoogleAds", statsTable=google_stats, keywordTable=keywords),
+ MarketingAnalyticsSearchSource(sourceType="BingAds", statsTable=bing_stats),
+ ],
+ )
+ rows = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert len(rows) == 6
+ google = next(
+ row for row in rows if row.platform == "GoogleAds" and row.currency == "USD" and row.keyword == "hedgehog"
+ )
+ assert google.model_dump() == {
+ "keyword": "hedgehog",
+ "page": None,
+ "position": None,
+ "platform": "GoogleAds",
+ "matchType": "exact",
+ "currency": "USD",
+ "clicks": 40,
+ "impressions": 1000,
+ "cost": 60,
+ "conversions": 2.5,
+ "ctr": 0.04,
+ "cpc": 1.5,
+ "cpa": 24,
+ "previous": None,
+ }
+ zero = next(row for row in rows if row.keyword == "zero")
+ assert zero.ctr is None and zero.cpc is None and zero.cpa is None
+ assert next(row for row in rows if row.keyword == "other keyword").clicks == 3
+ query.search = "HEDGE"
+ filtered = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert len(filtered) == 4
+ assert all(row.keyword == "hedgehog" for row in filtered)
+
+ query.search = None
+ query.compareFilter = CompareFilter(compare=True)
+ compared = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert len(compared) == 7
+ google_compared = next(
+ row
+ for row in compared
+ if row.platform == "GoogleAds" and row.currency == "USD" and row.keyword == "hedgehog"
+ )
+ assert google_compared.clicks == 40
+ assert google_compared.previous is not None
+ assert google_compared.previous.model_dump() == {
+ "clicks": 20,
+ "impressions": 200,
+ "cost": 30,
+ "conversions": 1.25,
+ "ctr": 0.1,
+ "cpc": 1.5,
+ "cpa": 24,
+ "position": None,
+ }
+ previous_only = next(row for row in compared if row.keyword == "previous only")
+ assert previous_only.clicks == 0
+ assert previous_only.ctr is None and previous_only.cpc is None and previous_only.cpa is None
+ assert previous_only.previous is not None and previous_only.previous.clicks == 5
+ new_keyword = next(row for row in compared if row.keyword == "other keyword")
+ assert new_keyword.previous is not None and new_keyword.previous.clicks == 0
+ assert new_keyword.previous.ctr is None
+
+ query.compareFilter = CompareFilter(compare=True, compare_to="-1y")
+ year_compared = (
+ MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ )
+ previous_year = next(
+ row
+ for row in year_compared
+ if row.platform == "GoogleAds" and row.currency == "USD" and row.keyword == "hedgehog"
+ )
+ assert previous_year.clicks == 40
+ assert previous_year.previous is not None and previous_year.previous.clicks == 8
+ assert not any(row.keyword == "previous only" for row in year_compared)
+
+ def test_google_landing_pages_exclude_non_search_traffic_and_keep_currencies(self) -> None:
+ table = self._table(
+ "paid_landing_pages",
+ {
+ "segments_date": "Date",
+ "landing_page_view_unexpanded_final_url": "String",
+ "segments_ad_network_type": "String",
+ "customer_currency_code": "String",
+ "metrics_clicks": "Float64",
+ "metrics_impressions": "Float64",
+ "metrics_cost_micros": "Float64",
+ "metrics_conversions": "Float64",
+ },
+ "segments_date,landing_page_view_unexpanded_final_url,segments_ad_network_type,customer_currency_code,metrics_clicks,metrics_impressions,metrics_cost_micros,metrics_conversions\n"
+ "2023-01-10,https://example.com/a,SEARCH,USD,10,100,20000000,2\n"
+ "2023-01-11,https://example.com/a,SEARCH_PARTNERS,USD,5,50,10000000,0.5\n"
+ "2023-01-10,https://example.com/a,SEARCH,EUR,3,30,6000000,1\n"
+ "2023-01-10,https://example.com/a,CONTENT,USD,900,9000,90000000,90\n",
+ )
+ query = MarketingAnalyticsSearchQuery(
+ breakdown="page",
+ sources=[MarketingAnalyticsSearchSource(sourceType="GoogleAds", statsTable=table)],
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ )
+ rows = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert len(rows) == 2
+ usd = next(row for row in rows if row.currency == "USD")
+ assert usd.page == "https://example.com/a" and usd.keyword is None
+ assert usd.clicks == 15 and usd.impressions == 150
+ assert usd.cost == 30 and usd.conversions == 2.5 and usd.position is None
+
+ def test_organic_positions_are_weighted_and_details_keep_query_page_filters(self) -> None:
+ table = self._table(
+ "organic_query_pages",
+ {
+ "date": "Date",
+ "query": "String",
+ "page": "String",
+ "clicks": "Float64",
+ "impressions": "Float64",
+ "position": "Float64",
+ },
+ "date,query,page,clicks,impressions,position\n"
+ "2023-01-10,Analytics,https://example.com/a,10,100,1\n"
+ "2023-01-10,Analytics,https://example.com/b,90,900,9\n"
+ "2023-01-10,Other,https://example.com/a,5,50,2\n"
+ "2022-12-15,Analytics,https://example.com/a,8,200,4\n",
+ )
+ query = MarketingAnalyticsSearchQuery(
+ sources=[
+ MarketingAnalyticsSearchSource(sourceType="GoogleSearchConsole", statsTable=table, queryPageTable=True)
+ ],
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ compareFilter=CompareFilter(compare=True),
+ )
+ rows = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ analytics = next(row for row in rows if row.keyword == "analytics")
+ assert analytics.clicks == 100 and analytics.impressions == 1000
+ assert analytics.position == 8.2 and analytics.ctr == 0.1
+ assert analytics.cost is None and analytics.conversions is None and analytics.cpc is None
+ assert analytics.previous is not None and analytics.previous.position == 4
+ query.breakdown = Breakdown1.PAGE
+ query.keyword = "ANALYTICS"
+ pages = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert {row.page for row in pages} == {"https://example.com/a", "https://example.com/b"}
+ assert sum(row.clicks for row in pages) == 100
+ query.breakdown = Breakdown1.KEYWORD
+ query.keyword = None
+ query.page = "https://example.com/a"
+ queries = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
+ assert {row.keyword for row in queries} == {"analytics", "other"}
+ assert sum(row.clicks for row in queries) == 15
+ query.page = "https://example.com/a' OR 1=1 --"
+ assert (
+ MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results == []
+ )
+
+
+class TestMarketingSearchCacheAccessControl(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ self.addCleanup(cache.clear)
+
+ @parameterized.expand(
+ [
+ ("warehouse_objects", {"warehouse_table", "warehouse_view"}),
+ ("external_data_source", {"external_data_source"}),
+ ]
+ )
+ def test_marketing_search_partitions_cache_on_warehouse_access_control(
+ self, resource: str, expected_scopes: set[str]
+ ) -> None:
+ query = MarketingAnalyticsSearchQuery(
+ sources=[MarketingAnalyticsSearchSource(sourceType="BingAds", statsTable="example.keyword_stats")]
+ )
+ access_control = AccessControl.objects.create(team=self.team, resource=resource, access_level="none")
+ denied_runner = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user)
+ assert expected_scopes.issubset(denied_runner.get_cache_payload().get("restricted_resources") or [])
+ key_denied = denied_runner.get_cache_key()
+
+ access_control.access_level = "editor"
+ access_control.save()
+ key_granted = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).get_cache_key()
+
+ assert key_denied != key_granted
diff --git a/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx
index 4a97f6dc8f22..6a4f9b6ce04b 100644
--- a/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx
+++ b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx
@@ -5,7 +5,7 @@ import { IconPlusSmall } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonMenuItems, LemonTag } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
-import { TeamMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import {
@@ -51,6 +51,9 @@ export function AddIntegrationButton({ onIntegrationSelect }: AddIntegrationButt
const groups = [
{ title: 'Native integrations', sources: getEnabledNativeMarketingSources(featureFlags) },
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
+ ? [{ title: 'Organic search', sources: ['GoogleSearchConsole'] }]
+ : []),
{ title: 'External sources', sources: VALID_NON_NATIVE_MARKETING_SOURCES },
{ title: 'Self-managed sources', sources: VALID_SELF_MANAGED_MARKETING_SOURCES },
]
@@ -77,7 +80,10 @@ export function AddIntegrationButton({ onIntegrationSelect }: AddIntegrationButt
title,
items: sources.map((integrationId) => ({
key: integrationId,
- label: nativeSourceDisplayLabel(integrationId),
+ label:
+ integrationId === 'GoogleSearchConsole'
+ ? 'Google Search Console'
+ : nativeSourceDisplayLabel(integrationId),
icon: <SourceIcon type={integrationId} size="xsmall" disableTooltip />,
tag:
showNewSourcesInMenu && newSources.some((source) => source === integrationId)
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx
new file mode 100644
index 000000000000..27944a88c887
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx
@@ -0,0 +1,117 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import { ChangeValueCell } from '../dashboard/tables/ChangeValueCell'
+import { SEARCH_PLATFORM_LABELS } from './searchPerformance'
+import { searchPerformanceLogic } from './searchPerformanceLogic'
+import { SearchPerformanceTable } from './SearchPerformanceTable'
+
+export function SearchPerformanceDetail(): JSX.Element {
+ const { selectedRow, detailQuery, compareFilter, hasSearchConsole } = useValues(searchPerformanceLogic)
+ const { selectRow } = useActions(searchPerformanceLogic)
+ const organic = selectedRow?.platform === 'GoogleSearchConsole'
+ const metricKeys: ('clicks' | 'impressions' | 'ctr' | 'position' | 'conversions')[] = [
+ 'clicks',
+ 'impressions',
+ 'ctr',
+ organic ? 'position' : 'conversions',
+ ]
+
+ return (
+ <LemonModal
+ isOpen={!!selectedRow}
+ onClose={() => selectRow(null)}
+ title={<span className="break-all">{selectedRow?.page ?? selectedRow?.keyword ?? 'Search details'}</span>}
+ description={selectedRow ? SEARCH_PLATFORM_LABELS[selectedRow.platform] : undefined}
+ width={900}
+ >
+ {selectedRow && (
+ <div className="@container flex flex-col gap-4">
+ <dl className="grid grid-cols-2 @min-[40rem]:grid-cols-4 gap-4 m-0">
+ {metricKeys.map((metric) => (
+ <div key={metric}>
+ <dt className="text-secondary text-xs mb-1">
+ {
+ {
+ clicks: 'Clicks',
+ impressions: 'Impressions',
+ ctr: 'CTR',
+ position: 'Average position',
+ conversions: 'Conversions',
+ }[metric]
+ }
+ </dt>
+ <dd className="m-0 text-lg font-semibold">
+ <ChangeValueCell
+ value={
+ selectedRow[metric] == null
+ ? null
+ : [selectedRow[metric], selectedRow.previous?.[metric] ?? null]
+ }
+ compare={!!compareFilter?.compare}
+ kind={
+ metric === 'ctr'
+ ? 'percentage'
+ : metric === 'position' || metric === 'conversions'
+ ? 'decimal'
+ : 'number'
+ }
+ currency={CurrencyCode.USD}
+ reverseColors={metric === 'position'}
+ />
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <div>
+ <h3 className="mb-1">
+ {selectedRow.page ? 'Organic queries for this page' : 'Organic pages for this keyword'}
+ </h3>
+ <p className="text-secondary mb-0">
+ {selectedRow.page
+ ? 'See which Google searches bring people to this page.'
+ : 'See the pages that appear in Google for this search.'}
+ {!organic &&
+ !selectedRow.page &&
+ ' Ad keywords can match different searches; these organic results are for the same text.'}
+ </p>
+ </div>
+ {detailQuery?.sources.length ? (
+ <SearchPerformanceTable
+ query={detailQuery}
+ metrics="traffic"
+ queryKey="marketing-search-detail"
+ />
+ ) : (
+ <LemonBanner type="info">
+ {hasSearchConsole
+ ? 'Enable search_analytics_by_query_page in Google Search Console to see this breakdown.'
+ : 'Connect Google Search Console to see organic queries and landing pages.'}
+ </LemonBanner>
+ )}
+ {!hasSearchConsole && (
+ <LemonButton
+ type="primary"
+ to={urls.dataWarehouseSourceNew(
+ 'GoogleSearchConsole',
+ `${urls.marketingAnalyticsApp()}?tab=ad-performance`,
+ 'Marketing analytics'
+ )}
+ >
+ Connect Google Search Console
+ </LemonButton>
+ )}
+ <p className="text-xs text-secondary mb-0">
+ Google can withhold low-volume queries. Query and page breakdowns may not add up to property
+ totals.
+ </p>
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
new file mode 100644
index 000000000000..7f9c537cf051
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
@@ -0,0 +1,480 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { within } from '@testing-library/dom'
+import { BindLogic } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { MarketingAnalyticsScene } from 'scenes/marketing-analytics/MarketingAnalyticsScene'
+import { urls } from 'scenes/urls'
+import { MarketingAnalyticsFilters } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters'
+import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import { Mocks } from '~/mocks/utils'
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { MarketingAnalyticsSearchQuery, MarketingAnalyticsSearchRow } from '~/queries/schema/schema-general'
+
+import IconBingAds from 'public/services/bing-ads.svg'
+import IconGoogleAds from 'public/services/google-ads.png'
+import IconGoogleSearchConsole from 'public/services/google-search-console.svg'
+
+import { expect, userEvent } from 'storybook/test'
+
+import { SearchPerformanceTab } from './SearchPerformanceTab'
+
+const SOURCES = [
+ {
+ id: 'example-google',
+ source_type: 'GoogleAds',
+ description: 'Example Google Ads',
+ prefix: 'example',
+ status: 'Completed',
+ schemas: ['campaign', 'campaign_overview_stats', 'keyword', 'keyword_stats', 'landing_page_stats'].map(
+ (name) => ({
+ id: `example-${name}`,
+ name,
+ should_sync: true,
+ status: 'Completed',
+ table: { name: `example_${name}`, hogql_name: `example.${name}` },
+ })
+ ),
+ },
+ {
+ id: 'example-bing',
+ source_type: 'BingAds',
+ description: 'Example Bing Ads',
+ prefix: 'example',
+ status: 'Completed',
+ schemas: ['campaigns', 'campaign_performance_report', 'keyword_performance_report'].map((name) => ({
+ id: `example-bing-${name}`,
+ name,
+ should_sync: true,
+ status: 'Completed',
+ table: { name: `example_bing_${name}`, hogql_name: `example.bing_${name}` },
+ })),
+ },
+ {
+ id: 'example-organic',
+ source_type: 'GoogleSearchConsole',
+ description: 'example.com',
+ prefix: 'example_organic',
+ status: 'Completed',
+ schemas: ['search_analytics_by_query', 'search_analytics_by_page', 'search_analytics_by_query_page'].map(
+ (name) => ({
+ id: `example-organic-${name}`,
+ name,
+ should_sync: true,
+ status: 'Completed',
+ table: { name: `example_organic_${name}`, hogql_name: `example.organic_${name}` },
+ })
+ ),
+ },
+]
+
+const ROWS: MarketingAnalyticsSearchRow[] = [
+ {
+ keyword: 'product analytics',
+ platform: 'GoogleSearchConsole',
+ matchType: null,
+ currency: null,
+ clicks: 1240,
+ impressions: 18000,
+ ctr: 1240 / 18000,
+ position: 4.2,
+ cost: null,
+ conversions: null,
+ cpc: null,
+ cpa: null,
+ },
+ {
+ keyword: 'product analytics',
+ platform: 'GoogleAds',
+ matchType: 'exact',
+ currency: 'USD',
+ clicks: 840,
+ impressions: 12000,
+ cost: 1260,
+ conversions: 42,
+ ctr: 0.07,
+ cpc: 1.5,
+ cpa: 30,
+ },
+ {
+ keyword: 'website analytics',
+ platform: 'GoogleAds',
+ matchType: 'phrase',
+ currency: 'USD',
+ clicks: 520,
+ impressions: 10400,
+ cost: 1040,
+ conversions: 26,
+ ctr: 0.05,
+ cpc: 2,
+ cpa: 40,
+ },
+ {
+ keyword: 'product analytics',
+ platform: 'BingAds',
+ matchType: 'exact',
+ currency: 'USD',
+ clicks: 240,
+ impressions: 6000,
+ cost: 288,
+ conversions: 12,
+ ctr: 0.04,
+ cpc: 1.2,
+ cpa: 24,
+ },
+ {
+ keyword: 'conversion tracking',
+ platform: 'BingAds',
+ matchType: 'broad',
+ currency: 'EUR',
+ clicks: 80,
+ impressions: 2000,
+ cost: 96,
+ conversions: 4.5,
+ ctr: 0.04,
+ cpc: 1.2,
+ cpa: 96 / 4.5,
+ },
+ {
+ keyword: 'analytics dashboard',
+ platform: 'GoogleAds',
+ matchType: 'exact',
+ currency: 'USD',
+ clicks: 0,
+ impressions: 250,
+ cost: 0,
+ conversions: 0,
+ ctr: 0,
+ cpc: null,
+ cpa: null,
+ },
+]
+
+const MOCKS: Mocks = {
+ get: {
+ '/api/environments/:team_id/external_data_sources/wizard/': {
+ GoogleAds: { name: 'GoogleAds', label: 'Google Ads', iconPath: IconGoogleAds, fields: [] },
+ BingAds: { name: 'BingAds', label: 'Bing Ads', iconPath: IconBingAds, fields: [] },
+ GoogleSearchConsole: {
+ name: 'GoogleSearchConsole',
+ label: 'Google Search Console',
+ iconPath: IconGoogleSearchConsole,
+ fields: [],
+ },
+ },
+ '/api/environments/:team_id/external_data_sources/': {
+ results: SOURCES,
+ count: SOURCES.length,
+ next: null,
+ previous: null,
+ },
+ },
+ post: {
+ '/api/environments/:team_id/query/MarketingAnalyticsSearchQuery/': async ({ request }) => {
+ const { query } = (await request.json()) as { query: MarketingAnalyticsSearchQuery }
+ return [
+ 200,
+ {
+ results: (query.breakdown === 'page'
+ ? ROWS.filter((row) => row.platform !== 'BingAds' && row.clicks > 0).map((row) => ({
+ ...row,
+ page: `https://example.com/${row.keyword?.replaceAll(' ', '-')}`,
+ keyword: null,
+ matchType: null,
+ }))
+ : ROWS
+ )
+ .filter(
+ (row) =>
+ query.sources.some((source) => source.sourceType === row.platform) &&
+ (row.page ?? row.keyword ?? '').includes((query.search ?? '').toLowerCase()) &&
+ (!query.keyword ||
+ row.page === `https://example.com/${query.keyword.replaceAll(' ', '-')}`) &&
+ (!query.page ||
+ `https://example.com/${row.keyword?.replaceAll(' ', '-')}` === query.page)
+ )
+ .map((row) => ({
+ ...row,
+ previous: query.compareFilter?.compare
+ ? {
+ clicks: row.clicks * 0.8,
+ position: row.position == null ? null : row.position + 1.5,
+ impressions: row.impressions * 0.9,
+ cost: row.cost == null ? null : row.cost * 1.1,
+ conversions: row.conversions == null ? null : row.conversions * 0.75,
+ ctr: row.impressions ? (row.clicks * 0.8) / (row.impressions * 0.9) : null,
+ cpc:
+ row.cost != null && row.clicks ? (row.cost * 1.1) / (row.clicks * 0.8) : null,
+ cpa:
+ row.cost != null && row.conversions
+ ? (row.cost * 1.1) / (row.conversions * 0.75)
+ : null,
+ }
+ : null,
+ })),
+ },
+ ]
+ },
+ },
+}
+
+const meta: Meta<typeof SearchPerformanceTab> = {
+ title: 'Scenes-App/Marketing Analytics/Search performance',
+ component: SearchPerformanceTab,
+ beforeEach: () => {
+ localStorage.removeItem('997__.scenes.webAnalytics.marketingAnalyticsLogic.integrationFilter')
+ },
+ render: () => (
+ <>
+ <MarketingAnalyticsFilters tabs={<></>} />
+ <SearchPerformanceTab />
+ </>
+ ),
+ decorators: [
+ mswDecorator({}),
+ (Story) => (
+ <BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }}>
+ <Story />
+ </BindLogic>
+ ),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ msw: { mocks: MOCKS },
+ pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance&date_from=-7d`,
+ featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS],
+ },
+}
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Connected: Story = {
+ parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance&compare=false` },
+}
+export const Comparison: Story = {
+ parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance&compare=true` },
+}
+export const MixedWithPosition: Story = {
+ ...Comparison,
+ play: async ({ canvasElement }) => {
+ await userEvent.click(await within(canvasElement).findByRole('checkbox', { name: 'Show position' }))
+ },
+}
+export const OrganicTraffic: Story = {
+ ...Comparison,
+ parameters: {
+ ...Comparison.parameters,
+ msw: {
+ mocks: {
+ get: {
+ '/api/environments/:team_id/external_data_sources/': {
+ results: SOURCES.filter((source) => source.source_type === 'GoogleSearchConsole'),
+ count: 1,
+ next: null,
+ previous: null,
+ },
+ },
+ },
+ },
+ },
+}
+export const Narrow: Story = {
+ ...Comparison,
+ play: MixedWithPosition.play,
+ parameters: { ...Comparison.parameters, layout: 'padded' },
+ decorators: [
+ (Story) => (
+ <div className="w-[520px]">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export const LandingPages: Story = {
+ play: async ({ canvasElement }) => {
+ await userEvent.click(within(canvasElement).getByText('Landing pages', { exact: true }))
+ },
+}
+export const OrganicDetail: Story = {
+ ...Comparison,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const keywords = await canvas.findAllByRole('button', { name: 'product analytics' })
+ await userEvent.click(keywords[0])
+ },
+}
+export const NotConnected: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/environments/:team_id/external_data_sources/': {
+ results: [],
+ count: 0,
+ next: null,
+ previous: null,
+ },
+ },
+ },
+ },
+ },
+}
+export const AwaitingSync: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/environments/:team_id/external_data_sources/': {
+ results: SOURCES.map((source) => ({
+ ...source,
+ schemas: source.schemas.map((schema) => ({ ...schema, table: null })),
+ })),
+ count: SOURCES.length,
+ next: null,
+ previous: null,
+ },
+ },
+ },
+ },
+ },
+}
+export const OnlyGoogleAds: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/environments/:team_id/external_data_sources/': {
+ results: SOURCES.filter((source) => source.source_type === 'GoogleAds'),
+ count: 1,
+ next: null,
+ previous: null,
+ },
+ },
+ },
+ },
+ },
+}
+export const Empty: Story = {
+ parameters: {
+ msw: {
+ mocks: { post: { '/api/environments/:team_id/query/MarketingAnalyticsSearchQuery/': { results: [] } } },
+ },
+ },
+}
+export const FilteredEmpty: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.type(await canvas.findByPlaceholderText('Filter keywords and queries'), 'no matching keyword')
+ await canvas.findByText('No search data matches your filters. Try clearing them to see more results.')
+ await expect(canvas.getByRole('button', { name: 'Clear filters' })).toBeVisible()
+ },
+}
+export const EmptyGoogleAds: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: OnlyGoogleAds.parameters!.msw.mocks.get,
+ post: Empty.parameters!.msw.mocks.post,
+ },
+ },
+ },
+}
+export const EmptyOrganic: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: OrganicTraffic.parameters!.msw.mocks.get,
+ post: Empty.parameters!.msw.mocks.post,
+ },
+ },
+ },
+}
+const pendingLoadingQueries = new Set<() => void>()
+
+export const Loading: Story = {
+ beforeEach: () => () => {
+ // Release the query slot so the loading fixture cannot block later stories.
+ pendingLoadingQueries.forEach((resolve) => resolve())
+ pendingLoadingQueries.clear()
+ },
+ parameters: {
+ msw: {
+ mocks: {
+ post: {
+ '/api/environments/:team_id/query/MarketingAnalyticsSearchQuery/': async () => {
+ await new Promise<void>((resolve) => pendingLoadingQueries.add(resolve))
+ return { results: [] }
+ },
+ },
+ },
+ },
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export const QueryError: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(await canvas.findByText('00000000-0000-4000-8000-000000000000')).toBeVisible()
+ await expect(canvas.getByRole('button', { name: 'Retry' })).toBeVisible()
+ },
+ parameters: {
+ testOptions: {
+ waitForLoadersToDisappear: false,
+ waitForSelector: '[data-attr="marketing-search-performance"] .LemonBanner--error',
+ },
+ msw: {
+ mocks: {
+ post: {
+ '/api/environments/:team_id/query/MarketingAnalyticsSearchQuery/': [
+ 500,
+ { detail: 'Query failed' },
+ ],
+ },
+ },
+ },
+ },
+}
+export const SourcesError: Story = {
+ parameters: {
+ testOptions: {
+ waitForLoadersToDisappear: false,
+ waitForSelector: '[data-attr="marketing-search-performance"] .LemonBanner--error',
+ },
+ msw: {
+ mocks: {
+ get: { '/api/environments/:team_id/external_data_sources/': [500, { detail: 'Sources unavailable' }] },
+ },
+ },
+ },
+}
+export const LegacyScene: Story = {
+ render: () => <MarketingAnalyticsScene />,
+ parameters: {
+ pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance`,
+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING, FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS],
+ },
+}
+export const NewDashboardScene: Story = {
+ ...LegacyScene,
+ parameters: {
+ ...LegacyScene.parameters,
+ featureFlags: [
+ FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,
+ FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD,
+ FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS,
+ ],
+ },
+}
+export const FlagOff: Story = {
+ ...LegacyScene,
+ parameters: { ...LegacyScene.parameters, featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING] },
+}
+export const NewDashboardFlagOff: Story = {
+ ...LegacyScene,
+ parameters: {
+ ...LegacyScene.parameters,
+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING, FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
+ },
+}
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx
new file mode 100644
index 000000000000..33daafd75a5c
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx
@@ -0,0 +1,173 @@
+import { useActions, useValues } from 'kea'
+
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCheckbox,
+ LemonInput,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonSkeleton,
+} from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { SEARCH_PLATFORM_LABELS, SearchChannel, SearchPlatform, requiredSearchTables } from './searchPerformance'
+import { SearchPerformanceDetail } from './SearchPerformanceDetail'
+import { searchPerformanceLogic } from './searchPerformanceLogic'
+import { SearchPerformanceTable } from './SearchPerformanceTable'
+import { SearchSourceSuggestions } from './SearchSourceSuggestions'
+
+export function SearchPerformanceTab(): JSX.Element {
+ const {
+ dataWarehouseSources,
+ dataWarehouseSourcesLoading,
+ sourcesError,
+ sources,
+ allSearchSources,
+ pendingSources,
+ readySources,
+ displayMetrics,
+ hasPaidSources,
+ showPosition,
+ canShowPosition,
+ search,
+ query,
+ breakdown,
+ channel,
+ hasActiveFilters,
+ hasSelectedBingSource,
+ } = useValues(searchPerformanceLogic)
+ const { loadSources, setMetrics, setSearch, setBreakdown, setChannel, selectRow, setShowPosition, clearFilters } =
+ useActions(searchPerformanceLogic)
+ const loading = !sourcesError && (dataWarehouseSourcesLoading || !dataWarehouseSources)
+
+ return (
+ <div className="@container flex flex-col gap-4 pb-8" data-attr="marketing-search-performance">
+ <div className="flex flex-wrap gap-2 items-center justify-between">
+ <LemonSegmentedButton
+ value={breakdown}
+ onChange={setBreakdown}
+ options={[
+ { value: 'keyword', label: 'Keywords and queries' },
+ { value: 'page', label: 'Landing pages' },
+ ]}
+ />
+ <LemonSelect<SearchChannel>
+ value={channel}
+ onChange={setChannel}
+ options={[
+ { value: 'all', label: 'Paid and organic' },
+ { value: 'paid', label: 'Paid search' },
+ { value: 'organic', label: 'Organic search' },
+ ]}
+ />
+ </div>
+ <div>
+ <h2 className="mb-1">{breakdown === 'page' ? 'Landing page performance' : 'Search performance'}</h2>
+ <p className="text-secondary mb-0">
+ {breakdown === 'page'
+ ? 'See which pages receive paid and organic search traffic. Click a page to explore its organic queries.'
+ : 'Compare ad keywords with organic search queries. Click a keyword or query to explore its landing pages.'}
+ </p>
+ </div>
+ {loading ? (
+ <LemonSkeleton repeat={5} className="h-10" />
+ ) : sourcesError ? (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadSources, loading }}>
+ Could not load your search sources. Try again to view search performance.
+ </LemonBanner>
+ ) : (
+ <>
+ {!hasActiveFilters && <SearchSourceSuggestions />}
+ {breakdown === 'page' && channel !== 'organic' && hasSelectedBingSource && (
+ <LemonBanner type="info">
+ Bing Ads landing page metrics are not available in this view. Its keyword metrics are
+ available under Keywords and queries.
+ </LemonBanner>
+ )}
+ {pendingSources.map((source) => (
+ <LemonBanner
+ key={source.id}
+ type="info"
+ action={{ children: 'Manage source', to: urls.dataWarehouseSource(source.id) }}
+ >
+ {`${source.description || SEARCH_PLATFORM_LABELS[source.source_type as SearchPlatform]}: enable ${requiredSearchTables(source, breakdown)} and wait for the first sync to finish.`}
+ </LemonBanner>
+ ))}
+ {sources.length === 0 && (hasActiveFilters || allSearchSources.length > 0) && (
+ <LemonBanner type="info" action={{ children: 'Clear filters', onClick: clearFilters }}>
+ No search data matches your filters. Clear the filters to see all connected search sources.
+ </LemonBanner>
+ )}
+ {readySources.length > 0 && (
+ <>
+ <div className="flex flex-wrap gap-2 justify-between">
+ <LemonInput
+ type="search"
+ placeholder={breakdown === 'page' ? 'Filter pages' : 'Filter keywords and queries'}
+ value={search}
+ onChange={setSearch}
+ data-attr="marketing-search-keyword-filter"
+ />
+ <div className="flex flex-wrap items-center gap-3">
+ {canShowPosition && (
+ <LemonCheckbox
+ checked={showPosition}
+ onChange={setShowPosition}
+ label="Show position"
+ data-attr="marketing-search-show-position"
+ />
+ )}
+ <LemonSegmentedButton
+ value={displayMetrics}
+ onChange={setMetrics}
+ options={[
+ { value: 'traffic', label: 'Traffic' },
+ {
+ value: 'conversions',
+ label: 'Spend and conversions',
+ disabledReason: !hasPaidSources
+ ? 'Organic search does not report spend or conversions'
+ : undefined,
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SearchPerformanceTable
+ query={query}
+ metrics={displayMetrics}
+ showPosition={showPosition}
+ onSelect={selectRow}
+ emptyState={
+ <div className="flex flex-col items-center gap-2 py-4">
+ <span>
+ {hasActiveFilters
+ ? 'No search data matches your filters. Try clearing them to see more results.'
+ : 'No search data for this period. Try a wider date range or check your source sync status.'}
+ </span>
+ {hasActiveFilters && (
+ <LemonButton type="secondary" size="small" onClick={clearFilters}>
+ Clear filters
+ </LemonButton>
+ )}
+ </div>
+ }
+ />
+ <p className="text-secondary text-xs mb-0">
+ Top 100 results by clicks, grouped by platform, match type and currency.{' '}
+ {breakdown === 'keyword' &&
+ 'Paid rows show targeted keywords; organic rows show actual Google queries. '}
+ Conversions use the ad platform's attribution. Google Search Console does not report
+ spend or conversions, and can omit low-volume queries. Organic positions are weighted by
+ impressions. Hover over a change to see its comparison value.
+ </p>
+ </>
+ )}
+ </>
+ )}
+ <SearchPerformanceDetail />
+ </div>
+ )
+}
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx
new file mode 100644
index 000000000000..67189f746f7d
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx
@@ -0,0 +1,210 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonTable } from '@posthog/lemon-ui'
+
+import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import {
+ CurrencyCode,
+ MarketingAnalyticsSearchMetrics,
+ MarketingAnalyticsSearchQuery,
+ MarketingAnalyticsSearchQueryResponse,
+ MarketingAnalyticsSearchRow,
+} from '~/queries/schema/schema-general'
+
+import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'
+
+import { MarketingQueryError } from '../dashboard/MarketingQueryError'
+import { ChangeValueCell } from '../dashboard/tables/ChangeValueCell'
+import { SEARCH_PLATFORM_LABELS, SearchMetrics } from './searchPerformance'
+
+export function SearchPerformanceTable({
+ query,
+ metrics,
+ showPosition = false,
+ emptyState = 'No results match this date range. Try a wider date range.',
+ onSelect,
+ queryKey = 'marketing-search-performance',
+}: {
+ query: MarketingAnalyticsSearchQuery
+ metrics: SearchMetrics
+ showPosition?: boolean
+ emptyState?: React.ReactNode
+ onSelect?: (row: MarketingAnalyticsSearchRow) => void
+ queryKey?: string
+}): JSX.Element {
+ const logic = dataNodeLogic({
+ query,
+ key: queryKey,
+ dataNodeCollectionId: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID,
+ })
+ const { response, responseLoading, responseError, responseErrorObject, queryId } = useValues(logic)
+ const { loadData } = useActions(logic)
+ const rows = (response as MarketingAnalyticsSearchQueryResponse | undefined)?.results ?? []
+ const hasPaidSources = query.sources.some((source) => source.sourceType !== 'GoogleSearchConsole')
+ const hasOrganicSources = query.sources.some((source) => source.sourceType === 'GoogleSearchConsole')
+ const metricKeys: (keyof MarketingAnalyticsSearchMetrics)[] =
+ metrics === 'traffic'
+ ? [
+ 'clicks',
+ 'impressions',
+ 'ctr',
+ ...(hasPaidSources ? ['cost' as const] : []),
+ ...(hasOrganicSources && (!hasPaidSources || showPosition) ? ['position' as const] : []),
+ ]
+ : ['cost', 'conversions', 'cpc', 'cpa']
+
+ if (responseError && !responseLoading) {
+ return (
+ <MarketingQueryError
+ message="Could not load search performance. Try again or check your source's sync status."
+ queryId={responseErrorObject?.queryId ?? queryId}
+ onRetry={() => loadData('force_async')}
+ loading={responseLoading}
+ />
+ )
+ }
+ return (
+ <LemonTable<MarketingAnalyticsSearchRow>
+ size="small"
+ tableLayout="fixed"
+ className="@max-[40rem]:[&_col:nth-child(2)]:w-10 @max-[40rem]:[&_th]:px-2 @max-[40rem]:[&_td]:px-2 @max-[40rem]:[&_th_svg]:hidden @max-[40rem]:[&_.sorting-indicator]:hidden"
+ dataSource={responseLoading ? [] : rows}
+ loading={responseLoading}
+ loadingSkeletonRows={5}
+ rowKey={(row) => JSON.stringify([row.keyword, row.page, row.platform, row.matchType, row.currency])}
+ pagination={{ pageSize: 10 }}
+ useURLForSorting={false}
+ emptyState={emptyState}
+ columns={[
+ {
+ title: query.breakdown === 'page' ? 'Landing page' : 'Keyword or query',
+ key: 'keyword',
+ width: '24%',
+ render: (_, row) => (
+ <div className="min-w-0">
+ {onSelect && (row.page || row.keyword) ? (
+ <LemonButton type="tertiary" size="xsmall" noPadding onClick={() => onSelect(row)}>
+ <span className="block truncate text-link" title={row.page ?? row.keyword ?? ''}>
+ {row.page ?? row.keyword}
+ </span>
+ </LemonButton>
+ ) : (
+ <span
+ className="block truncate"
+ title={row.page ?? row.keyword ?? 'Keyword unavailable'}
+ >
+ {row.page ?? row.keyword ?? 'Keyword unavailable'}
+ </span>
+ )}
+ <span className="text-xs text-secondary block truncate">
+ {row.platform === 'GoogleSearchConsole'
+ ? 'Organic search'
+ : [row.matchType, row.currency].filter(Boolean).join(' · ')}
+ </span>
+ </div>
+ ),
+ },
+ {
+ title: <span className="@max-[40rem]:sr-only">Platform</span>,
+ key: 'platform',
+ render: (_, row) => (
+ <span className="flex items-center gap-1 min-w-0" title={SEARCH_PLATFORM_LABELS[row.platform]}>
+ <SourceIcon type={row.platform} size="xsmall" disableTooltip />
+ <span className="hidden @min-[40rem]:inline truncate">
+ {SEARCH_PLATFORM_LABELS[row.platform]}
+ </span>
+ </span>
+ ),
+ },
+ ...metricKeys.map((metric) => ({
+ title: (
+ <span className="whitespace-normal wrap-anywhere">
+ <span className="hidden @min-[40rem]:inline">
+ {
+ {
+ clicks: 'Clicks',
+ impressions: 'Impressions',
+ ctr: 'CTR',
+ cost: 'Cost',
+ conversions: 'Conversions',
+ cpc: 'CPC',
+ cpa: 'CPA',
+ position: 'Position',
+ }[metric]
+ }
+ </span>
+ <span className="@min-[40rem]:hidden">
+ {
+ {
+ clicks: 'Clicks',
+ impressions: 'Impr.',
+ ctr: 'CTR',
+ cost: 'Cost',
+ conversions: 'Conv.',
+ cpc: 'CPC',
+ cpa: 'CPA',
+ position: 'Pos.',
+ }[metric]
+ }
+ </span>
+ </span>
+ ),
+ tooltip: {
+ clicks: 'Clicks reported by the search source',
+ impressions: 'Impressions reported by the search source',
+ ctr: 'Clicks divided by impressions',
+ cost: 'Spend in the ad account currency',
+ conversions: 'Conversions attributed by the ad platform',
+ cpc: 'Spend divided by clicks',
+ cpa: 'Spend divided by conversions',
+ position:
+ 'Average position in organic Google search, weighted by impressions. Lower is better.',
+ }[metric],
+ key: metric,
+ align: 'right' as const,
+ sorter: (a: MarketingAnalyticsSearchRow, b: MarketingAnalyticsSearchRow) =>
+ (a[metric] ?? -1) - (b[metric] ?? -1),
+ render: (_: unknown, row: MarketingAnalyticsSearchRow) => {
+ const value = row[metric] ?? null
+ const money = metric === 'cost' || metric === 'cpc' || metric === 'cpa'
+ const currency =
+ row.currency && Object.values(CurrencyCode).includes(row.currency as CurrencyCode)
+ ? (row.currency as CurrencyCode)
+ : null
+ return (
+ <div>
+ <ChangeValueCell
+ value={value === null ? null : [value, row.previous?.[metric] ?? null]}
+ compare={!!query.compareFilter?.compare}
+ kind={
+ metric === 'ctr'
+ ? 'percentage'
+ : money && currency
+ ? 'currency'
+ : metric === 'conversions' || metric === 'position' || money
+ ? 'decimal'
+ : 'number'
+ }
+ currency={currency ?? CurrencyCode.USD}
+ reverseColors={
+ metric === 'cost' ||
+ metric === 'cpc' ||
+ metric === 'cpa' ||
+ metric === 'position'
+ }
+ />
+ {money && row.platform !== 'GoogleSearchConsole' && (
+ <span className="block text-xs text-secondary">
+ {row.currency ?? 'Unknown currency'}
+ </span>
+ )}
+ </div>
+ )
+ },
+ })),
+ ]}
+ />
+ )
+}
diff --git a/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx b/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx
new file mode 100644
index 000000000000..5c16e5c2763f
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx
@@ -0,0 +1,44 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'
+
+import { SEARCH_PLATFORM_LABELS } from './searchPerformance'
+import { searchPerformanceLogic } from './searchPerformanceLogic'
+
+export function SearchSourceSuggestions(): JSX.Element {
+ const { missingSources } = useValues(searchPerformanceLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+ return (
+ <>
+ {missingSources.map((source) => (
+ <LemonBanner
+ key={source}
+ type="info"
+ action={{
+ children: `Connect ${SEARCH_PLATFORM_LABELS[source]}`,
+ icon: <SourceIcon type={source} size="xsmall" disableTooltip />,
+ disabledReason: restrictedReason,
+ to: urls.dataWarehouseSourceNew(
+ source,
+ `${urls.marketingAnalyticsApp()}?tab=ad-performance`,
+ 'Marketing analytics'
+ ),
+ }}
+ >
+ {source === 'GoogleAds'
+ ? 'Connect Google Ads to see paid keywords, spend and conversions.'
+ : 'Connect Google Search Console to see organic queries, landing pages and average positions.'}
+ </LemonBanner>
+ ))}
+ </>
+ )
+}
diff --git a/products/marketing_analytics/frontend/search/searchPerformance.test.ts b/products/marketing_analytics/frontend/search/searchPerformance.test.ts
new file mode 100644
index 000000000000..4b78320059a7
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/searchPerformance.test.ts
@@ -0,0 +1,97 @@
+import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'
+
+import { searchPerformanceSource, selectedSearchSources } from './searchPerformance'
+
+const schema = (name: string, shouldSync = true, synced = true): ExternalDataSourceSchema =>
+ ({
+ name,
+ should_sync: shouldSync,
+ table: synced ? { name: `example_${name}`, hogql_name: `example.${name}` } : undefined,
+ }) as ExternalDataSourceSchema
+
+describe('search performance sources', () => {
+ it.each([
+ [
+ 'GoogleAds',
+ [schema('keyword'), schema('keyword_stats')],
+ { sourceType: 'GoogleAds', keywordTable: 'example.keyword', statsTable: 'example.keyword_stats' },
+ ],
+ ['GoogleAds', [schema('keyword'), schema('keyword_stats', false)], null],
+ ['GoogleAds', [schema('keyword', true, false), schema('keyword_stats')], null],
+ ['GoogleAds', [schema('search_term_stats')], null],
+ [
+ 'BingAds',
+ [schema('keyword_performance_report')],
+ { sourceType: 'BingAds', statsTable: 'example.keyword_performance_report' },
+ ],
+ ['BingAds', [schema('keyword_performance_report', false)], null],
+ [
+ 'GoogleSearchConsole',
+ [schema('search_analytics_by_query')],
+ {
+ sourceType: 'GoogleSearchConsole',
+ statsTable: 'example.search_analytics_by_query',
+ queryPageTable: false,
+ },
+ ],
+ [
+ 'GoogleSearchConsole',
+ [schema('search_analytics_by_query', false), schema('search_analytics_by_query_page')],
+ {
+ sourceType: 'GoogleSearchConsole',
+ statsTable: 'example.search_analytics_by_query_page',
+ queryPageTable: true,
+ },
+ ],
+ ['GoogleSearchConsole', [schema('search_analytics_by_query_page', true, false)], null],
+ ])('requires synced keyword tables for %s', (source_type, schemas, expected) => {
+ expect(searchPerformanceSource({ source_type, schemas } as ExternalDataSource)).toEqual(expected)
+ })
+
+ it.each([
+ ['GoogleAds', ['landing_page_stats'], 'page', false, 'example.landing_page_stats'],
+ ['BingAds', ['keyword_performance_report'], 'page', false, undefined],
+ [
+ 'GoogleSearchConsole',
+ ['search_analytics_by_page', 'search_analytics_by_query_page'],
+ 'page',
+ false,
+ 'example.search_analytics_by_page',
+ ],
+ [
+ 'GoogleSearchConsole',
+ ['search_analytics_by_query', 'search_analytics_by_query_page'],
+ 'keyword',
+ true,
+ 'example.search_analytics_by_query_page',
+ ],
+ ['GoogleSearchConsole', ['search_analytics_by_query'], 'keyword', true, undefined],
+ ] as const)('uses the right table for %s %s %s details=%s', (source_type, schemas, breakdown, detail, expected) => {
+ expect(
+ searchPerformanceSource(
+ { source_type, schemas: schemas.map((name) => schema(name)) } as ExternalDataSource,
+ breakdown,
+ detail
+ )?.statsTable
+ ).toEqual(expected)
+ })
+
+ it.each([
+ [[], ['google-main', 'google-secondary', 'bing']],
+ [['google-secondary'], ['google-secondary']],
+ [
+ ['google-main', 'bing'],
+ ['google-main', 'bing'],
+ ],
+ [['meta'], []],
+ [['meta', 'bing'], ['bing']],
+ ])('selects connected search accounts for %j', (selectedIds, expectedIds) => {
+ const sources = [
+ { id: 'google-main', source_type: 'GoogleAds' },
+ { id: 'google-secondary', source_type: 'GoogleAds' },
+ { id: 'bing', source_type: 'BingAds' },
+ { id: 'meta', source_type: 'MetaAds' },
+ ] as ExternalDataSource[]
+ expect(selectedSearchSources(sources, selectedIds).map((source) => source.id)).toEqual(expectedIds)
+ })
+})
diff --git a/products/marketing_analytics/frontend/search/searchPerformance.ts b/products/marketing_analytics/frontend/search/searchPerformance.ts
new file mode 100644
index 000000000000..c3b9560ed4f7
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/searchPerformance.ts
@@ -0,0 +1,67 @@
+import { MarketingAnalyticsSearchQuery, MarketingAnalyticsSearchSource } from '~/queries/schema/schema-general'
+import { ExternalDataSource } from '~/types'
+
+export type SearchPlatform = MarketingAnalyticsSearchSource['sourceType']
+export type SearchMetrics = 'traffic' | 'conversions'
+export type SearchBreakdown = NonNullable<MarketingAnalyticsSearchQuery['breakdown']>
+export type SearchChannel = 'all' | 'paid' | 'organic'
+
+export const SEARCH_PLATFORM_LABELS: Record<SearchPlatform, string> = {
+ GoogleAds: 'Google Ads',
+ BingAds: 'Bing Ads',
+ GoogleSearchConsole: 'Google Search Console',
+}
+
+export function searchPerformanceSource(
+ source: ExternalDataSource,
+ breakdown: SearchBreakdown = 'keyword',
+ detail = false
+): MarketingAnalyticsSearchSource | null {
+ const table = (name: string): string | undefined => {
+ const schema = source.schemas.find((schema) => schema.name === name && schema.should_sync && schema.table)
+ return schema?.table?.hogql_name ?? schema?.table?.name
+ }
+ if (source.source_type === 'GoogleSearchConsole') {
+ const queryPage = table('search_analytics_by_query_page')
+ const aggregate = detail
+ ? undefined
+ : table(breakdown === 'page' ? 'search_analytics_by_page' : 'search_analytics_by_query')
+ const statsTable = aggregate ?? queryPage
+ return statsTable ? { sourceType: 'GoogleSearchConsole', statsTable, queryPageTable: !aggregate } : null
+ }
+ if (source.source_type === 'GoogleAds') {
+ if (breakdown === 'page') {
+ const statsTable = table('landing_page_stats')
+ return statsTable ? { sourceType: 'GoogleAds', statsTable } : null
+ }
+ const statsTable = table('keyword_stats')
+ const keywordTable = table('keyword')
+ return statsTable && keywordTable ? { sourceType: 'GoogleAds', statsTable, keywordTable } : null
+ }
+ if (source.source_type === 'BingAds' && breakdown === 'keyword') {
+ const statsTable = table('keyword_performance_report')
+ return statsTable ? { sourceType: 'BingAds', statsTable } : null
+ }
+ return null
+}
+
+export const SEARCH_SOURCE_TYPES = ['GoogleAds', 'BingAds', 'GoogleSearchConsole']
+
+export function selectedSearchSources(sources: ExternalDataSource[], selectedIds: string[]): ExternalDataSource[] {
+ const searchSources = sources.filter((source) => SEARCH_SOURCE_TYPES.includes(source.source_type))
+ const selected = searchSources.filter((source) => selectedIds.includes(source.id))
+ return selectedIds.length > 0 ? selected : searchSources
+}
+
+export function requiredSearchTables(source: ExternalDataSource, breakdown: SearchBreakdown): string {
+ if (source.source_type === 'GoogleSearchConsole') {
+ return breakdown === 'page'
+ ? 'search_analytics_by_page or search_analytics_by_query_page'
+ : 'search_analytics_by_query or search_analytics_by_query_page'
+ }
+ return source.source_type === 'GoogleAds'
+ ? breakdown === 'page'
+ ? 'landing_page_stats'
+ : 'keyword and keyword_stats'
+ : 'keyword_performance_report'
+}
diff --git a/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts b/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts
new file mode 100644
index 000000000000..b2f7170deefd
--- /dev/null
+++ b/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts
@@ -0,0 +1,242 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+
+import {
+ marketingAnalyticsLogic,
+ marketingAnalyticsLogicActions,
+ marketingAnalyticsLogicValues,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+
+import {
+ MarketingAnalyticsSearchQuery,
+ MarketingAnalyticsSearchRow,
+ MarketingAnalyticsSearchSource,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { ExternalDataSource } from '~/types'
+
+import {
+ SearchBreakdown,
+ SearchChannel,
+ SearchMetrics,
+ SearchPlatform,
+ selectedSearchSources,
+ searchPerformanceSource,
+} from './searchPerformance'
+
+export interface searchPerformanceLogicValues extends Pick<
+ marketingAnalyticsLogicValues,
+ 'dataWarehouseSources' | 'dataWarehouseSourcesLoading' | 'dateFilter' | 'compareFilter' | 'integrationFilter'
+> {
+ metrics: SearchMetrics
+ hasPaidSources: boolean
+ displayMetrics: SearchMetrics
+ showPosition: boolean
+ canShowPosition: boolean
+ breakdown: SearchBreakdown
+ channel: SearchChannel
+ selectedRow: MarketingAnalyticsSearchRow | null
+ detailQuery: MarketingAnalyticsSearchQuery | null
+ allSearchSources: ExternalDataSource[]
+ missingSources: SearchPlatform[]
+ hasActiveFilters: boolean
+ hasSearchConsole: boolean
+ hasSelectedBingSource: boolean
+ search: string
+ querySearch: string
+ sourcesError: boolean
+ sources: ExternalDataSource[]
+ pendingSources: ExternalDataSource[]
+ readySources: MarketingAnalyticsSearchSource[]
+ query: MarketingAnalyticsSearchQuery
+}
+
+export interface searchPerformanceLogicActions extends Pick<
+ marketingAnalyticsLogicActions,
+ 'loadSources' | 'loadSourcesSuccess' | 'loadSourcesFailure' | 'setIntegrationFilter' | 'setDates'
+> {
+ clearFilters: () => { value: true }
+ setShowPosition: (showPosition: boolean) => { showPosition: boolean }
+ setMetrics: (metrics: SearchMetrics) => { metrics: SearchMetrics }
+ setBreakdown: (breakdown: SearchBreakdown) => { breakdown: SearchBreakdown }
+ setChannel: (channel: SearchChannel) => { channel: SearchChannel }
+ selectRow: (row: MarketingAnalyticsSearchRow | null) => { row: MarketingAnalyticsSearchRow | null }
+ setSearch: (search: string) => { search: string }
+ setQuerySearch: (search: string) => { search: string }
+}
+
+export type searchPerformanceLogicType = MakeLogicType<searchPerformanceLogicValues, searchPerformanceLogicActions>
+
+export const searchPerformanceLogic = kea<searchPerformanceLogicType>([
+ path(['products', 'marketingAnalytics', 'searchPerformanceLogic']),
+ connect(() => ({
+ values: [
+ marketingAnalyticsLogic,
+ ['dataWarehouseSources', 'dataWarehouseSourcesLoading', 'dateFilter', 'compareFilter', 'integrationFilter'],
+ ],
+ actions: [
+ marketingAnalyticsLogic,
+ ['loadSources', 'loadSourcesSuccess', 'loadSourcesFailure', 'setIntegrationFilter', 'setDates'],
+ ],
+ })),
+ actions({
+ clearFilters: true,
+ setMetrics: (metrics: SearchMetrics) => ({ metrics }),
+ setShowPosition: (showPosition: boolean) => ({ showPosition }),
+ setBreakdown: (breakdown: SearchBreakdown) => ({ breakdown }),
+ setChannel: (channel: SearchChannel) => ({ channel }),
+ selectRow: (row: MarketingAnalyticsSearchRow | null) => ({ row }),
+ setSearch: (search: string) => ({ search }),
+ setQuerySearch: (search: string) => ({ search }),
+ }),
+ reducers({
+ breakdown: ['keyword' as SearchBreakdown, { setBreakdown: (_, { breakdown }) => breakdown }],
+ channel: ['all' as SearchChannel, { setChannel: (_, { channel }) => channel }],
+ selectedRow: [
+ null as MarketingAnalyticsSearchRow | null,
+ { selectRow: (_, { row }) => row, setBreakdown: () => null, setChannel: () => null },
+ ],
+ showPosition: [false, { setShowPosition: (_, { showPosition }) => showPosition }],
+ metrics: ['traffic' as SearchMetrics, { setMetrics: (_, { metrics }) => metrics }],
+ search: ['', { setSearch: (_, { search }) => search }],
+ querySearch: ['', { setQuerySearch: (_, { search }) => search }],
+ sourcesError: [
+ false,
+ { loadSources: () => false, loadSourcesSuccess: () => false, loadSourcesFailure: () => true },
+ ],
+ }),
+ selectors({
+ allSearchSources: [
+ (s) => [s.dataWarehouseSources],
+ (response): ExternalDataSource[] => selectedSearchSources(response?.results ?? [], []),
+ ],
+ missingSources: [
+ (s) => [s.allSearchSources],
+ (sources: ExternalDataSource[]): SearchPlatform[] =>
+ (['GoogleAds', 'GoogleSearchConsole'] as SearchPlatform[]).filter(
+ (type) => !sources.some((source) => source.source_type === type)
+ ),
+ ],
+ hasActiveFilters: [
+ (s) => [s.querySearch, s.channel, s.integrationFilter, s.dateFilter, s.allSearchSources],
+ (search, channel, filter, dates, sources: ExternalDataSource[]): boolean => {
+ const ids = filter.integrationSourceIds ?? []
+ const allSourcesSelected = sources.length > 0 && sources.every((source) => ids.includes(source.id))
+ return (
+ !!search.trim() ||
+ channel !== 'all' ||
+ (ids.length > 0 && !allSourcesSelected) ||
+ dates.dateFrom !== '-7d' ||
+ !!dates.dateTo
+ )
+ },
+ ],
+ hasSearchConsole: [
+ (s) => [s.allSearchSources],
+ (sources: ExternalDataSource[]): boolean =>
+ sources.some((source) => source.source_type === 'GoogleSearchConsole'),
+ ],
+ hasSelectedBingSource: [
+ (s) => [s.allSearchSources, s.integrationFilter],
+ (sources: ExternalDataSource[], integrationFilter): boolean =>
+ selectedSearchSources(sources, integrationFilter.integrationSourceIds ?? []).some(
+ (source) => source.source_type === 'BingAds'
+ ),
+ ],
+ sources: [
+ (s) => [s.allSearchSources, s.integrationFilter, s.channel, s.breakdown],
+ (allSources, integrationFilter, channel, breakdown): ExternalDataSource[] =>
+ selectedSearchSources(allSources, integrationFilter.integrationSourceIds ?? []).filter(
+ (source) =>
+ (channel === 'all' ||
+ (source.source_type === 'GoogleSearchConsole'
+ ? channel === 'organic'
+ : channel === 'paid')) &&
+ (breakdown !== 'page' || source.source_type !== 'BingAds')
+ ),
+ ],
+ pendingSources: [
+ (s) => [s.sources, s.breakdown],
+ (sources: ExternalDataSource[], breakdown): ExternalDataSource[] =>
+ sources.filter((source) => !searchPerformanceSource(source, breakdown)),
+ ],
+ readySources: [
+ (s) => [s.sources, s.breakdown],
+ (sources: ExternalDataSource[], breakdown): MarketingAnalyticsSearchSource[] =>
+ sources.flatMap((source) => {
+ const querySource = searchPerformanceSource(source, breakdown)
+ return querySource ? [querySource] : []
+ }),
+ ],
+ hasPaidSources: [
+ (s) => [s.readySources],
+ (sources: MarketingAnalyticsSearchSource[]): boolean =>
+ sources.some((source) => source.sourceType !== 'GoogleSearchConsole'),
+ ],
+ displayMetrics: [
+ (s) => [s.hasPaidSources, s.metrics],
+ (hasPaidSources: boolean, metrics: SearchMetrics): SearchMetrics => (hasPaidSources ? metrics : 'traffic'),
+ ],
+ canShowPosition: [
+ (s) => [s.readySources, s.metrics],
+ (sources: MarketingAnalyticsSearchSource[], metrics: SearchMetrics): boolean =>
+ metrics === 'traffic' &&
+ sources.some((source) => source.sourceType === 'GoogleSearchConsole') &&
+ sources.some((source) => source.sourceType !== 'GoogleSearchConsole'),
+ ],
+ query: [
+ (s) => [s.readySources, s.dateFilter, s.querySearch, s.compareFilter, s.breakdown],
+ (sources, dateFilter, search, compareFilter, breakdown): MarketingAnalyticsSearchQuery => ({
+ kind: NodeKind.MarketingAnalyticsSearchQuery,
+ sources,
+ breakdown,
+ compareFilter,
+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },
+ search,
+ }),
+ ],
+ detailQuery: [
+ (s) => [s.allSearchSources, s.integrationFilter, s.selectedRow, s.query],
+ (allSources: ExternalDataSource[], integrationFilter, row, query): MarketingAnalyticsSearchQuery | null => {
+ if (!row || !(row.page || row.keyword)) {
+ return null
+ }
+ const sources =
+ row.platform === 'GoogleSearchConsole'
+ ? selectedSearchSources(allSources, integrationFilter.integrationSourceIds ?? [])
+ : allSources
+ const detailSources = sources
+ .filter((source) => source.source_type === 'GoogleSearchConsole')
+ .flatMap((source) => {
+ const detailSource = searchPerformanceSource(source, row.page ? 'keyword' : 'page', true)
+ return detailSource ? [detailSource] : []
+ })
+ return {
+ ...query,
+ sources: detailSources,
+ search: undefined,
+ breakdown: row.page ? 'keyword' : 'page',
+ keyword: row.page ? undefined : (row.keyword ?? undefined),
+ page: row.page ?? undefined,
+ }
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ clearFilters: () => {
+ actions.setSearch('')
+ actions.setQuerySearch('')
+ actions.setChannel('all')
+ actions.setIntegrationFilter({ ...values.integrationFilter, integrationSourceIds: [] })
+ actions.setDates('-7d', null)
+ },
+ setSearch: async ({ search }, breakpoint) => {
+ await breakpoint(300)
+ actions.setQuerySearch(search)
+ },
+ })),
+ afterMount(({ values, actions }) => {
+ if (!values.dataWarehouseSources) {
+ actions.loadSources()
+ }
+ }),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 532c447ace28..0c96e32cb87d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17764,6 +17764,14 @@ export namespace Schemas {
state: string | null;
}
+ export type Breakdown1 = typeof Breakdown1[keyof typeof Breakdown1];
+
+
+ export const Breakdown1 = {
+ Keyword: 'keyword',
+ Page: 'page',
+ } as const;
+
/**
* * `auto` - auto
* * `manual` - manual
@@ -54063,6 +54071,98 @@ export namespace Schemas {
version?: number | null;
}
+ export type Platform = typeof Platform[keyof typeof Platform];
+
+
+ export const Platform = {
+ GoogleAds: 'GoogleAds',
+ BingAds: 'BingAds',
+ GoogleSearchConsole: 'GoogleSearchConsole',
+ } as const;
+
+ export interface MarketingAnalyticsSearchMetrics {
+ clicks: number;
+ conversions?: number | null;
+ cost?: number | null;
+ cpa?: number | null;
+ cpc?: number | null;
+ ctr?: number | null;
+ impressions: number;
+ position?: number | null;
+ }
+
+ export interface MarketingAnalyticsSearchRow {
+ clicks: number;
+ conversions?: number | null;
+ cost?: number | null;
+ cpa?: number | null;
+ cpc?: number | null;
+ ctr?: number | null;
+ currency?: string | null;
+ impressions: number;
+ keyword?: string | null;
+ matchType?: string | null;
+ page?: string | null;
+ platform: Platform;
+ position?: number | null;
+ previous?: MarketingAnalyticsSearchMetrics | null;
+ }
+
+ export interface MarketingAnalyticsSearchQueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsSearchRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export type SourceType = typeof SourceType[keyof typeof SourceType];
+
+
+ export const SourceType = {
+ GoogleAds: 'GoogleAds',
+ BingAds: 'BingAds',
+ GoogleSearchConsole: 'GoogleSearchConsole',
+ } as const;
+
+ export interface MarketingAnalyticsSearchSource {
+ keywordTable?: string | null;
+ queryPageTable?: boolean | null;
+ sourceType: SourceType;
+ statsTable: string;
+ }
+
+ export interface MarketingAnalyticsSearchQuery {
+ breakdown?: Breakdown1 | null;
+ compareFilter?: CompareFilter | null;
+ dateRange?: DateRange | null;
+ keyword?: string | null;
+ kind?: 'MarketingAnalyticsSearchQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ page?: string | null;
+ response?: MarketingAnalyticsSearchQueryResponse | null;
+ search?: string | null;
+ sources: MarketingAnalyticsSearchSource[];
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export type WebAgentContentGrouping = typeof WebAgentContentGrouping[keyof typeof WebAgentContentGrouping];
@@ -56332,7 +56432,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -56358,7 +56458,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -86444,7 +86544,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -87371,6 +87471,28 @@ export namespace Schemas {
}
export interface QueryResponseAlternative38 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MarketingAnalyticsSearchRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative39 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87399,7 +87521,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative39 {
+ export interface QueryResponseAlternative40 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87427,7 +87549,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative40 {
+ export interface QueryResponseAlternative41 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87455,7 +87577,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative41 {
+ export interface QueryResponseAlternative42 {
/** Executed ClickHouse query */
clickhouse?: string | null;
/** Returned columns */
@@ -87492,7 +87614,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative42 {
+ export interface QueryResponseAlternative43 {
dateFrom?: string | null;
dateTo?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -87520,7 +87642,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative43 {
+ export interface QueryResponseAlternative44 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87553,7 +87675,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative44 {
+ export interface QueryResponseAlternative45 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87581,7 +87703,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative45 {
+ export interface QueryResponseAlternative46 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87608,7 +87730,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative46 {
+ export interface QueryResponseAlternative47 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87639,7 +87761,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative47 {
+ export interface QueryResponseAlternative48 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -87668,7 +87790,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative48 {
+ export interface QueryResponseAlternative49 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87695,7 +87817,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative49 {
+ export interface QueryResponseAlternative50 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87722,7 +87844,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative50 {
+ export interface QueryResponseAlternative51 {
columns?: unknown[] | null;
/** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
dataComputedAt?: string | null;
@@ -87754,9 +87876,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative51Results = {[key: string]: MarketingAnalyticsItem};
+ export type QueryResponseAlternative52Results = {[key: string]: MarketingAnalyticsItem};
- export interface QueryResponseAlternative51 {
+ export interface QueryResponseAlternative52 {
/** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -87773,7 +87895,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative51Results;
+ results: QueryResponseAlternative52Results;
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
@@ -87783,7 +87905,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative52 {
+ export interface QueryResponseAlternative53 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87809,7 +87931,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative53 {
+ export interface QueryResponseAlternative54 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87835,19 +87957,19 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative54CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative55CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative54InsightItemItem = { [key: string]: unknown };
+ export type QueryResponseAlternative55InsightItemItem = { [key: string]: unknown };
- export type QueryResponseAlternative54Probability = {[key: string]: number};
+ export type QueryResponseAlternative55Probability = {[key: string]: number};
- export interface QueryResponseAlternative54 {
- credible_intervals: QueryResponseAlternative54CredibleIntervals;
+ export interface QueryResponseAlternative55 {
+ credible_intervals: QueryResponseAlternative55CredibleIntervals;
expected_loss: number;
funnels_query?: FunnelsQuery | null;
- insight: QueryResponseAlternative54InsightItemItem[][];
+ insight: QueryResponseAlternative55InsightItemItem[][];
kind?: 'ExperimentFunnelsQuery';
- probability: QueryResponseAlternative54Probability;
+ probability: QueryResponseAlternative55Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -87856,20 +87978,20 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export type QueryResponseAlternative55CredibleIntervals = {[key: string]: number[]};
+ export type QueryResponseAlternative56CredibleIntervals = {[key: string]: number[]};
- export type QueryResponseAlternative55InsightItem = { [key: string]: unknown };
+ export type QueryResponseAlternative56InsightItem = { [key: string]: unknown };
- export type QueryResponseAlternative55Probability = {[key: string]: number};
+ export type QueryResponseAlternative56Probability = {[key: string]: number};
- export interface QueryResponseAlternative55 {
+ export interface QueryResponseAlternative56 {
count_query?: TrendsQuery | null;
- credible_intervals: QueryResponseAlternative55CredibleIntervals;
+ credible_intervals: QueryResponseAlternative56CredibleIntervals;
exposure_query?: TrendsQuery | null;
- insight: QueryResponseAlternative55InsightItem[];
+ insight: QueryResponseAlternative56InsightItem[];
kind?: 'ExperimentTrendsQuery';
p_value: number;
- probability: QueryResponseAlternative55Probability;
+ probability: QueryResponseAlternative56Probability;
significance_code: ExperimentSignificanceCode;
significant: boolean;
stats_version?: number | null;
@@ -87878,7 +88000,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative56 {
+ export interface QueryResponseAlternative57 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87904,7 +88026,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative58 {
+ export interface QueryResponseAlternative59 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87931,7 +88053,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative59 {
+ export interface QueryResponseAlternative60 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -87961,7 +88083,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative60 {
+ export interface QueryResponseAlternative61 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -87989,9 +88111,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative61ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative62ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative61 {
+ export interface QueryResponseAlternative62 {
boxplot_data?: BoxPlotDatum[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88007,7 +88129,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative61ResultsItem[];
+ results: QueryResponseAlternative62ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -88016,7 +88138,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative62 {
+ export interface QueryResponseAlternative63 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88040,7 +88162,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative63 {
+ export interface QueryResponseAlternative64 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88062,7 +88184,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative64 {
+ export interface QueryResponseAlternative65 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88084,7 +88206,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88106,9 +88228,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative66ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative67ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative66 {
+ export interface QueryResponseAlternative67 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88121,7 +88243,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative66ResultsItem[];
+ results: QueryResponseAlternative67ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -88130,7 +88252,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative68 {
+ export interface QueryResponseAlternative69 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88157,14 +88279,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative69Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative70Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative69 {
+ export interface QueryResponseAlternative70 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative69Tables;
+ tables: QueryResponseAlternative70Tables;
}
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -88189,7 +88311,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative71 {
+ export interface QueryResponseAlternative72 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88217,7 +88339,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative72 {
+ export interface QueryResponseAlternative73 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88240,7 +88362,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88262,7 +88384,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative74 {
+ export interface QueryResponseAlternative75 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88284,7 +88406,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative75 {
+ export interface QueryResponseAlternative76 {
/** Upper bound per row (y axis), ascending. */
bounds: number[];
/** Observation count per cell: counts[row][column], row = bound, column = time. */
@@ -88312,7 +88434,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative76 {
+ export interface QueryResponseAlternative77 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -88339,7 +88461,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative77 {
+ export interface QueryResponseAlternative78 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AggregatedSpanRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -88363,7 +88485,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative78 {
+ export interface QueryResponseAlternative79 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: SpanTreeNode[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -88387,7 +88509,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative79 {
+ export interface QueryResponseAlternative80 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AttributeBreakdownRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -88411,13 +88533,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative80 {
+ export interface QueryResponseAlternative81 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative81 {
+ export interface QueryResponseAlternative82 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -88442,7 +88564,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative82 {
+ export interface QueryResponseAlternative83 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -88467,7 +88589,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative83 {
+ export interface QueryResponseAlternative84 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88489,7 +88611,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative84 {
+ export interface QueryResponseAlternative85 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88515,7 +88637,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative87 {
+ export interface QueryResponseAlternative88 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -88530,7 +88652,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative88 {
+ export interface QueryResponseAlternative89 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88552,7 +88674,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative89 {
+ export interface QueryResponseAlternative90 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88574,7 +88696,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88604,7 +88726,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -88632,7 +88754,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative92 {
+ export interface QueryResponseAlternative93 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88654,7 +88776,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -88681,9 +88803,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative94ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative95ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88696,7 +88818,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative94ResultsItem[];
+ results: QueryResponseAlternative95ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -88705,7 +88827,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative95 {
+ export interface QueryResponseAlternative96 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88727,7 +88849,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative96 {
+ export interface QueryResponseAlternative97 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88749,7 +88871,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative97 {
+ export interface QueryResponseAlternative98 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88771,7 +88893,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative98 {
+ export interface QueryResponseAlternative99 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Whether another page of individual model identifiers is available. */
@@ -88795,7 +88917,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative99 {
+ export interface QueryResponseAlternative100 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88817,7 +88939,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative100 {
+ export interface QueryResponseAlternative101 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88839,7 +88961,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative101 {
+ export interface QueryResponseAlternative102 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88861,7 +88983,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative102 {
+ export interface QueryResponseAlternative103 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88883,7 +89005,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88906,7 +89028,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative104 {
+ export interface QueryResponseAlternative105 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88928,7 +89050,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative105 {
+ export interface QueryResponseAlternative106 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88956,7 +89078,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative106 {
+ export interface QueryResponseAlternative107 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -88978,7 +89100,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative107 {
+ export interface QueryResponseAlternative108 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89000,7 +89122,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative108 {
+ export interface QueryResponseAlternative109 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89022,7 +89144,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative109 {
+ export interface QueryResponseAlternative110 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89044,7 +89166,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative110 {
+ export interface QueryResponseAlternative111 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89066,7 +89188,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative111 {
+ export interface QueryResponseAlternative112 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89088,7 +89210,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative112 {
+ export interface QueryResponseAlternative113 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89110,7 +89232,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative113 {
+ export interface QueryResponseAlternative114 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Whether more reports exist past this page. */
@@ -89134,7 +89256,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative114 {
+ export interface QueryResponseAlternative115 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -89156,7 +89278,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | unknown | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113 | QueryResponseAlternative114;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113 | QueryResponseAlternative114 | QueryResponseAlternative115;
export interface QueryScanResponse {
analysis?: QueryScanAnalysis | null;
@@ -89167,11 +89289,11 @@ export namespace Schemas {
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {