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(warehouse): add combined dimension cuts and search type to Google Search Console (#80680)

Kyle Swank3d3f0ea1cfd5
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 107435144c88..dabf93d8fcdb 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -49345,6 +49345,10 @@
"label": {
"type": "string"
},
+ "multiple": {
+ "description": "Allow selecting multiple values; the field's payload value becomes string[].",
+ "type": "boolean"
+ },
"name": {
"type": "string"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 7870a12601d3..40aa2d2e9e7d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -7497,6 +7497,8 @@ export interface SourceFieldSelectConfig {
options: SourceFieldSelectConfigOption[]
converter?: SourceFieldSelectConfigConverter
caption?: string
+ /** Allow selecting multiple values; the field's payload value becomes string[]. */
+ multiple?: boolean
}
export interface SourceFieldSwitchGroupConfig {
diff --git a/posthog/schema.py b/posthog/schema.py
index d13119cf7fcd..42ee341b177b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -30372,6 +30372,10 @@ class SourceFieldSelectConfig(BaseModel):
converter: SourceFieldSelectConfigConverter | None = None
defaultValue: str
label: str
+ multiple: bool | None = Field(
+ default=None,
+ description=("Allow selecting multiple values; the field's payload value becomes string[]."),
+ )
name: str
options: list[SourceFieldSelectConfigOption]
required: bool
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 20d772fbf372..f529c156974f 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -170,6 +170,11 @@ export const buildKeaFormDefaultFromSourceDetails = (
if (field.type === 'select') {
const hasOptionFields = !!field.options.filter((n) => (n.fields?.length ?? 0) > 0).length
+ if (field.multiple) {
+ obj[field.name] = field.defaultValue ? [field.defaultValue] : []
+ return
+ }
+
if (hasOptionFields) {
obj[field.name] = {}
obj[field.name]['selection'] = field.defaultValue
@@ -3923,8 +3928,14 @@ export const getErrorsForFields = (
const hasOptionFields = !!field.options.filter((n) => (n.fields?.length ?? 0) > 0).length
if (!hasOptionFields) {
- if (field.required && !valueObj[field.name]) {
- errorsObj[field.name] = `${field.label} is required`
+ // An empty array is truthy, so a multiple select needs its own emptiness
+ // check or `required` passes with nothing selected.
+ const selected = valueObj[field.name]
+ const selectionMissing = Array.isArray(selected) ? selected.length === 0 : !selected
+ if (field.required && selectionMissing) {
+ errorsObj[field.name] = Array.isArray(selected)
+ ? `Please select at least one of your ${field.label.toLowerCase()}`
+ : `${field.label} is required`
}
} else {
errorsObj[field.name] = {}
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 61cc71a9aac2..077441b34137 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -192,6 +192,33 @@ describe('sourceWizardLogic', () => {
expect(res).toEqual({ prefix: '', description: '', payload: { test_field: 'value1' } })
})
+ it('returns an array default for a multiple select field', async () => {
+ const sourceWizardLogic = await import('../sourceWizardLogic')
+ const res = sourceWizardLogic.buildKeaFormDefaultFromSourceDetails({
+ Test: {
+ name: 'GoogleSearchConsole',
+ iconPath: '',
+ caption: null,
+ fields: [
+ {
+ name: 'search_types',
+ label: 'Search types',
+ type: 'select',
+ required: true,
+ multiple: true,
+ options: [
+ { value: 'web', label: 'Web' },
+ { value: 'image', label: 'Image' },
+ ],
+ defaultValue: 'web',
+ },
+ ],
+ },
+ })
+
+ expect(res).toEqual({ prefix: '', description: '', payload: { search_types: ['web'] } })
+ })
+
it('returns defaults for select field with fields', async () => {
const sourceWizardLogic = await import('../sourceWizardLogic')
const res = sourceWizardLogic.buildKeaFormDefaultFromSourceDetails({
@@ -362,6 +389,50 @@ describe('sourceWizardLogic', () => {
expect(res.payload.test_field).toBeTruthy()
})
+ it('returns an error for a required multiple select with nothing selected', () => {
+ // An empty array is truthy, so without an array-aware check the form submits
+ // with no selection and the source syncs nothing.
+ const res = getErrorsForFields(
+ [
+ {
+ name: 'search_types',
+ label: 'Search types',
+ type: 'select',
+ required: true,
+ multiple: true,
+ options: [
+ { value: 'web', label: 'Web' },
+ { value: 'image', label: 'Image' },
+ ],
+ defaultValue: 'web',
+ },
+ ],
+ { prefix: '', payload: { search_types: [] } }
+ )
+ expect(res.payload.search_types).toBeTruthy()
+ })
+
+ it('returns no errors for a required multiple select with a selection', () => {
+ const res = getErrorsForFields(
+ [
+ {
+ name: 'search_types',
+ label: 'Search types',
+ type: 'select',
+ required: true,
+ multiple: true,
+ options: [
+ { value: 'web', label: 'Web' },
+ { value: 'image', label: 'Image' },
+ ],
+ defaultValue: 'web',
+ },
+ ],
+ { prefix: '', payload: { search_types: ['image'] } }
+ )
+ expect(res.payload).toEqual({})
+ })
+
it('returns no errors for an empty non-required text field', () => {
const res = getErrorsForFields(
[
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
index 78ca0169fa56..9d66c6f964d2 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
@@ -7,6 +7,7 @@ import {
LemonDivider,
LemonFileInput,
LemonInput,
+ LemonInputSelect,
LemonSelect,
LemonSkeleton,
LemonSwitch,
@@ -230,6 +231,31 @@ export const sourceFieldToElement = (
)
}
+ if (field.type === 'select' && field.multiple) {
+ // A config saved before the field became multiple still holds a bare string.
+ const toArray = (value: any): string[] => (Array.isArray(value) ? value : value ? [value] : [])
+
+ return (
+ <LemonField
+ key={field.name}
+ name={field.name}
+ label={field.label}
+ help={field.caption ? <LemonMarkdown className="text-xs">{field.caption}</LemonMarkdown> : undefined}
+ >
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ data-attr={field.name}
+ placeholder={`Select ${field.label.toLowerCase()}`}
+ options={field.options.map((option) => ({ key: option.value, label: option.label }))}
+ value={toArray(value === undefined || value === null ? lastValue?.[field.name] : value)}
+ onChange={onChange}
+ />
+ )}
+ </LemonField>
+ )
+ }
+
if (field.type === 'select') {
const hasOptionFields = !!field.options.filter((n) => (n.fields?.length ?? 0) > 0).length
diff --git a/products/warehouse_sources/backend/management/commands/generate_source_configs.py b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
index 85272fccff46..84626a97aabb 100644
--- a/products/warehouse_sources/backend/management/commands/generate_source_configs.py
+++ b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
@@ -176,6 +176,22 @@ class SourceConfigGenerator:
) -> tuple[list[str], list[str]]:
has_option_fields = any(option.fields for option in field.options if option.fields)
+ if field.multiple:
+ if field.converter:
+ raise ValueError(f"Select field '{field.name}' cannot combine `multiple` with a converter")
+ if has_option_fields:
+ raise ValueError(f"Select field '{field.name}' cannot combine `multiple` with per-option fields")
+
+ python_field_name, should_alias = self._make_python_identifier(field.name)
+ # Always optional on the dataclass, even when the form field is required: configs
+ # stored before the field existed must keep parsing. "At least one value" is the
+ # source's job (validate_credentials / effective_* helpers).
+ field_parts = ["converter=config.str_to_optional_list"]
+ if should_alias:
+ field_parts.append(f'alias="{field.name}"')
+ field_parts.append("default_factory=lambda: None")
+ return [f" {python_field_name}: list[str] | None = config.value({', '.join(field_parts)})"], []
+
field_parts = []
if not field.required and not field.defaultValue:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
index e16c1a864c27..59c2a5875bd4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
@@ -318,6 +318,37 @@ class TestSourceConfigGenerator(ClickhouseTestMixin):
in output
)
+ @pytest.mark.parametrize("required", [True, False])
+ def test_source_config_select_multiple_emits_optional_list(self, required):
+ # Same contract as the multiple oauth-account select: an optional list either way, so a
+ # config saved before the field existed keeps parsing.
+ config = SourceConfig(
+ name=SchemaExternalDataSourceType.GOOGLE_SEARCH_CONSOLE,
+ iconPath="",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="search_types",
+ label="Search types",
+ required=required,
+ defaultValue="web",
+ multiple=True,
+ options=[
+ SourceFieldSelectConfigOption(label="Web", value="web"),
+ SourceFieldSelectConfigOption(label="Image", value="image"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ output = self._run({ExternalDataSourceType.GOOGLESEARCHCONSOLE: config})
+ assert (
+ "search_types: list[str] | None = config.value(converter=config.str_to_optional_list, default_factory=lambda: None)"
+ in output
+ )
+
def test_source_config_ssh_tunnel_non_python_identifier(self):
config = SourceConfig(
name=SchemaExternalDataSourceType.STRIPE,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googlesearchconsole.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googlesearchconsole.py
index 5338c5a073ff..2ef7e4439dd3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googlesearchconsole.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googlesearchconsole.py
@@ -8,3 +8,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class GoogleSearchConsoleSourceConfig(config.Config):
site_url: str
google_search_console_integration_id: int = config.value(converter=config.str_to_int)
+ search_types: list[str] | None = config.value(converter=config.str_to_optional_list, default_factory=lambda: None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py
index 5ba8c8f26578..4e90c455151f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py
@@ -2,6 +2,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
CanonicalEndpoint,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (
+ NON_WEB_SEARCH_TYPES,
+ SEARCH_ANALYTICS_SCHEMAS,
+ qualified_schema_name,
+)
_SEARCH_ANALYTICS_DOCS_URL = "https://developers.google.com/webmaster-tools/v1/searchanalytics/query"
_SITES_DOCS_URL = "https://developers.google.com/webmaster-tools/v1/sites/list"
@@ -19,12 +24,19 @@ _DATE_COLUMN = {
"date": "The day the metrics were recorded, in Pacific time (UTC-7:00/8:00).",
}
+_SEARCH_TYPE_COLUMN = {
+ "search_type": (
+ "The search result type these rows come from: web, image, video, or news. "
+ "Constant within a table, and null for rows imported before this column existed."
+ ),
+}
+
def _search_analytics(description: str, **dimensions: str) -> CanonicalEndpoint:
return {
"description": description,
"docs_url": _SEARCH_ANALYTICS_DOCS_URL,
- "columns": {**_DATE_COLUMN, **dimensions, **_METRIC_COLUMNS},
+ "columns": {**_DATE_COLUMN, **dimensions, **_METRIC_COLUMNS, **_SEARCH_TYPE_COLUMN},
}
@@ -33,7 +45,7 @@ _PAGE_COLUMN = "The canonical URL of the result page the user saw."
_COUNTRY_COLUMN = "Country the search was made from, as a three-letter ISO 3166-1 alpha-3 code."
_DEVICE_COLUMN = "Device the search was made on: DESKTOP, MOBILE, or TABLET."
-CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+_BASE_DESCRIPTIONS: CanonicalDescriptions = {
"search_analytics_by_date": _search_analytics("Daily search performance totals for the property."),
"search_analytics_by_query": _search_analytics(
"Daily search performance for the property, grouped by search query.",
@@ -56,6 +68,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
country=_COUNTRY_COLUMN,
device=_DEVICE_COLUMN,
),
+ "search_analytics_by_page_device": _search_analytics(
+ "Daily search performance for the property, grouped by landing page and device together.",
+ page=_PAGE_COLUMN,
+ device=_DEVICE_COLUMN,
+ ),
+ "search_analytics_by_page_country": _search_analytics(
+ "Daily search performance for the property, grouped by landing page and the searcher's country.",
+ page=_PAGE_COLUMN,
+ country=_COUNTRY_COLUMN,
+ ),
+ "search_analytics_by_query_device": _search_analytics(
+ "Daily search performance for the property, grouped by search query and device together.",
+ query=_QUERY_COLUMN,
+ device=_DEVICE_COLUMN,
+ ),
+ "search_analytics_by_query_country": _search_analytics(
+ "Daily search performance for the property, grouped by search query and the searcher's country.",
+ query=_QUERY_COLUMN,
+ country=_COUNTRY_COLUMN,
+ ),
"search_analytics_by_query_page": _search_analytics(
"Daily search performance for the property, grouped by search query and landing page.",
query=_QUERY_COLUMN,
@@ -101,3 +133,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
},
}
+
+# Non-web search types reuse their base table's documentation, so a new dimension combo only
+# has to be described once above.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ **_BASE_DESCRIPTIONS,
+ **{
+ qualified_schema_name(base_name, search_type): {
+ **endpoint,
+ "description": f"{endpoint['description']} Restricted to {search_type} search results.",
+ }
+ for search_type in NON_WEB_SEARCH_TYPES
+ for base_name, endpoint in _BASE_DESCRIPTIONS.items()
+ if base_name in SEARCH_ANALYTICS_SCHEMAS and not SEARCH_ANALYTICS_SCHEMAS[base_name].get("web_only")
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
index 4a222a517109..506d1cfbf9e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
@@ -25,8 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
GoogleSearchConsoleSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (
+ DEFAULT_SEARCH_TYPE,
PROPERTY_SCHEMAS,
SEARCH_ANALYTICS_SCHEMAS,
+ split_schema_name,
)
logger = structlog.get_logger(__name__)
@@ -319,6 +321,7 @@ def _query_search_analytics(
start_row: int,
row_limit: int = ROW_LIMIT,
data_state: str = DEFAULT_DATA_STATE,
+ search_type: str = DEFAULT_SEARCH_TYPE,
) -> list[dict[str, Any]]:
body = {
"startDate": start_date,
@@ -327,6 +330,9 @@ def _query_search_analytics(
"rowLimit": row_limit,
"startRow": start_row,
"dataState": data_state,
+ # Sent even for "web". That's Google's own default, so existing web tables are
+ # unaffected, and the request stays explicit about which surface it reads.
+ "type": search_type,
}
url = f"{GSC_API_BASE}/sites/{quote(site_url, safe='')}/searchAnalytics/query"
@@ -433,7 +439,12 @@ def _as_int(value: Any) -> int:
return 0
-def _row_to_dict(row: dict[str, Any], dimensions: list[str], iter_date: dt.date | None = None) -> dict[str, Any]:
+def _row_to_dict(
+ row: dict[str, Any],
+ dimensions: list[str],
+ iter_date: dt.date | None = None,
+ search_type: str = DEFAULT_SEARCH_TYPE,
+) -> dict[str, Any]:
keys = row["keys"]
out: dict[str, Any] = {dim: keys[i] if i < len(keys) else None for i, dim in enumerate(dimensions)}
if "hour" in out:
@@ -456,6 +467,8 @@ def _row_to_dict(row: dict[str, Any], dimensions: list[str], iter_date: dt.date
out["impressions"] = int(row.get("impressions", 0))
out["ctr"] = float(row.get("ctr", 0.0))
out["position"] = float(row.get("position", 0.0))
+ # Constant per table, but carried on the row so the per-type tables can be unioned.
+ out["search_type"] = search_type
return out
@@ -578,10 +591,14 @@ def google_search_console_source(
if resource_name in PROPERTY_SCHEMAS:
return _property_source(config, resource_name, team_id)
- if resource_name not in SEARCH_ANALYTICS_SCHEMAS:
+ base_name, search_type = split_schema_name(resource_name)
+ if base_name not in SEARCH_ANALYTICS_SCHEMAS:
raise ValueError(f"Unknown Google Search Console schema: {resource_name}")
- schema = SEARCH_ANALYTICS_SCHEMAS[resource_name]
+ schema = SEARCH_ANALYTICS_SCHEMAS[base_name]
+ if search_type != DEFAULT_SEARCH_TYPE and schema.get("web_only"):
+ raise ValueError(f"Google Search Console schema {base_name} is only available for web search")
+
dimensions = schema["dimensions"]
primary_keys = list(schema["primary_key"])
data_state = schema.get("data_state", DEFAULT_DATA_STATE)
@@ -631,11 +648,12 @@ def google_search_console_source(
dimensions=dimensions,
start_row=start_row,
data_state=data_state,
+ search_type=search_type,
)
if not rows:
break
- yield [_row_to_dict(row, dimensions, iter_date=current) for row in rows]
+ yield [_row_to_dict(row, dimensions, iter_date=current, search_type=search_type) for row in rows]
next_start_row = start_row + len(rows)
if len(rows) < ROW_LIMIT:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py
index 5ebed0f4a83f..29ba16185553 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py
@@ -19,6 +19,18 @@ class SearchAnalyticsSchema(TypedDict):
# watermark. Only sane for tables whose window is a handful of days and whose
# rows Google keeps restating.
ignore_incremental_watermark: NotRequired[bool]
+ # Offer this table for web search only. Google documents neither support nor a
+ # restriction for pairing `hour`/`searchAppearance` with a non-web `type`, so these
+ # stay web-only rather than shipping tables that may silently sync nothing.
+ web_only: NotRequired[bool]
+
+
+DEFAULT_SEARCH_TYPE = "web"
+# Google's `type` parameter. `discover` and `googleNews` are deliberately left out: both
+# reject `aggregationType=byProperty` and behave differently enough to need their own
+# dimension catalog rather than a cross product with the schemas below.
+SEARCH_TYPES = ("web", "image", "video", "news")
+NON_WEB_SEARCH_TYPES = tuple(t for t in SEARCH_TYPES if t != DEFAULT_SEARCH_TYPE)
# Each schema maps to a single Search Analytics query with a fixed dimension set.
@@ -76,6 +88,47 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {
"(countries x three device types), so it stays well under the row sampling cap."
),
},
+ "search_analytics_by_page_device": {
+ "dimensions": ["date", "page", "device"],
+ "primary_key": ["date", "page", "device"],
+ "should_sync_default": False,
+ "description": (
+ "Daily performance broken out by landing page and device together. Answers questions "
+ "like mobile CTR per landing page. Roughly three rows per page per day, so it hits "
+ "Google's ~50K row/day API sampling cap about three times sooner than the per-page table."
+ ),
+ },
+ "search_analytics_by_page_country": {
+ "dimensions": ["date", "page", "country"],
+ "primary_key": ["date", "page", "country"],
+ "should_sync_default": False,
+ "description": (
+ "Daily performance broken out by landing page and country together. One row per page "
+ "per country per day, so it reaches Google's ~50K row/day API sampling cap much sooner "
+ "than the per-page table and long-tail pages drop out first."
+ ),
+ },
+ "search_analytics_by_query_device": {
+ "dimensions": ["date", "query", "device"],
+ "primary_key": ["date", "query", "device"],
+ "should_sync_default": False,
+ "description": (
+ "Daily performance broken out by search query and device together. Roughly three rows "
+ "per query per day, so it hits Google's ~50K row/day API sampling cap about three times "
+ "sooner than the per-query table."
+ ),
+ },
+ "search_analytics_by_query_country": {
+ "dimensions": ["date", "query", "country"],
+ "primary_key": ["date", "query", "country"],
+ "should_sync_default": False,
+ "description": (
+ "Daily performance broken out by search query and country together. The highest "
+ "cardinality table here after query x page: on multi-country sites it can hit Google's "
+ "~50K row/day API sampling cap sooner than query x page does. Above the cap only the "
+ "top rows by clicks are returned and the tail is silently dropped."
+ ),
+ },
# `hour` is the only dimension Google serves outside the 16-month daily window: it
# retains 10 days and requires `dataState: hourly_all`, which mixes complete and
# partial rows. Because Google keeps restating those rows for a few days, every sync
@@ -93,6 +146,7 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {
"history_days": 10,
"end_lag_days": 0,
"ignore_incremental_watermark": True,
+ "web_only": True,
},
"search_analytics_by_query_page": {
"dimensions": ["date", "query", "page"],
@@ -119,10 +173,35 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {
"(e.g. RICH_RESULT, REVIEW_SNIPPET, FAQ_RICH_RESULT, VIDEO, AMP_BLUE_LINK). "
"Useful for measuring the impact of structured data and rich result eligibility."
),
+ "web_only": True,
},
}
+def qualified_schema_name(base_name: str, search_type: str) -> str:
+ """Table name for a schema restricted to `search_type`.
+
+ Web keeps the bare name so sources created before search types existed keep their
+ tables. A single underscore is required: `NamingConvention` collapses runs of
+ underscores, so a `__` separator would make the schema name and the warehouse table
+ name diverge.
+ """
+ return base_name if search_type == DEFAULT_SEARCH_TYPE else f"{base_name}_{search_type}"
+
+
+def split_schema_name(schema_name: str) -> tuple[str, str]:
+ """Inverse of `qualified_schema_name`, as (base name, search type).
+
+ Only splits when the remainder is a known base, so an unrecognized name comes back
+ untouched and the caller's unknown-schema guard still fires.
+ """
+ for search_type in NON_WEB_SEARCH_TYPES:
+ base_name = schema_name.removesuffix(f"_{search_type}")
+ if base_name != schema_name and base_name in SEARCH_ANALYTICS_SCHEMAS:
+ return base_name, search_type
+ return schema_name, DEFAULT_SEARCH_TYPE
+
+
class PropertySchema(TypedDict):
primary_key: list[str]
should_sync_default: bool
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py
index 244bab43a430..4998c2e6678a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py
@@ -10,6 +10,8 @@ from posthog.schema import (
SourceConfig,
SourceFieldOauthAccountSelectConfig,
SourceFieldOauthConfig,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
from posthog.exceptions_capture import capture_exception
@@ -40,9 +42,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea
suggest_registered_site,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (
+ DEFAULT_SEARCH_TYPE,
PROPERTY_SCHEMAS,
SEARCH_ANALYTICS_INCREMENTAL_FIELD,
SEARCH_ANALYTICS_SCHEMAS,
+ SEARCH_TYPES,
+ SearchAnalyticsSchema,
+ qualified_schema_name,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -128,6 +134,33 @@ class GoogleSearchConsoleSource(
for site in sites
]
+ @staticmethod
+ def effective_search_types(config: GoogleSearchConsoleSourceConfig) -> list[str]:
+ """Search types to build tables for, in `SEARCH_TYPES` order.
+
+ Falls back to web when unset, so sources created before this field existed keep
+ exactly the table set they already sync.
+ """
+ selected = set(config.search_types or [])
+ return [t for t in SEARCH_TYPES if t in selected] or [DEFAULT_SEARCH_TYPE]
+
+ @staticmethod
+ def _search_analytics_schema(base_name: str, schema: SearchAnalyticsSchema, search_type: str) -> SourceSchema:
+ is_default_type = search_type == DEFAULT_SEARCH_TYPE
+ description = schema["description"]
+ if not is_default_type and description is not None:
+ description = f"{description} Restricted to {search_type} search results."
+ return SourceSchema(
+ name=qualified_schema_name(base_name, search_type),
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=[SEARCH_ANALYTICS_INCREMENTAL_FIELD],
+ description=description,
+ # Never default-on a non-web table: each one costs a full history backfill,
+ # and picking a search type shouldn't silently start one.
+ should_sync_default=schema["should_sync_default"] and is_default_type,
+ )
+
def get_schemas(
self,
config: GoogleSearchConsoleSourceConfig,
@@ -138,15 +171,10 @@ class GoogleSearchConsoleSource(
api_version: str | None = None,
) -> list[SourceSchema]:
schemas = [
- SourceSchema(
- name=name,
- supports_incremental=True,
- supports_append=True,
- incremental_fields=[SEARCH_ANALYTICS_INCREMENTAL_FIELD],
- description=schema["description"],
- should_sync_default=schema["should_sync_default"],
- )
- for name, schema in SEARCH_ANALYTICS_SCHEMAS.items()
+ self._search_analytics_schema(base_name, schema, search_type)
+ for search_type in self.effective_search_types(config)
+ for base_name, schema in SEARCH_ANALYTICS_SCHEMAS.items()
+ if search_type == DEFAULT_SEARCH_TYPE or not schema.get("web_only")
]
# Property metadata is a full snapshot each sync: both endpoints return the current
# state with no timestamp to filter on, so there is nothing to sync incrementally.
@@ -305,6 +333,25 @@ class GoogleSearchConsoleSource(
),
required=True,
),
+ SourceFieldSelectConfig(
+ name="search_types",
+ label="Search types",
+ required=True,
+ defaultValue=DEFAULT_SEARCH_TYPE,
+ multiple=True,
+ options=[
+ SourceFieldSelectConfigOption(label="Web", value="web"),
+ SourceFieldSelectConfigOption(label="Image", value="image"),
+ SourceFieldSelectConfigOption(label="Video", value="video"),
+ SourceFieldSelectConfigOption(label="News", value="news"),
+ ],
+ caption=(
+ "Which Search Console result types to sync. Web keeps the original table names. "
+ "Every other type adds a copy of each table with the type as a suffix, such as "
+ "search_analytics_by_page_image, and each copy costs a full set of API requests. "
+ "Removing a type later stops its tables syncing, but keeps the data already imported."
+ ),
+ ),
],
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
index 5b40741d69f1..4e63fe647cab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py
@@ -36,6 +36,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea
normalize_site_url,
suggest_registered_site,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (
+ DEFAULT_SEARCH_TYPE,
+ SEARCH_ANALYTICS_SCHEMAS,
+ SEARCH_TYPES,
+ qualified_schema_name,
+ split_schema_name,
+)
TODAY = dt.date(2026, 4, 30)
@@ -242,7 +249,17 @@ def test_source_yields_rows_and_advances_dates(monkeypatch):
queries: list[tuple[str, int]] = []
- def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000, data_state="final"):
+ def fake_query(
+ session,
+ site_url,
+ start_date,
+ end_date,
+ dimensions,
+ start_row,
+ row_limit=25000,
+ data_state="final",
+ search_type="web",
+ ):
queries.append((start_date, start_row))
pages = pages_per_date.get(start_date, [[]])
return pages.pop(0) if pages else []
@@ -282,7 +299,17 @@ def test_source_resumes_from_saved_state(monkeypatch):
fake_today = dt.date(2026, 4, 30)
queries: list[tuple[str, int]] = []
- def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000, data_state="final"):
+ def fake_query(
+ session,
+ site_url,
+ start_date,
+ end_date,
+ dimensions,
+ start_row,
+ row_limit=25000,
+ data_state="final",
+ search_type="web",
+ ):
queries.append((start_date, start_row))
return []
@@ -926,3 +953,108 @@ def test_normalize_site_url(raw, expected):
)
def test_suggest_registered_site(site_url, registered, expected):
assert suggest_registered_site(site_url, registered) == expected
+
+
+ "resource_name,expected_type",
+ [
+ ("search_analytics_by_page", "web"),
+ ("search_analytics_by_page_image", "image"),
+ ("search_analytics_by_page_news", "news"),
+ ],
+)
+def test_query_sends_search_type(monkeypatch, resource_name, expected_type):
+ # Google defaults `type` to web, so an omitted or mis-parsed suffix silently returns
+ # web numbers under an image/news table name.
+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)
+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())
+ monkeypatch.setattr(gsc, "_today", lambda: TODAY)
+
+ session = mock.MagicMock()
+ session.post.return_value = _fake_response(200, {"rows": []})
+ base_name, search_type = split_schema_name(resource_name)
+ _query_search_analytics(
+ session,
+ "sc-domain:example.com",
+ "2026-04-15",
+ "2026-04-15",
+ SEARCH_ANALYTICS_SCHEMAS[base_name]["dimensions"],
+ 0,
+ search_type=search_type,
+ )
+
+ assert session.post.call_args.kwargs["json"]["type"] == expected_type
+
+
+def test_suffixed_schema_queries_base_dimensions_under_suffixed_table_name(monkeypatch):
+ config = GoogleSearchConsoleSourceConfig(
+ site_url="https://example.com/",
+ google_search_console_integration_id=1,
+ )
+ calls: list[dict] = []
+
+ def fake_query(**kwargs):
+ calls.append(kwargs)
+ return [{"keys": ["2026-04-26", "/pricing"], "clicks": 3, "impressions": 9, "ctr": 0.33, "position": 2.0}]
+
+ monkeypatch.setattr(gsc, "_today", lambda: dt.date(2026, 4, 30))
+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())
+ monkeypatch.setattr(gsc, "_query_search_analytics", fake_query)
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ response = google_search_console_source(
+ config=config,
+ resource_name="search_analytics_by_page_image",
+ team_id=1,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=dt.date(2026, 4, 26),
+ )
+ batches = list(response.items()) # type: ignore[arg-type]
+
+ assert response.name == "search_analytics_by_page_image"
+ # The suffix selects the search type; it must not leak into the requested dimensions.
+ assert calls[0]["dimensions"] == ["date", "page"]
+ assert {call["search_type"] for call in calls} == {"image"}
+ assert batches[0][0]["search_type"] == "image"
+ # Constant per table, so adding it to the key would only bloat the merge predicate.
+ assert response.primary_keys == ["date", "page"]
+
+
+ "resource_name",
+ [
+ "not_a_real_schema_image",
+ # `discover` is not an offered search type, so this is not a suffixed name.
+ "search_analytics_by_query_discover",
+ # Hourly data only exists for web search.
+ "search_analytics_by_hour_image",
+ "search_analytics_by_search_appearance_news",
+ ],
+)
+def test_unavailable_schema_names_raise(resource_name):
+ config = GoogleSearchConsoleSourceConfig(
+ site_url="https://example.com/",
+ google_search_console_integration_id=1,
+ )
+ with pytest.raises(ValueError):
+ google_search_console_source(
+ config=config,
+ resource_name=resource_name,
+ team_id=1,
+ resumable_source_manager=mock.MagicMock(),
+ )
+
+
[email protected]("base_name", sorted(SEARCH_ANALYTICS_SCHEMAS))
[email protected]("search_type", SEARCH_TYPES)
+def test_schema_name_round_trips(base_name, search_type):
+ assert split_schema_name(qualified_schema_name(base_name, search_type)) == (base_name, search_type)
+
+
+def test_no_base_schema_name_collides_with_a_search_type_suffix():
+ # A base name ending in `_image` would be silently reinterpreted as the image variant
+ # of a shorter name, quietly querying the wrong dimensions.
+ for base_name in SEARCH_ANALYTICS_SCHEMAS:
+ assert split_schema_name(base_name) == (base_name, DEFAULT_SEARCH_TYPE)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py
index 74c19374e92e..070c7d36a67b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py
@@ -3,6 +3,8 @@ from unittest import mock
import requests
+from posthog.schema import SourceFieldSelectConfig
+
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesearchconsole import (
GoogleSearchConsoleSourceConfig,
)
@@ -10,8 +12,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea
GoogleSearchConsoleResumeConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (
+ DEFAULT_SEARCH_TYPE,
PROPERTY_SCHEMAS,
SEARCH_ANALYTICS_SCHEMAS,
+ SEARCH_TYPES,
+ qualified_schema_name,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.source import (
GoogleSearchConsoleSource,
@@ -19,13 +24,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea
from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType
-def _config() -> GoogleSearchConsoleSourceConfig:
+def _config(search_types: list[str] | None = None) -> GoogleSearchConsoleSourceConfig:
return GoogleSearchConsoleSourceConfig(
site_url="https://example.com/",
google_search_console_integration_id=1,
+ search_types=search_types,
)
+def _all_types_config() -> GoogleSearchConsoleSourceConfig:
+ return _config(list(SEARCH_TYPES))
+
+
+def _expected_names(search_types: list[str]) -> set[str]:
+ return {
+ qualified_schema_name(base_name, search_type)
+ for search_type in search_types
+ for base_name, schema in SEARCH_ANALYTICS_SCHEMAS.items()
+ if search_type == DEFAULT_SEARCH_TYPE or not schema.get("web_only")
+ } | set(PROPERTY_SCHEMAS.keys())
+
+
def test_source_type():
assert GoogleSearchConsoleSource().source_type == ExternalDataSourceType.GOOGLESEARCHCONSOLE
@@ -34,16 +53,23 @@ def test_get_source_config_fields():
cfg = GoogleSearchConsoleSource().get_source_config
field_names = {field.name for field in cfg.fields}
- assert field_names == {"google_search_console_integration_id", "site_url"}
+ assert field_names == {"google_search_console_integration_id", "site_url", "search_types"}
assert cfg.label == "Google Search Console"
assert cfg.featureFlag is None
assert cfg.releaseStatus == "ga"
+ search_types = next(field for field in cfg.fields if field.name == "search_types")
+ assert isinstance(search_types, SourceFieldSelectConfig)
+ # Without `multiple` the form stores a bare string and only one type can ever sync.
+ assert search_types.multiple is True
+ assert search_types.defaultValue == DEFAULT_SEARCH_TYPE
+ assert tuple(option.value for option in search_types.options) == SEARCH_TYPES
+
def test_get_schemas_returns_all_schemas_with_date_incremental():
- schemas = GoogleSearchConsoleSource().get_schemas(_config(), team_id=1)
+ schemas = GoogleSearchConsoleSource().get_schemas(_all_types_config(), team_id=1)
- assert {s.name for s in schemas} == set(SEARCH_ANALYTICS_SCHEMAS.keys()) | set(PROPERTY_SCHEMAS.keys())
+ assert {s.name for s in schemas} == _expected_names(list(SEARCH_TYPES))
for schema in schemas:
if schema.name in PROPERTY_SCHEMAS:
continue
@@ -70,14 +96,57 @@ def test_property_schemas_are_not_incremental(name):
assert schema.incremental_fields == []
-def test_get_schemas_default_on_tables():
- schemas = GoogleSearchConsoleSource().get_schemas(_config(), team_id=1)
+ "config",
+ [
+ pytest.param(_config(), id="unset_defaults_to_web"),
+ pytest.param(_config([]), id="empty_defaults_to_web"),
+ pytest.param(_all_types_config(), id="all_types"),
+ pytest.param(_config(["news", "web"]), id="subset"),
+ ],
+)
+def test_get_schemas_default_on_tables(config):
+ schemas = GoogleSearchConsoleSource().get_schemas(config, team_id=1)
by_default_on = {s.name for s in schemas if s.should_sync_default}
# Search analytics tables are opt-in apart from the most useful one; the property metadata
- # tables are one cheap request each per sync, so they stay on.
+ # tables are one cheap request each per sync, so they stay on. Picking an extra search type
+ # must never switch one on, since each table costs a full history backfill.
assert by_default_on == {"search_analytics_by_query_page", *PROPERTY_SCHEMAS.keys()}
+ "search_types,expected_types",
+ [
+ # A config saved before search types existed must keep exactly its current tables.
+ (None, [DEFAULT_SEARCH_TYPE]),
+ ([], [DEFAULT_SEARCH_TYPE]),
+ (["image", "web"], ["web", "image"]),
+ (["news", "news"], ["news"]),
+ (["discover", "image"], ["image"]),
+ (list(SEARCH_TYPES), list(SEARCH_TYPES)),
+ ],
+)
+def test_effective_search_types(search_types, expected_types):
+ assert GoogleSearchConsoleSource.effective_search_types(_config(search_types)) == expected_types
+
+
+ "search_types",
+ [None, ["web"], ["image"], ["web", "image", "news"], list(SEARCH_TYPES)],
+)
+def test_get_schemas_cross_product_excludes_web_only_tables(search_types):
+ schemas = GoogleSearchConsoleSource().get_schemas(_config(search_types), team_id=1)
+ effective = GoogleSearchConsoleSource.effective_search_types(_config(search_types))
+
+ assert {s.name for s in schemas} == _expected_names(effective)
+ # Hourly and search appearance data only exist for web search.
+ for web_only_name in ("search_analytics_by_hour", "search_analytics_by_search_appearance"):
+ for search_type in effective:
+ if search_type == DEFAULT_SEARCH_TYPE:
+ continue
+ assert qualified_schema_name(web_only_name, search_type) not in {s.name for s in schemas}
+
+
def test_search_appearance_schema_uses_solo_dimension_with_date_in_pk():
# Google's API refuses to group `searchAppearance` with any other dimension,
# so the schema must request it alone — but the warehouse still partitions per
@@ -95,11 +164,15 @@ def test_get_schemas_filters_by_names():
assert {s.name for s in schemas} == {"search_analytics_by_date", "search_analytics_by_query"}
-def test_canonical_descriptions_cover_every_schema():
+ "config",
+ [pytest.param(_config(), id="web_only"), pytest.param(_all_types_config(), id="all_types")],
+)
+def test_canonical_descriptions_cover_every_schema(config):
# A table shipped without a canonical entry silently falls back to LLM-generated
# descriptions, which is what the curated file exists to avoid.
source = GoogleSearchConsoleSource()
- names = {s.name for s in source.get_schemas(_config(), team_id=1)}
+ names = {s.name for s in source.get_schemas(config, team_id=1)}
assert names <= set(source.get_canonical_descriptions().keys())