Marketing Funnel Metrics & Attribution with BigQuery Graph & Measures

1. Introduction

In this codelab, you use BigQuery Graph, BigQuery Measures, and Conversational Analytics to analyze top-of-the-funnel, bottom-of-the-funnel, and unified marketing metrics for an online retailer.

In retail and ecommerce, customer purchase paths are rarely linear. Shoppers move through Paid Search, Paid Social, Video, Organic search, and Email campaigns before they check out. Marketing leaders keep running into the same questions:

  • Which campaigns are truly driving high-margin revenue, and which are burning ad spend?
  • How do different attribution models (First-Touch, Last-Touch, Linear) change the ranking of channels?
  • How can we report campaign budgets next to web touchpoints and order line items without double-counting?

Marketing attribution graph concept

What you'll build

  • A property graph named thelook_graph.eCommerce_Integrated that links campaigns, touchpoints, users, orders, order items, and products, with 10 measures declared directly on its nodes.
  • An executive ROAS scorecard that combines grain-safe budget and spend rollups with 4-hop profit attribution in one query.
  • (Optional) A Conversational Analytics data agent grounded on the graph that business users can query in natural language.

The eCommerce_Integrated graph drawn as a marketing funnel: top-of-funnel nodes and measures, the INFLUENCED attribution edge, and bottom-of-funnel nodes and measures

What you'll learn

Each step is a milestone that you validate before moving on:

  1. Model a property graph in place over BigQuery tables and views, with measures declared on nodes.
  2. Introspect measures through INFORMATION_SCHEMA.PROPERTY_GRAPHS.
  3. Reproduce Cartesian fan-out with a plain SQL join, then roll up top-of-funnel and bottom-of-funnel metrics with GRAPH_EXPAND and AGG() without duplication.
  4. Compare First-Touch, Last-Touch, and Linear attribution with GRAPH_TABLE.
  5. Compute 4-hop gross profit and margin % by traversing from touchpoints to product cost.
  6. Trace a customer's conversion journey with pure ISO GQL.
  7. Fuse both query styles into a single executive ROAS scorecard.
  8. (Optional) Ground a Conversational Analytics agent on the graph and publish it to Gemini Enterprise.

The core problem: grain and Cartesian fan-out

Throughout this codelab, grain means what one row represents. A campaign budget lives at the campaign grain (1 row per campaign). A web click lives at the touchpoint grain (millions of rows). An order line item lives at the order-item grain.

In a relational data warehouse, answering attribution questions means joining tables of very different grains (campaigns ➔ touchpoints ➔ orders ➔ order_items ➔ products). That causes two problems:

  1. Cartesian fan-out (double counting): joining a coarse-grain row (one campaign budget) to fine-grain rows (every click and every line item) repeats the budget on every joined row. A plain SUM() then adds it up millions of times: in this dataset a single $60,000 email budget, joined down to order line items, lands on more than a million rows.
  2. Complex, fragile SQL: multi-hop path analysis needs nested CTEs, window functions, or ANY_VALUE() workarounds that silently break when someone changes the GROUP BY.

How BigQuery Graph and measures solve it

With BigQuery Graph, you declare all of these relationships once as a property graph—a logical layer on top of your existing BigQuery tables and views. No data is copied into a separate graph database. You then query the same graph in two complementary ways:

  • GRAPH_EXPAND + AGG() (standard SQL): pass start_node => "touchpoints" for top-of-funnel metrics or start_node => "order_items" for bottom-of-funnel metrics, and roll up each measure at the grain where it was declared. The syntax is plain SELECT ... GROUP BY, so it works from Looker, Tableau, or any BI tool.
  • GRAPH_TABLE and ISO GQL (graph pattern matching): traverse multiple hops to compare attribution models, connect touchpoints to product cost of goods sold (COGS) for true gross margin, and map individual customer journeys.

BigQuery Measures (MEASURE(...)) embed each business metric—total_campaign_budget, total_ad_spend, total_clicks, unique_reach, total_users, total_orders, gross_revenue, total_items_sold, avg_cost, avg_retail_price—on the node that owns it, so double counting becomes mathematically impossible. Finally, a Conversational Analytics data agent grounded on the graph lets business users ask these questions in natural language.

What you'll need

  • A web browser such as Chrome.
  • A Google Cloud project with billing enabled.
  • IAM roles on that project: BigQuery Admin (roles/bigquery.admin), BigQuery Resource Admin (roles/bigquery.resourceAdmin) to create reservations, and Service Usage Admin (roles/serviceusage.serviceUsageAdmin) to enable APIs. Project Owner covers all three.
  • Cloud Shell (for gcloud and bq commands) and BigQuery Studio (for SQL).
  • Working knowledge of SQL (JOIN, GROUP BY, CTEs). No prior graph-query experience is needed.
  • (Optional, final step only) Access to a Gemini Enterprise application.

This codelab is designed for data analysts, analytics engineers, and developers at an intermediate level.

Estimated duration: about 90 minutes (about 80 minutes if you skip the optional Gemini Enterprise step)
Estimated cost: less than $5 USD. Loading data is free; queries run on a serverless BigQuery Enterprise reservation with 0 baseline slots, and you delete it at the end.

2. Before you begin

Create a Google Cloud project

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
  2. Make sure that billing is enabled for your project.

Start Cloud Shell

You run commands in Google Cloud Shell, which comes with the Google Cloud CLI (gcloud) and the BigQuery CLI (bq) preinstalled.

  1. In the Google Cloud console, click Activate Cloud Shell in the top navigation bar.
  2. Confirm authorization if prompted.

Set up environment variables

In Cloud Shell, set the variables that the rest of the codelab uses:

export PROJECT_ID=$(gcloud config get-value project)
export REGION="US"
export RESERVATION_NAME="graph-enterprise-reservation"

echo "Using project ${PROJECT_ID} in location ${REGION}"

Enable APIs

Enable the BigQuery and BigQuery Reservation APIs. (The optional Conversational Analytics step enables its own APIs later.)

gcloud services enable \
  bigquery.googleapis.com \
  bigqueryreservation.googleapis.com \
  --project=${PROJECT_ID}

Create a BigQuery Enterprise reservation and assignment

According to the BigQuery Graph documentation, GQL queries (GRAPH_TABLE and GRAPH ... MATCH) require a reservation that uses the Enterprise or Enterprise Plus edition, while GRAPH_EXPAND queries can also run with on-demand pricing. Create an autoscaling reservation with 0 baseline slots so that it costs nothing while idle:

# 1. Create an Enterprise reservation (0 baseline slots, autoscale up to 100)
bq mk --reservation \
  --project_id=${PROJECT_ID} \
  --location=${REGION} \
  --edition=ENTERPRISE \
  --slots=0 \
  --autoscale_max_slots=100 \
  --ignore_idle_slots=true \
  ${RESERVATION_NAME}

# 2. Assign your project's queries to the reservation
bq mk --reservation_assignment \
  --project_id=${PROJECT_ID} \
  --location=${REGION} \
  --reservation_id=${RESERVATION_NAME} \
  --job_type=QUERY \
  --assignee_type=PROJECT \
  --assignee_id=${PROJECT_ID}

Validate the reservation

Confirm that the assignment exists before you run any graph queries. If it is missing, GQL queries later in the codelab fail with an edition error.

bq ls --reservation_assignment \
  --project_id=${PROJECT_ID} \
  --location=${REGION}

Expected output (your assignment ID is a different number):

                               name                                 jobType           assignee
 ------------------------------------------------------------------ --------- --------------------------
  PROJECT_ID:US.graph-enterprise-reservation.7664235470433641991     QUERY     projects/PROJECT_ID

3. Create the dataset and load the sample data

In this step, you create the thelook_graph dataset and load the five base tables of the thelook_ecommerce snapshot from the public bucket gs://sample-data-and-media/thelook_dataset_snapshot/.

Table

Rows

What one row represents (grain)

users

100,000

A registered shopper, with demographics and acquisition traffic_source

orders

125,270

A checkout transaction, with status and num_of_item

order_items

181,271

One purchased line item, with sale_price

products

29,120

A catalog product, with department, category, brand, cost, and retail_price

events

2,423,365

One web interaction (home, department, product, cart, purchase) with traffic_source

Open BigQuery Studio, paste the following into a query editor, and click Run:

-- 1. Create the dataset
CREATE SCHEMA IF NOT EXISTS `thelook_graph`
OPTIONS (
  location = 'US',
  description = 'Marketing attribution and ROAS graph over the thelook_ecommerce snapshot'
);

-- 2. Users (100,000 rows)
LOAD DATA OVERWRITE `thelook_graph.users`
FROM FILES (
  format = 'AVRO',
  uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/users/*.avro.gz'],
  enable_logical_types = true
);

-- 3. Orders (125,270 rows)
LOAD DATA OVERWRITE `thelook_graph.orders`
FROM FILES (
  format = 'AVRO',
  uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/orders/*.avro.gz'],
  enable_logical_types = true
);

-- 4. Order items (181,271 rows)
LOAD DATA OVERWRITE `thelook_graph.order_items`
FROM FILES (
  format = 'AVRO',
  uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/order_items/*.avro.gz'],
  enable_logical_types = true
);

-- 5. Products (29,120 rows)
LOAD DATA OVERWRITE `thelook_graph.products`
FROM FILES (
  format = 'AVRO',
  uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/products/*.avro.gz'],
  enable_logical_types = true
);

-- 6. Web events (2,423,365 rows)
LOAD DATA OVERWRITE `thelook_graph.events`
FROM FILES (
  format = 'AVRO',
  uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/events/*.avro.gz'],
  enable_logical_types = true
);

Method B: Load with bq in Cloud Shell

Alternatively, run the following in Cloud Shell:

bq --location=${REGION} mk --dataset \
  --description "Marketing attribution and ROAS graph" \
  ${PROJECT_ID}:thelook_graph

for table in users orders order_items products events; do
  bq load --replace --source_format=AVRO --use_avro_logical_types \
    ${PROJECT_ID}:thelook_graph.${table} \
    "gs://sample-data-and-media/thelook_dataset_snapshot/${table}/*.avro.gz"
done

Validate the load

Run this query in BigQuery Studio and compare the row counts:

SELECT table_id, row_count
FROM `thelook_graph.__TABLES__`
ORDER BY table_id;

Expected output:

table_id

row_count

events

2,423,365

order_items

181,271

orders

125,270

products

29,120

users

100,000

If events shows fewer rows, a load job is still running; wait a minute and rerun the query.

4. Build the marketing views and attribution edges

The thelook_ecommerce dataset has shoppers, orders, and web events, but no marketing campaign data. In this step, you add three objects to thelook_graph that turn it into a marketing-attribution dataset:

Entity diagram of the eCommerce_Integrated graph: users, touchpoints, campaigns, orders, order_items, and products linked by the ENGAGED_WITH, GENERATED_BY, INFLUENCED, BELONGS_TO, and IS_PRODUCT edges. Blue tables are loaded from the snapshot; the green views and the amber edge table are created in this step

  • marketing_campaigns (view): 8 Q4 campaigns across 5 channels, with budgets and target ROAS.
  • touchpoints (view): the 2,423,365 web events, each tagged with a campaign, a channel, and a benchmark cost per click (CPC).
  • edge_influenced (table): which touchpoints influenced which orders, with First-Touch, Last-Touch, and Linear attribution weights.

2a. The campaign reference view

Campaign budgets are upstream, coarse-grain data: one row per campaign. The following view defines 8 campaigns with realistic Q4 budgets.

CREATE OR REPLACE VIEW `thelook_graph.marketing_campaigns` AS
SELECT 'Paid Search' AS channel, 'Q4_Search_Generic_Audio' AS campaign_name, 1500000.0 AS total_budget, 4.0 AS target_roas UNION ALL
SELECT 'Paid Search', 'Q4_Search_Brand_Electronics', 1100000.0, 5.0 UNION ALL
SELECT 'Paid Social', 'Q4_Meta_IG_Retargeting', 250000.0, 4.5 UNION ALL
SELECT 'Video', 'Q4_YouTube_Video_Awareness', 220000.0, 2.5 UNION ALL
SELECT 'Paid Social', 'Q4_TikTok_Prospecting_GenZ', 150000.0, 3.0 UNION ALL
SELECT 'Email Marketing', 'Q4_Email_Cart_Abandonment', 75000.0, 10.0 UNION ALL
SELECT 'Email Marketing', 'Q4_Email_VIP_Weekly_Drop', 60000.0, 8.0 UNION ALL
SELECT 'Organic', 'Organic_Search_SEO', 25000.0, 15.0;

2b. The touchpoints view

Every web event already records a traffic_source (Adwords, Facebook, YouTube, Email, or Organic). The view maps each source to a marketing channel, splits each paid source into two campaigns by using MOD(e.id, 2) (even event IDs go to one campaign, odd IDs to the other), and assigns an industry-benchmark CPC:

traffic_source

Channel

Campaigns (even / odd event ID)

CPC

Adwords

Paid Search

Q4_Search_Generic_Audio / Q4_Search_Brand_Electronics

$3.78 / $2.64

Facebook

Paid Social

Q4_Meta_IG_Retargeting / Q4_TikTok_Prospecting_GenZ

$1.85 / $0.99

YouTube

Video

Q4_YouTube_Video_Awareness

$0.85

Email

Email Marketing

Q4_Email_Cart_Abandonment / Q4_Email_VIP_Weekly_Drop

$0.12 / $0.10

Organic

Organic

Organic_Search_SEO

$0.00

This is a view, so no data is duplicated; the 2.4 million events are tagged at query time.

CREATE OR REPLACE VIEW `thelook_graph.touchpoints` AS
SELECT
  e.id AS touchpoint_id,
  e.user_id,
  e.session_id,
  e.created_at,
  e.event_type,
  e.browser,
  e.traffic_source,
  CASE
    WHEN e.traffic_source = 'Adwords' AND MOD(e.id, 2) = 0 THEN 'Q4_Search_Generic_Audio'
    WHEN e.traffic_source = 'Adwords' THEN 'Q4_Search_Brand_Electronics'
    WHEN e.traffic_source = 'Facebook' AND MOD(e.id, 2) = 0 THEN 'Q4_Meta_IG_Retargeting'
    WHEN e.traffic_source = 'Facebook' THEN 'Q4_TikTok_Prospecting_GenZ'
    WHEN e.traffic_source = 'YouTube' THEN 'Q4_YouTube_Video_Awareness'
    WHEN e.traffic_source = 'Email' AND MOD(e.id, 2) = 0 THEN 'Q4_Email_Cart_Abandonment'
    WHEN e.traffic_source = 'Email' THEN 'Q4_Email_VIP_Weekly_Drop'
    ELSE 'Organic_Search_SEO'
  END AS campaign_name,
  CASE
    WHEN e.traffic_source = 'Adwords' THEN 'Paid Search'
    WHEN e.traffic_source = 'Facebook' THEN 'Paid Social'
    WHEN e.traffic_source = 'YouTube' THEN 'Video'
    WHEN e.traffic_source = 'Email' THEN 'Email Marketing'
    ELSE 'Organic'
  END AS channel,
  CASE
    WHEN e.traffic_source = 'Adwords' AND MOD(e.id, 2) = 0 THEN 3.78
    WHEN e.traffic_source = 'Adwords' THEN 2.64
    WHEN e.traffic_source = 'Facebook' AND MOD(e.id, 2) = 0 THEN 1.85
    WHEN e.traffic_source = 'Facebook' THEN 0.99
    WHEN e.traffic_source = 'YouTube' THEN 0.85
    WHEN e.traffic_source = 'Email' AND MOD(e.id, 2) = 0 THEN 0.12
    WHEN e.traffic_source = 'Email' THEN 0.10
    ELSE 0.00
  END AS cpc_cost
FROM `thelook_graph.events` e;

2c. The attribution edge table

edge_influenced connects touchpoints to the orders they influenced. It follows four rules:

  • A touchpoint influences an order if the same user made it within the 30 days before the order (created_at between order time - 30 days and order time).
  • Orders with status Cancelled or Returned are excluded.
  • Touchpoints are ranked by time within each order (touchpoint_rank); the event ID breaks ties so that the ranking is deterministic.
  • Three attribution weights are precomputed per touchpoint:
    • first_touch_weight = 1.0 for the earliest touchpoint, otherwise 0.0
    • last_touch_weight = 1.0 for the latest touchpoint, otherwise 0.0
    • linear_weight = 1 / (number of touchpoints), so the weights for each order add up to 1.0

For example, an order with three touchpoints gets these weights:

touchpoint_rank

first_touch_weight

last_touch_weight

linear_weight

1

1.0

0.0

0.333333

2

0.0

0.0

0.333333

3

0.0

1.0

0.333333

Because each order's weights sum to 1.0 under every model, multiplying a line item's sale_price by a weight and summing never double-counts revenue.

CREATE OR REPLACE TABLE `thelook_graph.edge_influenced` AS
WITH ranked_touchpoints AS (
  SELECT
    t.touchpoint_id,
    o.order_id,
    t.campaign_name,
    t.channel,
    t.cpc_cost,
    t.created_at AS event_timestamp,
    o.created_at AS order_timestamp,
    ROW_NUMBER() OVER (PARTITION BY o.order_id ORDER BY t.created_at ASC, t.touchpoint_id ASC) AS touchpoint_asc,
    ROW_NUMBER() OVER (PARTITION BY o.order_id ORDER BY t.created_at DESC, t.touchpoint_id DESC) AS touchpoint_desc,
    COUNT(*) OVER (PARTITION BY o.order_id) AS total_touchpoints
  FROM `thelook_graph.orders` o
  JOIN `thelook_graph.touchpoints` t
    ON o.user_id = t.user_id
   AND t.created_at <= o.created_at
   AND t.created_at >= TIMESTAMP_SUB(o.created_at, INTERVAL 30 DAY)
  WHERE o.status NOT IN ('Cancelled', 'Returned')
)
SELECT
  touchpoint_id,
  order_id,
  campaign_name,
  channel,
  cpc_cost,
  touchpoint_asc AS touchpoint_rank,
  total_touchpoints,
  ROUND(TIMESTAMP_DIFF(order_timestamp, event_timestamp, HOUR) / 24.0, 1) AS days_to_convert,
  IF(touchpoint_asc = 1, 1.0, 0.0) AS first_touch_weight,
  IF(touchpoint_desc = 1, 1.0, 0.0) AS last_touch_weight,
  ROUND(1.0 / total_touchpoints, 6) AS linear_weight
FROM ranked_touchpoints;

Validate the attribution edges

SELECT COUNT(*) AS attribution_edges
FROM `thelook_graph.edge_influenced`;

Expected output: 976,555. If you get a different number, confirm that created_at loaded as TIMESTAMP (rerun the load with the logical-type flag) and that all five tables have the expected row counts.

5. Declare the property graph with measures

Anatomy of a property graph

Clause

What it does

NODE TABLES (...)

Lists the tables or views that become nodes (entities).

KEY (col)

The column that uniquely identifies a node. Measures are deduplicated by this key.

LABEL name PROPERTIES (...)

Gives the node a label used in queries ((c:campaigns)) and lists the columns exposed as properties.

MEASURE(expr) AS name

Declares an aggregation that belongs to this node. AGG(name) later evaluates it once per distinct key, no matter how many rows a join produces.

EDGE TABLES (...)

Lists the tables whose rows become edges (relationships). The same table can appear as a node and as an edge.

SOURCE KEY ... REFERENCES node / DESTINATION KEY ... REFERENCES node

Define which node an edge starts from and points to. NO PROPERTIES means the edge carries no attributes of its own.

Here is one node and one edge from the graph you are about to create, annotated:

-- A node: one row per campaign, keyed by campaign_name
`thelook_graph.marketing_campaigns` AS campaigns
  KEY (campaign_name)                              -- unique key => AGG() dedupes on it
  LABEL campaigns PROPERTIES (
    campaign_name, channel, total_budget, target_roas,
    MEASURE(SUM(total_budget)) AS total_campaign_budget   -- a measure owned by this node
  ),

-- An edge: each touchpoint row points to the campaign that generated it
`thelook_graph.touchpoints` AS touchpoint_campaign
  KEY (touchpoint_id)
  SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)   -- from a touchpoint...
  DESTINATION KEY (campaign_name) REFERENCES campaigns (campaign_name) -- ...to its campaign
  LABEL GENERATED_BY NO PROPERTIES

Create eCommerce_Integrated

Run the complete statement in BigQuery Studio. It declares 6 node tables with 10 measures and 5 edge tables:

CREATE OR REPLACE PROPERTY GRAPH `thelook_graph.eCommerce_Integrated`
NODE TABLES (
  -- 1. Marketing campaigns (upstream, coarse grain)
  `thelook_graph.marketing_campaigns` AS campaigns
    KEY (campaign_name)
    LABEL campaigns PROPERTIES (
      campaign_name,
      channel,
      total_budget,
      target_roas,
      MEASURE(SUM(total_budget)) AS total_campaign_budget
    ),

  -- 2. Marketing touchpoints (web events tagged with campaigns)
  `thelook_graph.touchpoints` AS touchpoints
    KEY (touchpoint_id)
    LABEL touchpoints PROPERTIES (
      touchpoint_id,
      user_id,
      session_id,
      campaign_name,
      channel,
      cpc_cost,
      event_type,
      browser,
      created_at,
      MEASURE(SUM(cpc_cost)) AS total_ad_spend,
      MEASURE(COUNT(touchpoint_id)) AS total_clicks,
      MEASURE(COUNT(DISTINCT user_id)) AS unique_reach
    ),

  -- 3. Users
  `thelook_graph.users` AS users
    KEY (id)
    LABEL users PROPERTIES (
      id,
      first_name,
      last_name,
      email,
      age,
      gender,
      country,
      traffic_source,
      created_at,
      MEASURE(COUNT(DISTINCT id)) AS total_users
    ),

  -- 4. Orders
  `thelook_graph.orders` AS orders
    KEY (order_id)
    LABEL orders PROPERTIES (
      order_id,
      user_id,
      status,
      created_at,
      num_of_item,
      MEASURE(COUNT(order_id)) AS total_orders
    ),

  -- 5. Order items (the finest financial grain)
  `thelook_graph.order_items` AS order_items
    KEY (id)
    LABEL order_items PROPERTIES (
      id,
      order_id,
      user_id,
      product_id,
      sale_price,
      status,
      created_at,
      MEASURE(SUM(sale_price)) AS gross_revenue,
      MEASURE(COUNT(id)) AS total_items_sold
    ),

  -- 6. Product catalog
  `thelook_graph.products` AS products
    KEY (id)
    LABEL products PROPERTIES (
      id,
      cost,
      category,
      name,
      brand,
      retail_price,
      department,
      MEASURE(AVG(cost)) AS avg_cost,
      MEASURE(AVG(retail_price)) AS avg_retail_price
    )
)
EDGE TABLES (
  -- Touchpoint -> Campaign
  `thelook_graph.touchpoints` AS touchpoint_campaign
    KEY (touchpoint_id)
    SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
    DESTINATION KEY (campaign_name) REFERENCES campaigns (campaign_name)
    LABEL GENERATED_BY NO PROPERTIES,

  -- User -> Touchpoint
  `thelook_graph.touchpoints` AS user_touchpoint
    KEY (touchpoint_id)
    SOURCE KEY (user_id) REFERENCES users (id)
    DESTINATION KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
    LABEL ENGAGED_WITH NO PROPERTIES,

  -- Touchpoint -> Order, carrying the attribution weights
  `thelook_graph.edge_influenced` AS edge_influenced
    KEY (touchpoint_id, order_id)
    SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
    DESTINATION KEY (order_id) REFERENCES orders (order_id)
    LABEL INFLUENCED PROPERTIES (
      campaign_name,
      channel,
      cpc_cost,
      touchpoint_rank,
      total_touchpoints,
      days_to_convert,
      first_touch_weight,
      last_touch_weight,
      linear_weight
    ),

  -- Order item -> Order
  `thelook_graph.order_items` AS item_order
    KEY (id)
    SOURCE KEY (id) REFERENCES order_items (id)
    DESTINATION KEY (order_id) REFERENCES orders (order_id)
    LABEL BELONGS_TO NO PROPERTIES,

  -- Order item -> Product
  `thelook_graph.order_items` AS item_product
    KEY (id)
    SOURCE KEY (id) REFERENCES order_items (id)
    DESTINATION KEY (product_id) REFERENCES products (id)
    LABEL IS_PRODUCT NO PROPERTIES
);

The 10 measures, each declared at the grain that owns it:

  • campaigns: total_campaign_budget
  • touchpoints: total_ad_spend, total_clicks, unique_reach
  • users: total_users
  • orders: total_orders
  • order_items: gross_revenue, total_items_sold
  • products: avg_cost, avg_retail_price

Structural edges (GENERATED_BY, ENGAGED_WITH, BELONGS_TO, IS_PRODUCT) use NO PROPERTIES. Only INFLUENCED carries attributes, because attribution weights are a property of the touchpoint-order relationship, not of either node.

Validate the graph

SELECT property_graph_name
FROM `thelook_graph.INFORMATION_SCHEMA.PROPERTY_GRAPHS`;

Expected output: one row, eCommerce_Integrated. If the CREATE statement failed, the most common cause is a missing table or view from the previous two steps.

6. Introspect the measures with INFORMATION_SCHEMA

INFORMATION_SCHEMA.PROPERTY_GRAPHS exposes the graph definition as JSON in the property_graph_metadata_json column. Its nodeTables array contains each node, and each node's labelAndProperties[0].properties array lists the properties, with expressionKind = "MEASURE" marking the measures. The following query unnests that structure:

SELECT
  JSON_VALUE(node_table_json, "$.name") AS node_table_name,
  JSON_VALUE(prop_json, "$.name") AS measure_name,
  JSON_VALUE(prop_json, "$.expression") AS measure_expression,
  CONCAT("MEASURE<", JSON_VALUE(prop_json, "$.dataType.typeKind"), ">") AS measure_type
FROM `thelook_graph.INFORMATION_SCHEMA.PROPERTY_GRAPHS`,
UNNEST(JSON_EXTRACT_ARRAY(property_graph_metadata_json, "$.nodeTables")) AS node_table_json,
UNNEST(JSON_EXTRACT_ARRAY(node_table_json, "$.labelAndProperties[0].properties")) AS prop_json
WHERE JSON_VALUE(prop_json, "$.expressionKind") = "MEASURE"
ORDER BY node_table_name, measure_name;

Expected output (10 rows):

node_table_name

measure_name

measure_expression

measure_type

campaigns

total_campaign_budget

SUM(total_budget)

MEASURE

order_items

gross_revenue

SUM(sale_price)

MEASURE

order_items

total_items_sold

COUNT(id)

MEASURE

orders

total_orders

COUNT(order_id)

MEASURE

products

avg_cost

AVG(cost)

MEASURE

products

avg_retail_price

AVG(retail_price)

MEASURE

touchpoints

total_ad_spend

SUM(cpc_cost)

MEASURE

touchpoints

total_clicks

COUNT(touchpoint_id)

MEASURE

touchpoints

unique_reach

COUNT(DISTINCT user_id)

MEASURE

users

total_users

COUNT(DISTINCT id)

MEASURE

See the measures in BigQuery Studio

  1. In BigQuery Studio, open the Explorer panel.
  2. Expand your project, then the dataset thelook_graph, then Graphs.
  3. Click eCommerce_Integrated and open the List tab.
  4. Expand touchpoints. The physical columns (touchpoint_id, campaign_name, cpc_cost, ...) are listed as DIMENSION, followed by total_ad_spend, total_clicks, and unique_reach, marked MEASURE and shown with their inferred types. Expand edge_influenced to see the three attribution weights carried by the INFLUENCED edge.The List tab of the eCommerce_Integrated graph in BigQuery Studio with the touchpoints node expanded: total_ad_spend, total_clicks, and unique_reach are marked MEASURE

7. See the problem: fan-out in a plain SQL join

Before you query the graph, reproduce the problem that measures solve. The top-of-funnel question is simple—for each campaign, what are the budget, clicks, and ad spend?—but its inputs live at two grains: budget on marketing_campaigns (1 row per campaign), clicks and spend on touchpoints (2.4 million rows). Answer it the way most warehouses do today, with a join:

SELECT
  c.channel,
  c.campaign_name,
  SUM(c.total_budget) AS total_budget,          -- wrong: repeated per touchpoint
  COUNT(t.touchpoint_id) AS total_clicks,       -- right: touchpoint grain
  ROUND(SUM(t.cpc_cost), 2) AS total_ad_spend   -- right: touchpoint grain
FROM `thelook_graph.marketing_campaigns` c
JOIN `thelook_graph.touchpoints` t
  ON t.campaign_name = c.campaign_name
GROUP BY c.channel, c.campaign_name
ORDER BY total_ad_spend DESC;

Expected output:

channel

campaign_name

total_budget

total_clicks

total_ad_spend

Paid Search

Q4_Search_Generic_Audio

$545,517,000,000

363,678

$1,374,702.84

Paid Search

Q4_Search_Brand_Electronics

$400,045,800,000

363,678

$960,109.92

Paid Social

Q4_Meta_IG_Retargeting

$30,387,750,000

121,551

$224,869.35

Video

Q4_YouTube_Video_Awareness

$53,192,700,000

241,785

$205,517.25

Paid Social

Q4_TikTok_Prospecting_GenZ

$18,278,700,000

121,858

$120,639.42

Email Marketing

Q4_Email_Cart_Abandonment

$40,838,925,000

544,519

$65,342.28

Email Marketing

Q4_Email_VIP_Weekly_Drop

$32,677,800,000

544,630

$54,463.00

Organic

Organic_Search_SEO

$3,041,650,000

121,666

$0.00

Why two of the three columns are still right

total_clicks and total_ad_spend are correct because touchpoint_id and cpc_cost live at the grain of the rows being summed: one value per touchpoint, one touchpoint per row. total_budget is a campaign-grain value stamped onto every touchpoint row, so the join turns one number into hundreds of thousands of copies. This is Cartesian fan-out, and it compounds with every hop: extend the join to orders and order items and the same $60,000 lands on more than a million rows.

Why the usual workarounds don't hold

  • ANY_VALUE(c.total_budget) picks one copy, but only works while the GROUP BY stays at the campaign grain. Group by channel instead and it silently keeps one campaign's budget and drops the rest.
  • A separate CTE per grain is correct, but every new metric needs its own CTE and join, and nothing stops a later edit from aggregating across the wrong one.
  • SUM(DISTINCT c.total_budget) is wrong as soon as two campaigns share a budget.

Measures remove the problem at the source: the budget aggregation is declared once on the campaigns node, and BigQuery evaluates it at that grain no matter what else the query joins to. Keep the $32,677,800,000 figure in mind; in the next step you run the same scorecard through the graph.

8. Use Case 1: Top-of-funnel and bottom-of-funnel rollups (GRAPH_EXPAND)

How GRAPH_EXPAND works

  • GRAPH_EXPAND("graph", start_node => "touchpoints") returns one row per touchpoints node, joined to the nodes it connects to—here campaigns (through GENERATED_BY) and users (through ENGAGED_WITH).
  • Every property and measure is exposed as a column named _, such as campaigns_channel, campaigns_total_campaign_budget, and touchpoints_total_clicks.
  • AGG() evaluates the measure once per distinct node key within each group. AGG(campaigns_total_campaign_budget) therefore sums each campaign's budget once, even though the campaign row is repeated across 363,678 touchpoint rows.
  • Everything else is standard SQL (GROUP BY, ORDER BY, ROUND), so BI tools can issue these queries directly.

Query 1A: Top-of-funnel marketing scorecard

In the previous step, a plain join inflated every campaign's budget by its click count. Now answer the same question through the graph. Structurally, GRAPH_EXPAND replaces the join in the FROM clause and AGG() replaces SUM() and COUNT():

SELECT
  campaigns_channel AS channel,
  campaigns_campaign_name AS campaign_name,
  AGG(campaigns_total_campaign_budget) AS total_budget,
  AGG(touchpoints_total_clicks) AS total_clicks,
  AGG(touchpoints_unique_reach) AS unique_reach,
  ROUND(AGG(touchpoints_total_ad_spend), 2) AS total_ad_spend,
  ROUND(AGG(campaigns_total_campaign_budget) - AGG(touchpoints_total_ad_spend), 2) AS remaining_budget,
  ROUND(AGG(touchpoints_total_ad_spend) / NULLIF(AGG(touchpoints_total_clicks), 0), 2) AS effective_avg_cpc
FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "touchpoints")
GROUP BY channel, campaign_name
ORDER BY total_ad_spend DESC;

Expected output:

channel

campaign_name

total_budget

total_clicks

unique_reach

total_ad_spend

remaining_budget

effective_avg_cpc

Paid Search

Q4_Search_Generic_Audio

$1,500,000

363,678

39,695

$1,374,702.84

$125,297.16

$3.78

Paid Search

Q4_Search_Brand_Electronics

$1,100,000

363,678

39,695

$960,109.92

$139,890.08

$2.64

Paid Social

Q4_Meta_IG_Retargeting

$250,000

121,551

16,182

$224,869.35

$25,130.65

$1.85

Video

Q4_YouTube_Video_Awareness

$220,000

241,785

16,161

$205,517.25

$14,482.75

$0.85

Paid Social

Q4_TikTok_Prospecting_GenZ

$150,000

121,858

16,182

$120,639.42

$29,360.58

$0.99

Email Marketing

Q4_Email_Cart_Abandonment

$75,000

544,519

52,049

$65,342.28

$9,657.72

$0.12

Email Marketing

Q4_Email_VIP_Weekly_Drop

$60,000

544,630

52,049

$54,463.00

$5,537.00

$0.10

Organic

Organic_Search_SEO

$25,000

121,666

8,618

$0.00

$25,000.00

$0.00

Check: total_budget for Q4_Email_VIP_Weekly_Drop is $60,000, not the $32,677,800,000 the plain join produced. AGG() counted the campaign's budget once, even though the campaign row is still repeated across every one of its touchpoints, while total_clicks still counts all 544,630 of them.

Query 1B: Bottom-of-funnel merchandising rollup

Pass start_node => "order_items" on the same graph to expand toward orders (BELONGS_TO) and products (IS_PRODUCT):

SELECT
  products_department AS department,
  products_category AS category,
  AGG(orders_total_orders) AS distinct_orders,
  AGG(order_items_total_items_sold) AS items_sold,
  ROUND(AGG(order_items_gross_revenue), 2) AS gross_revenue,
  ROUND(AGG(products_avg_cost), 2) AS avg_unit_cost,
  ROUND(AGG(products_avg_retail_price), 2) AS avg_retail_price
FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "order_items")
GROUP BY department, category
ORDER BY gross_revenue DESC
LIMIT 5;

Expected output:

department

category

distinct_orders

items_sold

gross_revenue

avg_unit_cost

avg_retail_price

Men

Outerwear & Coats

5,564

5,713

$852,464.61

$65.94

$149.40

Men

Jeans

7,370

7,679

$779,004.17

$53.80

$101.16

Men

Suits & Sport Coats

4,926

5,041

$642,783.10

$50.74

$126.37

Men

Sweaters

6,660

6,869

$528,344.51

$38.83

$77.59

Women

Outerwear & Coats

3,258

3,323

$470,456.28

$63.74

$141.55

Check: for Men's Outerwear & Coats, distinct_orders (5,564) is smaller than items_sold (5,713). AGG(orders_total_orders) deduplicated multi-item baskets by order_id, while AGG(order_items_total_items_sold) counted every line item.

9. Use Case 2: Multi-touch attribution comparison (GRAPH_TABLE)

Reading a GQL pattern

GRAPH_TABLE embeds a graph pattern in a SQL FROM clause. The pattern in this query is:

(t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)
  • (t:touchpoints) matches a node with label touchpoints and binds it to the variable t.
  • -[i:INFLUENCED]-> follows an INFLUENCED edge in its declared direction (touchpoint ➔ order) and binds the edge to i, so you can read i.linear_weight.
  • (o:orders) is the influenced order.
  • <-[:BELONGS_TO]-(oi:order_items) matches BELONGS_TO edges that point into the order (the arrow points left): each line item oi belongs to order o. The edge gets no variable because you don't need any of its properties.
  • COLUMNS (...) projects node and edge properties into ordinary columns, after which SUM and GROUP BY work as usual.

Query

SELECT
  campaign_name,
  channel,
  ROUND(SUM(sale_price * first_touch_weight), 2) AS first_touch_revenue,
  ROUND(SUM(sale_price * last_touch_weight), 2) AS last_touch_revenue,
  ROUND(SUM(sale_price * linear_weight), 2) AS linear_revenue
FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
  MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)
  COLUMNS (
    t.campaign_name AS campaign_name,
    t.channel AS channel,
    oi.sale_price,
    i.first_touch_weight,
    i.last_touch_weight,
    i.linear_weight
  )
)
GROUP BY campaign_name, channel
ORDER BY linear_revenue DESC;

Expected output:

campaign_name

channel

first_touch_revenue

last_touch_revenue

linear_revenue

Q4_Email_VIP_Weekly_Drop

Email Marketing

$1,844,969.34

$1,852,985.64

$1,836,711.27

Q4_Email_Cart_Abandonment

Email Marketing

$1,846,318.54

$1,818,126.95

$1,836,242.50

Q4_Search_Generic_Audio

Paid Search

$1,203,174.40

$1,203,055.84

$1,208,564.90

Q4_Search_Brand_Electronics

Paid Search

$1,204,866.84

$1,204,632.74

$1,207,724.05

Q4_YouTube_Video_Awareness

Video

$809,437.33

$821,840.02

$814,035.10

Organic_Search_SEO

Organic

$409,598.88

$420,458.99

$412,996.24

Q4_TikTok_Prospecting_GenZ

Paid Social

$410,900.27

$401,289.08

$407,354.92

Q4_Meta_IG_Retargeting

Paid Social

$398,192.90

$405,069.24

$403,816.94

Check: add up the linear_revenue column (or remove the GROUP BY). The total is $8,127,445.92 under every model, because each order's weights sum to 1.0—revenue is redistributed between campaigns, never created or lost.

What the numbers say

  • Email nurturing leads in every model. The two email campaigns each attribute about $1.84 million.
  • Prospecting versus closing. Q4_TikTok_Prospecting_GenZ earns more credit under First-Touch ($410,900.27) than Last-Touch ($401,289.08), consistent with a top-of-funnel role. Q4_Meta_IG_Retargeting ($405,069.24) and Q4_YouTube_Video_Awareness ($821,840.02) gain under Last-Touch, consistent with closing roles.

10. Use Case 3: 4-hop profitability and gross margin % (GRAPH_TABLE)

Query

The pattern adds -[:IS_PRODUCT]->(p:products) to reach each line item's catalog cost:

SELECT
  campaign_name,
  channel,
  ROUND(SUM(sale_price * linear_weight), 2) AS attributed_revenue,
  ROUND(SUM(cost * linear_weight), 2) AS attributed_cogs,
  ROUND(SUM((sale_price - cost) * linear_weight), 2) AS gross_profit,
  ROUND(SAFE_DIVIDE(SUM((sale_price - cost) * linear_weight), SUM(sale_price * linear_weight)) * 100, 2) AS gross_margin_pct
FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
  MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
  COLUMNS (
    t.campaign_name AS campaign_name,
    t.channel AS channel,
    oi.sale_price,
    p.cost,
    i.linear_weight
  )
)
GROUP BY campaign_name, channel
ORDER BY gross_profit DESC;

Expected output:

campaign_name

channel

attributed_revenue

attributed_cogs

gross_profit

gross_margin_pct

Q4_Email_VIP_Weekly_Drop

Email Marketing

$1,836,711.27

$883,586.30

$953,124.97

51.89%

Q4_Email_Cart_Abandonment

Email Marketing

$1,836,242.50

$883,678.75

$952,563.75

51.88%

Q4_Search_Generic_Audio

Paid Search

$1,208,564.90

$581,095.89

$627,469.01

51.92%

Q4_Search_Brand_Electronics

Paid Search

$1,207,724.05

$580,774.28

$626,949.77

51.91%

Q4_YouTube_Video_Awareness

Video

$814,035.10

$391,917.60

$422,117.50

51.85%

Organic_Search_SEO

Organic

$412,996.24

$199,002.75

$213,993.48

51.81%

Q4_TikTok_Prospecting_GenZ

Paid Social

$407,354.92

$195,816.75

$211,538.17

51.93%

Q4_Meta_IG_Retargeting

Paid Social

$403,816.94

$194,039.16

$209,777.78

51.95%

Check: attributed_revenue matches linear_revenue from Use Case 2 to the cent. Adding a hop to products didn't change the revenue, because every order item has exactly one product.

Bonus: Category affinity across 4 hops

Slice the same path by product category to see which campaigns sell a category and how long shoppers take to convert:

SELECT
  category AS product_category,
  channel AS marketing_channel,
  campaign_name,
  COUNT(DISTINCT order_id) AS orders_count,
  ROUND(SUM(sale_price * linear_weight), 2) AS attributed_sales,
  ROUND(AVG(days_to_convert), 1) AS avg_days_to_convert
FROM GRAPH_TABLE(
  `thelook_graph.eCommerce_Integrated`
  MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
  COLUMNS (
    t.campaign_name AS campaign_name,
    t.channel AS channel,
    p.category AS category,
    o.order_id AS order_id,
    oi.sale_price AS sale_price,
    i.linear_weight AS linear_weight,
    i.days_to_convert AS days_to_convert
  )
)
WHERE category = 'Outerwear & Coats'
GROUP BY category, channel, campaign_name
ORDER BY attributed_sales DESC;

Expected output:

product_category

marketing_channel

campaign_name

orders_count

attributed_sales

avg_days_to_convert

Outerwear & Coats

Email Marketing

Q4_Email_VIP_Weekly_Drop

4,178

$226,054.71

0.6

Outerwear & Coats

Email Marketing

Q4_Email_Cart_Abandonment

4,186

$224,058.77

0.6

Outerwear & Coats

Paid Search

Q4_Search_Generic_Audio

3,131

$151,458.01

0.6

Outerwear & Coats

Paid Search

Q4_Search_Brand_Electronics

3,138

$150,364.63

0.6

Outerwear & Coats

Video

Q4_YouTube_Video_Awareness

1,246

$97,937.94

0.6

Outerwear & Coats

Organic

Organic_Search_SEO

666

$48,987.74

0.5

Outerwear & Coats

Paid Social

Q4_TikTok_Prospecting_GenZ

1,158

$48,378.34

0.6

Outerwear & Coats

Paid Social

Q4_Meta_IG_Retargeting

1,156

$47,820.41

0.6

11. Use Case 4: Customer journey mapping (ISO GQL)

Query 4A: Trace one shopper's conversion path

Shopper Maurice (user_id = 21) placed two orders. This query starts at the user, follows ENGAGED_WITH to his touchpoints, then INFLUENCED to the orders they led to:

GRAPH `thelook_graph.eCommerce_Integrated`
MATCH (u:users)-[:ENGAGED_WITH]->(t:touchpoints)-[i:INFLUENCED]->(o:orders)
WHERE u.id = 21
RETURN
  u.id AS user_id,
  u.first_name,
  t.campaign_name,
  t.channel,
  t.event_type,
  i.touchpoint_rank,
  i.linear_weight,
  o.order_id
ORDER BY o.order_id, i.touchpoint_rank
LIMIT 10;

Expected output:

user_id

first_name

campaign_name

channel

event_type

touchpoint_rank

linear_weight

order_id

21

Maurice

Q4_Email_Cart_Abandonment

Email Marketing

home

1

0.2

27

21

Maurice

Q4_Email_VIP_Weekly_Drop

Email Marketing

department

2

0.2

27

21

Maurice

Q4_Email_Cart_Abandonment

Email Marketing

product

3

0.2

27

21

Maurice

Q4_Email_VIP_Weekly_Drop

Email Marketing

cart

4

0.2

27

21

Maurice

Q4_Email_Cart_Abandonment

Email Marketing

purchase

5

0.2

27

21

Maurice

Q4_Search_Brand_Electronics

Paid Search

home

1

0.2

28

21

Maurice

Q4_Search_Generic_Audio

Paid Search

department

2

0.2

28

21

Maurice

Q4_Search_Brand_Electronics

Paid Search

product

3

0.2

28

21

Maurice

Q4_Search_Generic_Audio

Paid Search

cart

4

0.2

28

21

Maurice

Q4_Search_Brand_Electronics

Paid Search

purchase

5

0.2

28

Check: each order has 5 touchpoints with linear_weight = 0.2, and the event_type sequence (home ➔ department ➔ product ➔ cart ➔ purchase) reads like a browsing session. Order 27 was driven by email; order 28 by paid search.

Query 4B: Return the path as graph objects

Bind the whole pattern to a path variable, p, and serialize it with TO_JSON(). The result carries every node and edge on the path as one JSON value, which is useful for passing a subgraph to an application or an AI agent, and it is what BigQuery Studio's graph visualization reads:

GRAPH `thelook_graph.eCommerce_Integrated`
MATCH p = (u:users)-[:ENGAGED_WITH]->(t:touchpoints)-[:INFLUENCED]->(o:orders)
WHERE u.id = 21
RETURN TO_JSON(p) AS path
LIMIT 10;

After the query finishes, select the Graph tab next to Results in the query results pane. BigQuery Studio draws Maurice's user node connected by ENGAGED_WITH edges to his 10 touchpoints, and each touchpoint by an INFLUENCED edge to the order it led to. Click the users node to see its properties, including first_name: Maurice, and its 10 neighbors.

The Graph tab in BigQuery Studio showing user 21’s node linked to 10 touchpoint nodes, with the side panel listing the user’s properties, including first_name Maurice

12. Use Case 5: Unified executive ROAS scorecard

Query

WITH marketing_funnel AS (
  -- 1. Top-of-funnel measures at their own grain (all 2.4M touchpoints)
  SELECT
    campaigns_channel AS channel,
    campaigns_campaign_name AS campaign_name,
    AGG(campaigns_total_campaign_budget) AS total_budget,
    AGG(touchpoints_total_clicks) AS total_clicks,
    AGG(touchpoints_unique_reach) AS unique_reach,
    ROUND(AGG(touchpoints_total_ad_spend), 2) AS total_ad_spend,
    ROUND(AGG(campaigns_total_campaign_budget) - AGG(touchpoints_total_ad_spend), 2) AS remaining_budget,
    ROUND(AGG(touchpoints_total_ad_spend) / NULLIF(AGG(touchpoints_total_clicks), 0), 2) AS effective_avg_cpc
  FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "touchpoints")
  GROUP BY channel, campaign_name
),

sales_attribution AS (
  -- 2. 4-hop profit attribution over converting paths only
  SELECT
    campaign_name,
    ROUND(SUM(sale_price * linear_weight), 2) AS attributed_revenue,
    ROUND(SUM(cost * linear_weight), 2) AS attributed_cogs,
    ROUND(SUM((sale_price - cost) * linear_weight), 2) AS gross_profit
  FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
    MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
    COLUMNS (
      t.campaign_name AS campaign_name,
      oi.sale_price,
      p.cost,
      i.linear_weight
    )
  )
  GROUP BY campaign_name
)

-- 3. Join the two views of the same graph
SELECT
  m.channel,
  m.campaign_name,
  m.total_budget,
  m.total_ad_spend,
  m.remaining_budget,
  m.effective_avg_cpc,
  s.attributed_revenue,
  s.gross_profit,
  ROUND(s.attributed_revenue / NULLIF(m.total_ad_spend, 0), 2) AS roas_on_spend,
  ROUND(s.attributed_revenue / NULLIF(m.total_budget, 0), 2) AS roas_on_budget,
  ROUND(SAFE_DIVIDE(s.gross_profit, s.attributed_revenue) * 100, 2) AS gross_margin_pct
FROM marketing_funnel m
JOIN sales_attribution s ON m.campaign_name = s.campaign_name
ORDER BY s.gross_profit DESC;

Expected output:

channel

campaign_name

total_budget

total_ad_spend

remaining_budget

effective_avg_cpc

attributed_revenue

gross_profit

roas_on_spend

roas_on_budget

gross_margin_pct

Email Marketing

Q4_Email_VIP_Weekly_Drop

$60,000

$54,463.00

$5,537.00

$0.10

$1,836,711.27

$953,124.97

33.72

30.61

51.89%

Email Marketing

Q4_Email_Cart_Abandonment

$75,000

$65,342.28

$9,657.72

$0.12

$1,836,242.50

$952,563.75

28.10

24.48

51.88%

Paid Search

Q4_Search_Generic_Audio

$1,500,000

$1,374,702.84

$125,297.16

$3.78

$1,208,564.90

$627,469.01

0.88

0.81

51.92%

Paid Search

Q4_Search_Brand_Electronics

$1,100,000

$960,109.92

$139,890.08

$2.64

$1,207,724.05

$626,949.77

1.26

1.10

51.91%

Video

Q4_YouTube_Video_Awareness

$220,000

$205,517.25

$14,482.75

$0.85

$814,035.10

$422,117.50

3.96

3.70

51.85%

Organic

Organic_Search_SEO

$25,000

$0.00

$25,000.00

$0.00

$412,996.24

$213,993.48

NULL

16.52

51.81%

Paid Social

Q4_TikTok_Prospecting_GenZ

$150,000

$120,639.42

$29,360.58

$0.99

$407,354.92

$211,538.17

3.38

2.72

51.93%

Paid Social

Q4_Meta_IG_Retargeting

$250,000

$224,869.35

$25,130.65

$1.85

$403,816.94

$209,777.78

1.80

1.62

51.95%

Check: roas_on_spend for Q4_Email_VIP_Weekly_Drop is 33.72 ($1,836,711.27 ÷ $54,463.00). Organic_Search_SEO shows NULL because its ad spend is $0—NULLIF protects you from dividing by zero.

13. Optional: Conversational Analytics agent in BigQuery and Gemini Enterprise

+---------------------------------------------------+
| BigQuery Studio: Agents                           |
| (knowledge source: thelook_graph.eCommerce_Integrated,|
|  10 measures)                                     |
+-------------------------┬-------------------------+
                          │ 1. Create and publish the data agent
                          ▼
+---------------------------------------------------+
| Conversational Analytics data agent               |
| (Marketing-Attribution-Agent)                     |
+-------------------------┬-------------------------+
                          │ 2. Import the agent into Gemini Enterprise
                          ▼
+---------------------------------------------------+
| Gemini Enterprise chat                            |
| (business users ask questions in natural language)|
+---------------------------------------------------+

Enable the APIs and roles

Data agents need the Gemini Data Analytics, Gemini for Google Cloud, and Knowledge Catalog APIs in addition to BigQuery. In Cloud Shell:

gcloud services enable \
  geminidataanalytics.googleapis.com \
  cloudaicompanion.googleapis.com \
  dataplex.googleapis.com \
  --project=${PROJECT_ID}

To create agents you need the Gemini Data Analytics Data Agent Creator role (roles/geminidataanalytics.dataAgentCreator); users who chat with the agent need Gemini Data Analytics Data Agent User (roles/geminidataanalytics.dataAgentUser). See Create data agents for details.

Create and publish the agent in BigQuery

  1. In the Google Cloud console, go to BigQuery > Agents and select the Agent catalog tab.
  2. Click Create agent and set:
    • Agent name: Marketing-Attribution-Agent
    • Agent description: Answers questions about marketing campaigns, ad spend, multi-touch attribution, ROAS, and customer conversion journeys.
  3. Under Knowledge sources, click Add source and select the property graph thelook_graph.eCommerce_Integrated. Attach the graph itself, not just the dataset—the measures are defined on the graph.
  4. Click Publish. In the Publishing channels pane, under Additional channels, choose how Gemini Enterprise will reach the agent:
    • If BigQuery and Gemini Enterprise are in the same project, select Register this agent in the Agent Registry section.
    • Otherwise, in Integrate via A2A (Agent2Agent), click Copy JSON to copy the agent card.
    The Marketing-Attribution-Agent editor in BigQuery with the eCommerce_Integrated graph under Knowledge sources, and the Publishing channels pane showing Register this agent and the Copy JSON button for A2A
  5. Click Publish (or Publish updates).

Import the agent into Gemini Enterprise

  1. In Gemini Enterprise, open your application and go to Agents > Add agent.
  2. On the Import agent step, paste the agent card JSON and click Preview Agent Details. Confirm that the agent name is Marketing-Attribution-Agent, then click Next.Import the agent card into Gemini Enterprise
  3. On the Agent authorization step, accept the prefilled OAuth settings (or enter your organization's) and click Finish.Authorize the agent in Gemini Enterprise

Validate the agent

Open a chat with Marketing-Attribution-Agent and ask:

What is the total ad spend for Q4_Search_Generic_Audio? Break it down by year and show a chart.

  • Expected: a grand total of $1,374,702.84—the value of the total_ad_spend measure for that campaign (see Query 1A). The agent also returns the yearly breakdown and usually renders it as a bar chart.
  • If you get a number in the billions: the agent joined the raw tables instead of using the graph. Confirm that the property graph eCommerce_Integrated is attached as the knowledge source, publish the update, and ask again.

Gemini Enterprise chat with Marketing-Attribution-Agent showing a bar chart of Q4_Search_Generic_Audio ad spend by year and the grand_total_spend result, 1374702.8399

More prompts to try

  • "Show the conversion journey for user 21. Include the user's first name, and for each order they placed, list the influencing touchpoints in rank order with campaign name, channel, event type, and linear weight. Then summarize which channel drove each order." The agent should name Maurice and describe his two orders: five Email Marketing touchpoints before order 27 and five Paid Search touchpoints before order 28, each weighted 0.2.The agent’s answer for user 21: Maurice’s order 27 was driven by five Email Marketing touchpoints and order 28 by five Paid Search touchpoints, each with linear weight 0.2, followed by the result table
  • "Build a campaign profitability leaderboard from the thelook_graph.eCommerce_Integrated graph. For each campaign report channel, total_ad_spend (use the graph's total_ad_spend measure, not a sum of cpc_cost through joins), attributed_revenue and gross_profit weighted by linear_weight, and roas_on_spend. Rank by gross_profit and draw a bar chart of roas_on_spend." The agent should rank Q4_Email_VIP_Weekly_Drop ($953,124.97 gross profit, 33.72x ROAS) and Q4_Email_Cart_Abandonment ($952,563.75, 28.10x) at the top, matching Use Case 5. If the total_ad_spend values don't match Query 1A, the agent re-derived spend from the raw tables; repeat the instruction to use the measure.The agent’s campaign profitability leaderboard: eight campaigns ranked by gross profit, with Q4_Email_VIP_Weekly_Drop at 33.72x and Q4_Email_Cart_Abandonment at 28.10x ROAS on spend
  • "What is our remaining budget for Q4_Search_Generic_Audio and what was its average CPC?" Expected: $125,297.16 remaining at $3.78 per click.

14. Decision guide and clean up

When to use which operator

Approach

Use it when

Why

Plain SQL SUM() on a single table

You aggregate a column at the grain of its own table (for example, SELECT SUM(total_budget) FROM marketing_campaigns).

No joins, so no rows are repeated.

Plain SQL SUM() across multi-table joins

Avoid for 1:N or N:M relationships.

Coarse-grain values repeat on every joined row, so a single campaign budget is summed once per click and line item.

GRAPH_TABLE

You need multi-hop paths, edge filters, or leaf-grain weighted sums such as sale_price * linear_weight.

Path-level expressions are evaluated per matched path. Safe for revenue and cost because each order's weights sum to 1.0.

GRAPH_EXPAND + AGG()

You need multi-grain rollups that mix coarse measures (total_campaign_budget) with fine ones (total_clicks, total_ad_spend, unique_reach) in BI-friendly SQL.

Each measure is evaluated at the grain where it was declared, so fan-out can't inflate it.

Clean up

To avoid charges after you finish, delete the graph and dataset in BigQuery Studio:

DROP PROPERTY GRAPH IF EXISTS `thelook_graph.eCommerce_Integrated`;
DROP SCHEMA IF EXISTS `thelook_graph` CASCADE;

Then delete the reservation assignment and the reservation in Cloud Shell. The assignment ID is generated by BigQuery, so look it up first:

# 1. Look up the assignment ID
ASSIGNMENT_ID=$(bq ls --reservation_assignment \
  --project_id=${PROJECT_ID} --location=${REGION} --format=json \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["name"].split("/")[-1])')
echo "Deleting assignment ${ASSIGNMENT_ID}"

# 2. Delete the assignment, then the reservation
bq rm --reservation_assignment \
  --project_id=${PROJECT_ID} \
  --location=${REGION} \
  ${RESERVATION_NAME}.${ASSIGNMENT_ID}

bq rm --reservation \
  --project_id=${PROJECT_ID} \
  --location=${REGION} \
  ${RESERVATION_NAME}

# 3. Confirm nothing is left
bq ls --reservation --project_id=${PROJECT_ID} --location=${REGION}

Expected final output: No reservations found.

If you created the optional data agent, delete it from BigQuery > Agents > Agent catalog, and remove it from your Gemini Enterprise application.

15. Congratulations

You built a marketing attribution and ROAS graph on BigQuery over the thelook_ecommerce snapshot, and used measures to roll up budgets, spend, and revenue at their own grain instead of double-counting through joins.

What you did

  • Modeled a property graph in place: thelook_graph.eCommerce_Integrated, 6 nodes, 5 edges, 10 measures, no data copied into a graph database.
  • Introspected the measures through INFORMATION_SCHEMA.PROPERTY_GRAPHS.
  • Reproduced Cartesian fan-out with a plain join: a $60,000 budget summed to $32,677,800,000.
  • Rolled up both ends of the funnel with GRAPH_EXPAND and AGG(), keeping every measure at its own grain.
  • Compared First-Touch, Last-Touch, and Linear attribution with GRAPH_TABLE, and verified that the total ($8,127,445.92) is invariant across models.
  • Computed 4-hop gross profit and margin (about 51.9% in every campaign) by reaching product cost.
  • Traced a shopper's journey in pure ISO GQL and visualized it in BigQuery Studio.
  • Fused both query styles into one executive ROAS scorecard.
  • (Optional) Grounded a Conversational Analytics agent on the graph and published it to Gemini Enterprise.

Next steps and further reading