Currently Available: Need a skilled Software Developer for your next project?
Categories
SEO, GEO and AEO

Querying AI Referrals in GA4 BigQuery

For website traffic in Google Analytics 4 (GA4), BigQuery lets you query the event data that GA4 exports. Some visits from AI assistants include source details, such as the referring site's hostname (the domain in its URL) or a campaign medium. Visits without that evidence cannot be reliably labeled as AI referrals.

First group event rows into sessions, then assign each session to one category so you do not count it as both an AI referral and direct traffic. A session is a visit made up of one or more events. In the standard GA4 export, its key is the combination of user_pseudo_id and the ga_session_id event parameter. The query below uses that key to identify each session, then checks several source fields. It leaves sessions with no source evidence out of the AI category.

Choose fields that describe the session

Start with session_traffic_source_last_click.manual_campaign.source and .medium. These fields give the source and medium that GA4 credits to a session. Google documents these separately from traffic_source.source and .medium, which show the source that first brought the user to the site. Use the session fields to classify visits; use the first-user fields for acquisition questions. See Google’s BigQuery attribution guidance.

Other fields help you investigate or fill gaps:

Field What it tells you How to use it
session_traffic_source_last_click.manual_campaign.campaign_name The session campaign name Check for Google’s documented (ai-assistant) campaign value.
collected_traffic_source.manual_source and .manual_medium Source and medium values collected with an event Use as supporting evidence, then check whether they agree with the session attribution.
event_params['ga_session_id'] The session identifier on an event Pair it with user_pseudo_id to form the session key.
event_params['page_referrer'] The page that referred the current page Check the referrer host on the session’s first page-view event.
event_params['page_location'] The URL of the current page Inspect the landing page and check whether campaign parameters appear in its URL.

GA4 stores event parameters in the repeated event_params field; each event can have several parameters. The query reads each parameter by its key. The export schema describes these event fields and the traffic-source records.

Google’s current default channel rules include an AI Assistant channel. Google documents ai-assistant as the medium and (ai-assistant) as the campaign for matched assistant referrals. The rule covers recognized referrers such as ChatGPT, Gemini, DeepSeek, Copilot, and Grok. Google places AI Overviews and AI Mode under Organic Search instead. Because Google introduced this measurement in May 2026, older exports may not contain the newer values; check the current channel definition and release notes.

Build one row per session

The query first reads selected values from each event row, then groups the rows by user_pseudo_id and ga_session_id. It uses the first page-view event as the landing page and assigns each session to one category. Replace the table path and date range for your property. Use the AI domain list as an initial set, then check source values in your export and update the list for your reporting.

-- Replace the project, dataset, and date range.
WITH event_rows AS (
  SELECT
    user_pseudo_id,
    event_timestamp,
    event_name,
    platform,

    (
      SELECT ep.value.int_value
      FROM UNNEST(event_params) AS ep
      WHERE ep.key = 'ga_session_id'
    ) AS ga_session_id,

    (
      SELECT NULLIF(ep.value.string_value, '')
      FROM UNNEST(event_params) AS ep
      WHERE ep.key = 'page_referrer'
    ) AS page_referrer,

    (
      SELECT NULLIF(ep.value.string_value, '')
      FROM UNNEST(event_params) AS ep
      WHERE ep.key = 'page_location'
    ) AS page_location,

    session_traffic_source_last_click.manual_campaign.source
      AS session_source,
    session_traffic_source_last_click.manual_campaign.medium
      AS session_medium,
    session_traffic_source_last_click.manual_campaign.campaign_name
      AS session_campaign,

    collected_traffic_source.manual_source AS collected_source,
    collected_traffic_source.manual_medium AS collected_medium
  FROM
    <code>your_project.analytics_123456789.events_*
  WHERE
    _TABLE_SUFFIX BETWEEN '20261101' AND '20261114'
    AND platform = 'WEB'
),

valid_events AS (
  SELECT *
  FROM event_rows
  WHERE user_pseudo_id IS NOT NULL
    AND ga_session_id IS NOT NULL
),

session_sources AS (
  SELECT
    user_pseudo_id,
    ga_session_id,

    ARRAY_AGG(
      NULLIF(session_source, '')
      IGNORE NULLS ORDER BY event_timestamp
      LIMIT 1
    )[SAFE_OFFSET(0)] AS session_source,

    ARRAY_AGG(
      NULLIF(session_medium, '')
      IGNORE NULLS ORDER BY event_timestamp
      LIMIT 1
    )[SAFE_OFFSET(0)] AS session_medium,

    ARRAY_AGG(
      NULLIF(session_campaign, '')
      IGNORE NULLS ORDER BY event_timestamp
      LIMIT 1
    )[SAFE_OFFSET(0)] AS session_campaign,

    ARRAY_AGG(
      NULLIF(collected_source, '')
      IGNORE NULLS ORDER BY event_timestamp
      LIMIT 1
    )[SAFE_OFFSET(0)] AS collected_source,

    ARRAY_AGG(
      NULLIF(collected_medium, '')
      IGNORE NULLS ORDER BY event_timestamp
      LIMIT 1
    )[SAFE_OFFSET(0)] AS collected_medium
  FROM valid_events
  GROUP BY user_pseudo_id, ga_session_id
),

landing_pages AS (
  SELECT
    user_pseudo_id,
    ga_session_id,
    page_referrer AS landing_referrer,
    page_location AS landing_page
  FROM valid_events
  WHERE event_name = 'page_view'
  QUALIFY ROW_NUMBER() OVER (
    PARTITION BY user_pseudo_id, ga_session_id
    ORDER BY event_timestamp
  ) = 1
),

session_evidence AS (
  SELECT
    s.*,
    l.landing_referrer,
    l.landing_page,
    LOWER(NET.HOST(l.landing_referrer)) AS referrer_host
  FROM session_sources AS s
  LEFT JOIN landing_pages AS l
    USING (user_pseudo_id, ga_session_id)
),

classified AS (
  SELECT
    *,
    CASE
      WHEN LOWER(COALESCE(session_medium, '')) = 'ai-assistant'
        OR LOWER(COALESCE(session_campaign, '')) = '(ai-assistant)'
        OR REGEXP_CONTAINS(
          LOWER(COALESCE(session_source, '')),
          r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
        )
        OR REGEXP_CONTAINS(
          LOWER(COALESCE(referrer_host, '')),
          r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
        )
        OR REGEXP_CONTAINS(
          LOWER(COALESCE(collected_source, '')),
          r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
        )
        THEN 'AI referral'

      WHEN LOWER(COALESCE(session_source, '')) = '(direct)'
        AND LOWER(COALESCE(session_medium, '')) IN ('(none)', '(not set)')
        THEN 'Direct'

      WHEN (session_source IS NULL OR LOWER(session_source) = '(not set)')
        AND (session_medium IS NULL OR LOWER(session_medium) = '(not set)')
        AND (collected_source IS NULL OR LOWER(collected_source) = '(not set)')
        AND (collected_medium IS NULL OR LOWER(collected_medium) = '(not set)')
        AND landing_referrer IS NULL
        AND (session_campaign IS NULL OR LOWER(session_campaign) = '(not set)')
        THEN 'Unknown / no source evidence'

      ELSE 'Other identifiable source'
    END AS traffic_bucket,

    CASE
      WHEN LOWER(COALESCE(session_medium, '')) = 'ai-assistant'
        OR LOWER(COALESCE(session_campaign, '')) = '(ai-assistant)'
        OR REGEXP_CONTAINS(
          LOWER(COALESCE(session_source, '')),
          r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
        )
        THEN 'Session attribution'

      WHEN REGEXP_CONTAINS(
        LOWER(COALESCE(referrer_host, '')),
        r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
      )
        THEN 'Landing-page referrer'

      WHEN REGEXP_CONTAINS(
        LOWER(COALESCE(collected_source, '')),
        r'(^|\.)(chatgpt\.com|openai\.com|perplexity\.ai|claude\.ai|anthropic\.com|gemini\.google\.com|copilot\.com|copilot\.microsoft\.com|deepseek\.com|grok\.com|you\.com|poe\.com)$'
      )
        THEN 'Collected event source'

      ELSE 'n/a'
    END AS ai_evidence
  FROM session_evidence
)

SELECT
  traffic_bucket,
  ai_evidence,
  COUNT(*) AS sessions
FROM classified
GROUP BY traffic_bucket, ai_evidence
ORDER BY sessions DESC;

classified contains one row per session key, so the final count includes each session once. Counting the raw event rows instead would count a session repeatedly when it contains multiple events. Google documents user_pseudo_id plus ga_session_id as the standard session key in its session-count guidance.

The query excludes event rows without either part of that key. Check how many rows lack user_pseudo_id or ga_session_id before treating the result as a complete session count. Do not assign fabricated keys to those rows; this method cannot deduplicate them reliably.

The query checks session attribution first, then the landing-page referrer, then collected event source. Its evidence label shows which signal matched. Treat Collected event source as a weaker fallback: collected_traffic_source describes data on events, and a value on one event does not automatically describe the whole session. If source values change during visits, compare the fallback against the session-entry event and the session attribution before relying on it.

Interpret direct and unknown traffic carefully

A session belongs in the AI bucket only when a source, medium, campaign, collected source, or landing-page referrer matches an explicit AI rule. The query's domain list does not cover every assistant or hostname. Review the actual source and referrer values in your export, then update the allowlist to fit the property.

GA4’s Direct label means that Analytics has no clear referral source. It does not prove that someone typed the URL. Google lists direct entry and offline documents alongside missing campaign details, redirects, URL shorteners, and ad blockers as reasons source information can be absent. See Google’s explanation of direct traffic. A missing referrer by itself is therefore not evidence of AI discovery.

The query places a session in Unknown / no source evidence when its source, medium, campaign, and landing referrer provide no usable evidence. Keep that bucket separate from both Direct and AI referrals. A rise in unknown sessions cannot establish that AI assistants sent them.

The categories are exclusive: the AI check runs before the Direct check, so a session with an AI signal is counted once as AI referral. If you instead add a separate is_ai_referral yes-or-no field beside channel totals, that field can overlap with those totals. Treat it as a diagnostic subset, not another bucket to add to the channel count.

Finally, BigQuery exports data for individual events, and its results do not always match the Analytics interface, which can include additional reporting values. Google also documents export limits and differences between daily and streaming exports in its BigQuery Export overview. Record the date range and classification rules with your report so readers can interpret the counts against the data and rules used.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *