BigQuery Graph 및 측정값을 사용한 마케팅 유입경로 측정항목 및 기여 분석

1. 소개

이 Codelab에서는 BigQuery Graph, BigQuery 측정, 대화형 분석을 사용하여 온라인 소매업체의 상위 유입경로, 하위 유입경로, 통합 마케팅 측정항목을 분석합니다.

소매 및 전자상거래에서 고객의 구매 경로는 선형인 경우가 거의 없습니다. 쇼핑객은 결제하기 전에 유료 검색, 유료 소셜, 동영상, 자연 검색, 이메일 캠페인을 거칩니다. 마케팅 리더들은 다음과 같은 질문을 계속해서 마주하게 됩니다.

  • 어떤 캠페인이 실제로 높은 마진의 수익을 창출하고 있으며, 어떤 캠페인이 광고비를 낭비하고 있는가?
  • 다양한 기여 분석 모델 (첫 번째 터치, 마지막 터치, 선형)은 채널 순위를 어떻게 변경하나요?
  • 중복 집계 없이 웹 터치 포인트 및 주문 광고 항목과 함께 캠페인 예산을 보고하려면 어떻게 해야 하나요?

마케팅 기여 분석 그래프 개념

빌드할 항목

  • 캠페인, 터치 포인트, 사용자, 주문, 주문 항목, 제품을 연결하는 thelook_graph.eCommerce_Integrated라는 속성 그래프로, 노드에 직접 선언된 10개의 측정값이 있습니다.
  • 하나의 쿼리에 세분화된 안전 예산 및 지출 롤업과 4홉 수익 기여 분석을 결합한 임원 ROAS 스코어카드
  • (선택사항) 비즈니스 사용자가 자연어로 쿼리할 수 있는 그래프를 기반으로 하는 대화형 분석 데이터 에이전트

마케팅 유입경로로 그려진 eCommerce_Integrated 그래프: 상위 유입경로 노드 및 측정, INFLUENCED 기여 분석 에지, 하위 유입경로 노드 및 측정

학습할 내용

각 단계는 다음 단계로 넘어가기 전에 검증해야 하는 마일스톤입니다.

  1. 노드에 선언된 측정값을 사용하여 BigQuery 테이블 및 뷰에서 속성 그래프를 제자리에서 모델링합니다.
  2. INFORMATION_SCHEMA.PROPERTY_GRAPHS를 통해 측정값을 검사합니다.
  3. 일반 SQL 조인으로 데카르트 팬아웃을 재현한 다음 GRAPH_EXPAND 및 AGG()를 사용하여 중복 없이 유입경로 상단 및 하단 측정항목을 롤업합니다.
  4. GRAPH_TABLE를 사용하여 첫 번째 터치, 마지막 터치, 선형 기여 분석을 비교합니다.
  5. 터치 포인트에서 제품 비용까지 이동하여 4홉 총이익 및 마진율을 계산합니다.
  6. 순수 ISO GQL을 사용하여 고객의 전환 여정을 추적합니다.
  7. 두 쿼리 스타일을 단일 임원 ROAS 스코어카드로 통합합니다.
  8. (선택사항) 그래프에서 대화형 분석 에이전트를 그라운딩하고 Gemini Enterprise에 게시합니다.

핵심 문제: 세분화 및 데카르트 팬아웃

이 Codelab에서 세부사항은 한 행이 나타내는 것을 의미합니다. 캠페인 예산은 캠페인 세분성 (캠페인당 1행)에 있습니다. 웹 클릭은 터치포인트 세분화 수준 (수백만 개의 행)에 있습니다. 주문 항목은 주문 항목 세분화 수준에 있습니다.

관계형 데이터 웨어하우스에서 기여 분석 질문에 답하려면 매우 다른 세분화 수준의 테이블을 조인해야 합니다 (campaigns ➔ touchpoints ➔ orders ➔ order_items ➔ products). 이로 인해 두 가지 문제가 발생합니다.

  1. 카티전 팬아웃 (중복 집계): 대략적인 행 (캠페인 예산 1개)을 세부적인 행 (모든 클릭 및 모든 광고 항목)에 조인하면 조인된 모든 행에서 예산이 반복됩니다. 일반 SUM()는 이를 수백만 번 합산합니다. 이 데이터 세트에서 단일 60,000달러 이메일 예산은 주문 광고 항목에 조인되어 100만 개가 넘는 행에 표시됩니다.
  2. 복잡하고 취약한 SQL: 멀티홉 경로 분석에는 중첩된 CTE, 윈도우 함수 또는 누군가 GROUP BY를 변경할 때 자동으로 중단되는 ANY_VALUE() 해결 방법이 필요합니다.

BigQuery Graph 및 측정으로 해결하는 방법

BigQuery Graph를 사용하면 이러한 모든 관계를 기존 BigQuery 테이블 및 뷰 위에 있는 논리적 레이어인 속성 그래프로 한 번에 선언할 수 있습니다. 데이터가 별도의 그래프 데이터베이스에 복사되지 않습니다. 그런 다음 두 가지 상호 보완적인 방식으로 동일한 그래프를 쿼리합니다.

  • GRAPH_EXPAND + AGG() (표준 SQL): 유입경로 상단 측정항목의 경우 start_node => "touchpoints"를 전달하고 유입경로 하단 측정항목의 경우 start_node => "order_items"를 전달하고 선언된 세부사항에서 각 측정값을 롤업합니다. 구문은 일반 SELECT ... GROUP BY이므로 Looker, Tableau 또는 모든 BI 도구에서 작동합니다.
  • GRAPH_TABLE 및 ISO GQL (그래프 패턴 일치): 여러 홉을 순회하여 기여 분석 모델을 비교하고, 터치 포인트를 제품 매출원가 (COGS)에 연결하여 실제 총이익을 파악하고, 개별 고객 여정을 매핑합니다.

BigQuery 측정(MEASURE(...))은 각 비즈니스 측정항목(total_campaign_budget, total_ad_spend, total_clicks, unique_reach, total_users, total_orders, gross_revenue, total_items_sold, avg_cost, avg_retail_price)을 소유한 노드에 삽입하므로 수학적으로 중복 집계가 불가능합니다. 마지막으로, 그래프에 그라운딩된 대화형 분석 데이터 에이전트를 통해 비즈니스 사용자는 자연어로 이러한 질문을 할 수 있습니다.

필요한 항목

  • 웹브라우저(예: Chrome)
  • 결제가 사용 설정된의 Google Cloud 프로젝트.
  • 해당 프로젝트의 IAM 역할: BigQuery 관리자 (roles/bigquery.admin), 예약을 만드는 BigQuery 리소스 관리자 (roles/bigquery.resourceAdmin), API를 사용 설정하는 서비스 사용량 관리자 (roles/serviceusage.serviceUsageAdmin) 프로젝트 소유자는 세 가지를 모두 포함합니다.
  • Cloud Shell(gcloud 및 bq 명령어용) 및 BigQuery Studio (SQL용)
  • SQL (JOIN, GROUP BY, CTE)에 대한 실무 지식 그래프 쿼리 경험이 없어도 됩니다.
  • (선택사항, 최종 단계만 해당) Gemini Enterprise 애플리케이션에 대한 액세스 권한

이 Codelab은 중급 수준의 데이터 분석가, 분석 엔지니어, 개발자를 대상으로 합니다.

예상 소요 시간: 약 90분 (선택사항인 Gemini Enterprise 단계를 건너뛰는 경우 약 80분)
예상 비용: $5 USD 미만 데이터 로드는 무료입니다. 쿼리는 기준 슬롯이 0개인 서버리스 BigQuery Enterprise 예약에서 실행되며 마지막에 삭제합니다.

2. 시작하기 전에

Google Cloud 프로젝트 만들기

  1. Google Cloud 콘솔의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.
  2. 프로젝트에 결제가 사용 설정되어 있는지 확인하세요.

Cloud Shell 시작

Google Cloud CLI (gcloud) 및 BigQuery CLI (bq)가 사전 설치된 Google Cloud Shell에서 명령어를 실행합니다.

  1. Google Cloud 콘솔의 상단 탐색 메뉴에서 Cloud Shell 활성화를 클릭합니다.
  2. 메시지가 표시되면 승인을 확인합니다.

환경 변수 설정

Cloud Shell에서 Codelab의 나머지 부분에서 사용하는 변수를 설정합니다.

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}"

API 사용 설정

BigQuery 및 BigQuery Reservation API를 사용 설정합니다. (선택사항인 대화형 분석 단계에서는 나중에 자체 API를 사용 설정합니다.)

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

BigQuery Enterprise 예약 및 할당 만들기

BigQuery Graph 문서에 따르면 GQL 쿼리 (GRAPH_TABLE 및 GRAPH ... MATCH)에는 Enterprise 또는 Enterprise Plus 버전을 사용하는 예약이 필요하지만 GRAPH_EXPAND 쿼리는 주문형 가격 책정으로도 실행할 수 있습니다. 유휴 상태일 때 비용이 발생하지 않도록 기준 슬롯 0개로 자동 확장 예약을 만듭니다.

# 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}

예약 검증

그래프 쿼리를 실행하기 전에 할당이 있는지 확인합니다. 누락된 경우 이 Codelab의 뒷부분에서 GQL 쿼리가 버전 오류와 함께 실패합니다.

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

예상 출력 (과제 ID는 다른 번호임):

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

3. 데이터 세트 만들기 및 샘플 데이터 로드

이 단계에서는 thelook_graph 데이터 세트를 만들고 공개 버킷 gs://sample-data-and-media/thelook_dataset_snapshot/에서 thelook_ecommerce 스냅샷의 기본 테이블 5개를 로드합니다.

테이블

행

한 행이 나타내는 항목 (세분성)

users

100,000

등록된 쇼핑객(인구통계 및 획득 traffic_source 포함)

orders

125,270

status 및 num_of_item를 사용한 결제 거래

order_items

181,271

구매한 광고 항목 1개(sale_price)

products

29,120

department, category, brand, cost, retail_price가 있는 카탈로그 제품

events

2,423,365

traffic_source와의 웹 상호작용 (home, department, product, cart, purchase) 1회

BigQuery Studio를 열고 다음을 쿼리 편집기에 붙여넣은 후 실행을 클릭합니다.

-- 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
);

방법 B: Cloud Shell에서 bq로 로드

또는 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

로드 검증

BigQuery Studio에서 이 쿼리를 실행하고 행 수를 비교합니다.

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

예상 출력:

table_id

row_count

events

2,423,365

order_items

181,271

orders

125,270

products

29,120

users

100,000명

events에 행이 더 적게 표시되면 로드 작업이 아직 실행 중인 것입니다. 잠시 기다린 후 쿼리를 다시 실행합니다.

4. 마케팅 뷰 및 기여 분석 에지 빌드

thelook_ecommerce 데이터 세트에는 쇼핑객, 주문, 웹 이벤트가 있지만 마케팅 캠페인 데이터는 없습니다. 이 단계에서는 thelook_graph에 세 가지 객체를 추가하여 마케팅 기여 분석 데이터 세트로 변환합니다.

eCommerce_Integrated 그래프의 항목 다이어그램: ENGAGED_WITH, GENERATED_BY, INFLUENCED, BELONGS_TO, IS_PRODUCT 에지로 연결된 사용자, 터치 포인트, 캠페인, 주문, order_items, 제품 파란색 테이블은 스냅샷에서 로드되고, 녹색 뷰와 주황색 에지 테이블은 이 단계에서 생성됩니다.

  • marketing_campaigns (보기): 5개 채널에 걸친 8개의 4분기 캠페인, 예산 및 타겟 ROAS 포함
  • touchpoints (뷰): 2,423,365개의 웹 이벤트로, 각각 캠페인, 채널, 벤치마크 클릭당비용 (CPC)으로 태그가 지정되어 있습니다.
  • edge_influenced (표): 첫 번째 터치, 마지막 터치, 선형 기여 분석 가중치를 사용하여 어떤 터치 포인트가 어떤 주문에 영향을 미쳤는지 보여줍니다.

2a. 캠페인 참조 뷰

캠페인 예산은 업스트림의 대략적인 데이터로, 캠페인당 하나의 행이 있습니다. 다음 뷰는 현실적인 4분기 예산으로 8개의 캠페인을 정의합니다.

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. 터치 포인트 뷰

모든 웹 이벤트는 이미 traffic_source (Adwords, Facebook, YouTube, Email 또는 Organic)를 기록합니다. 뷰는 각 소스를 마케팅 채널에 매핑하고, MOD(e.id, 2)를 사용하여 각 유료 소스를 두 캠페인으로 분할하고(짝수 이벤트 ID는 한 캠페인으로, 홀수 ID는 다른 캠페인으로 이동), 업계 벤치마크 CPC를 할당합니다.

traffic_source

채널

캠페인 (짝수/홀수 이벤트 ID)

CPC

Adwords

유료 검색

Q4_Search_Generic_Audio/Q4_Search_Brand_Electronics

$3.78 / $2.64

Facebook

유료 소셜

Q4_Meta_IG_Retargeting/Q4_TikTok_Prospecting_GenZ

$1.85 / $0.99

YouTube

동영상

Q4_YouTube_Video_Awareness

0.85달러

Email

이메일 마케팅

Q4_Email_Cart_Abandonment/Q4_Email_VIP_Weekly_Drop

$0.12 / $0.10

Organic

유기농

Organic_Search_SEO

$0.00

이것은 뷰이므로 데이터가 중복되지 않습니다.240만 개의 이벤트가 쿼리 시점에 태그됩니다.

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. 기여 분석 에지 테이블

edge_influenced은 터치 포인트와 영향을 받은 주문을 연결합니다. 이는 다음의 4가지 규칙을 따릅니다.

  • 동일한 사용자가 주문 30일 전(order time - 30 days~order time 사이의 created_at)에 터치 포인트를 만든 경우 터치 포인트가 주문에 영향을 미칩니다.
  • 상태가 Cancelled 또는 Returned인 주문은 제외됩니다.
  • 터치 포인트는 각 주문 (touchpoint_rank) 내에서 시간별로 순위가 매겨집니다. 이벤트 ID는 순위가 결정론적이 되도록 동점을 해소합니다.
  • 터치 포인트당 세 가지 기여 분석 가중치가 미리 계산됩니다.
    • first_touch_weight = 가장 이른 터치 포인트의 경우 1.0, 그 외에는 0.0
    • last_touch_weight = 최신 터치 포인트의 경우 1.0, 그렇지 않으면 0.0
    • linear_weight = 1 / (터치포인트 수)이므로 각 주문의 가중치 합계는 1.0입니다.

예를 들어 터치 포인트가 3개인 주문에는 다음과 같은 가중치가 부여됩니다.

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

모든 모델에서 각 주문의 가중치 합계는 1.0이므로 광고 항목의 sale_price에 가중치를 곱하고 합산하면 수익이 중복 집계되지 않습니다.

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;

기여 분석 에지 검증

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

예상 출력: 976,555 다른 숫자가 표시되면 created_at가 TIMESTAMP로 로드되었는지 확인하고(logical-type 플래그를 사용하여 로드를 다시 실행) 5개 테이블 모두에 예상 행 수가 있는지 확인합니다.

5. 측정값으로 속성 그래프 선언

속성 그래프 분석

절

기능

NODE TABLES (...)

노드 (항목)가 되는 테이블 또는 뷰를 나열합니다.

KEY (col)

노드를 고유하게 식별하는 열입니다. 측정은 이 키로 중복 삭제됩니다.

LABEL name PROPERTIES (...)

쿼리에 사용되는 라벨 ((c:campaigns))을 노드에 지정하고 속성으로 노출되는 열을 나열합니다.

MEASURE(expr) AS name

이 노드에 속하는 집계를 선언합니다. AGG(name)는 조인에서 생성되는 행 수와 관계없이 고유 키당 한 번씩 평가합니다.

EDGE TABLES (...)

행이 에지 (관계)가 되는 테이블을 나열합니다. 동일한 테이블이 노드와 에지로 표시될 수 있습니다.

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

에지가 시작되고 가리키는 노드를 정의합니다. NO PROPERTIES는 에지에 자체 속성이 없음을 의미합니다.

다음은 만들려는 그래프의 노드 하나와 에지 하나에 주석을 추가한 것입니다.

-- 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

eCommerce_Integrated 만들기

BigQuery Studio에서 전체 문을 실행합니다. 측정값 10개가 있는 노드 테이블 6개와 에지 테이블 5개를 선언합니다.

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
);

10개의 측정항목은 각각 해당 측정항목을 소유한 세부사항에서 선언됩니다.

  • 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

구조적 에지 (GENERATED_BY, ENGAGED_WITH, BELONGS_TO, IS_PRODUCT)는 NO PROPERTIES를 사용합니다. 기여 분석 가중치는 노드가 아닌 터치 포인트-순서 관계의 속성이므로 INFLUENCED만 속성을 전달합니다.

그래프 검증

SELECT property_graph_name
FROM `thelook_graph.INFORMATION_SCHEMA.PROPERTY_GRAPHS`;

예상 출력: 행 1개, eCommerce_Integrated CREATE 문이 실패한 경우 가장 일반적인 원인은 이전 두 단계에서 테이블 또는 뷰가 누락된 것입니다.

6. INFORMATION_SCHEMA를 사용하여 측정 검사

INFORMATION_SCHEMA.PROPERTY_GRAPHS는 그래프 정의를 property_graph_metadata_json 열에 JSON으로 노출합니다. nodeTables 배열에는 각 노드가 포함되고 각 노드의 labelAndProperties[0].properties 배열에는 속성이 나열되며 expressionKind = "MEASURE"는 측정값을 표시합니다. 다음 쿼리는 해당 구조를 UNNEST합니다.

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;

예상 출력 (행 10개):

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

BigQuery Studio에서 측정값 보기

  1. BigQuery Studio에서 탐색기 패널을 엽니다.
  2. 프로젝트를 펼친 다음 데이터 세트 thelook_graph, 그래프를 펼칩니다.
  3. eCommerce_Integrated를 클릭하고 목록 탭을 엽니다.
  4. 터치포인트를 확장합니다. 실제 열 (touchpoint_id, campaign_name, cpc_cost, …)은 DIMENSION로 나열되고 그 뒤에 total_ad_spend, total_clicks, unique_reach가 오며, MEASURE로 표시되고 추론된 유형과 함께 표시됩니다. edge_influenced를 펼쳐 INFLUENCED 에지가 전달하는 세 가지 기여 분석 가중치를 확인합니다.터치 포인트 노드가 펼쳐진 BigQuery Studio의 eCommerce_Integrated 그래프의 목록 탭: total_ad_spend, total_clicks, unique_reach가 MEASURE로 표시됨

7. 문제 확인: 일반 SQL 조인의 팬아웃

그래프를 쿼리하기 전에 측정으로 해결하는 문제를 재현합니다. 상위 유입경로 질문은 간단합니다. 각 캠페인의 예산, 클릭수, 광고비는 얼마인가요? 하지만 입력은 두 가지 세부사항으로 구성됩니다. marketing_campaigns의 예산(캠페인당 1개 행), touchpoints의 클릭수 및 지출(240만 개 행)입니다. 오늘날 대부분의 데이터 웨어하우스에서 하는 것처럼 조인을 사용하여 답해 보겠습니다.

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;

예상 출력:

채널

campaign_name

total_budget

total_clicks

total_ad_spend

유료 검색

Q4_Search_Generic_Audio

545,517,000,000달러

363,678

$1,374,702.84

유료 검색

Q4_Search_Brand_Electronics

400,045,800,000달러

363,678

$960,109.92

유료 소셜

Q4_Meta_IG_Retargeting

30,387,750,000달러

121,551

$224,869.35

동영상

Q4_YouTube_Video_Awareness

53,192,700,000달러

241,785

$205,517.25

유료 소셜

Q4_TikTok_Prospecting_GenZ

18,278,700,000달러

121,858

$120,639.42

이메일 마케팅

Q4_Email_Cart_Abandonment

40,838,925,000달러

544,519

$65,342.28

이메일 마케팅

Q4_Email_VIP_Weekly_Drop

32,677,800,000달러

544,630

$54,463.00

유기농

Organic_Search_SEO

3,041,650,000달러

121,666

$0.00

세 가지 열 중 두 가지가 여전히 올바른 이유

total_clicks 및 total_ad_spend는 정답입니다. touchpoint_id 및 cpc_cost는 합산되는 행의 세부사항에 따라 달라지기 때문입니다. 터치 포인트당 하나의 값, 행당 하나의 터치 포인트가 있습니다. total_budget는 모든 터치 포인트 행에 스탬프 처리된 캠페인 단위 값이므로 조인을 통해 하나의 숫자가 수십만 개의 사본으로 변환됩니다. 이것이 바로 데카르트 팬아웃이며, 홉마다 복합적으로 작용합니다. 조인을 주문과 주문 항목으로 확장하면 동일한 60,000달러가 100만 개가 넘는 행에 표시됩니다.

일반적인 해결 방법이 효과가 없는 이유

  • ANY_VALUE(c.total_budget)는 하나의 사본을 선택하지만 GROUP BY가 캠페인 세부사항에 유지되는 동안에만 작동합니다. 대신 채널별로 그룹화하면 한 캠페인의 예산은 그대로 유지되고 나머지는 삭제됩니다.
  • 세분화 수준별로 별도의 CTE를 사용하는 것이 맞지만, 새로운 측정항목마다 자체 CTE와 조인이 필요하며, 나중에 잘못된 CTE를 통해 집계하는 것을 막을 수 없습니다.
  • 두 캠페인이 예산을 공유하는 즉시 SUM(DISTINCT c.total_budget)가 잘못됩니다.

측정값은 소스에서 문제를 제거합니다. 예산 집계는 campaigns 노드에서 한 번 선언되며 BigQuery는 쿼리가 조인하는 다른 항목에 관계없이 해당 세부사항에서 이를 평가합니다. $32,677,800,000이라는 숫자를 기억해 두세요. 다음 단계에서는 그래프를 통해 동일한 스코어카드를 실행합니다.

8. 사용 사례 1: 상위 유입경로 및 하위 유입경로 롤업 (GRAPH_EXPAND)

GRAPH_EXPAND 작동 방식

  • GRAPH_EXPAND("graph", start_node => "touchpoints")는 touchpoints 노드당 하나의 행을 반환하며, 이 행은 연결된 노드(여기서는 GENERATED_BY를 통한 campaigns 및 ENGAGED_WITH를 통한 users)에 조인됩니다.
  • 모든 속성과 측정값은 campaigns_channel, campaigns_total_campaign_budget, touchpoints_total_clicks와 같이 _라는 열로 노출됩니다.
  • AGG()는 각 그룹 내에서 고유 노드 키당 한 번 측정값을 평가합니다. 따라서 캠페인 행이 363,678개의 터치 포인트 행에 걸쳐 반복되더라도 AGG(campaigns_total_campaign_budget)는 각 캠페인의 예산을 한 번만 합산합니다.
  • 그 외에는 모두 표준 SQL (GROUP BY, ORDER BY, ROUND)이므로 BI 도구에서 이러한 쿼리를 직접 실행할 수 있습니다.

쿼리 1A: 상위 유입경로 마케팅 스코어카드

이전 단계에서는 일반 조인으로 인해 모든 캠페인의 예산이 클릭수로 부풀려졌습니다. 이제 그래프를 통해 같은 질문에 답해 보세요. 구조적으로 GRAPH_EXPAND은 FROM 절의 조인을 대체하고 AGG()은 SUM() 및 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;

예상 출력:

채널

campaign_name

total_budget

total_clicks

unique_reach

total_ad_spend

remaining_budget

effective_avg_cpc

유료 검색

Q4_Search_Generic_Audio

1,500,000달러

363,678

39,695

$1,374,702.84

$125,297.16

3,780원

유료 검색

Q4_Search_Brand_Electronics

1,100,000달러

363,678

39,695

$960,109.92

$139,890.08

$2.64

유료 소셜

Q4_Meta_IG_Retargeting

$250,000

121,551

16,182

$224,869.35

$25,130.65

$1.85

동영상

Q4_YouTube_Video_Awareness

$220,000

241,785

16,161

$205,517.25

$14,482.75

0.85달러

유료 소셜

Q4_TikTok_Prospecting_GenZ

$150,000

121,858

16,182

$120,639.42

$29,360.58

$0.99

이메일 마케팅

Q4_Email_Cart_Abandonment

$75,000

544,519

52,049

$65,342.28

$9,657.72

$0.12

이메일 마케팅

Q4_Email_VIP_Weekly_Drop

$60,000

544,630

52,049

$54,463.00

$5,537.00

$0.10

유기농

Organic_Search_SEO

$25,000

121,666

8,618

$0.00

$25,000.00

$0.00

확인: Q4_Email_VIP_Weekly_Drop의 total_budget는 일반 조인에서 생성된 $32,677,800,000가 아닌 $60,000입니다. AGG()는 캠페인 행이 모든 터치 포인트에서 반복되더라도 캠페인 예산을 한 번만 집계하는 반면, total_clicks는 여전히 544,630개를 모두 집계합니다.

쿼리 1B: 하위 유입경로 상품기획 롤업

동일한 그래프에서 start_node => "order_items"를 전달하여 orders (BELONGS_TO) 및 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;

예상 출력:

department

카테고리

distinct_orders

items_sold

gross_revenue

avg_unit_cost

avg_retail_price

남성

Outerwear & Coats

5,564

5,713

$852,464.61

$65.94

$149.40

남성

Jeans

7,370

7,679

$779,004.17

$53.80

$101.16

남성

Suits & Sport Coats

4,926

5,041

$642,783.10

$50.74

$126.37

남성

Sweaters

6,660

6,869

528,344.51달러

$38.83

$77.59

여성

Outerwear & Coats

3,258

3,323

$470,456.28

$63.74

$141.55

확인: 남성 Outerwear & Coats의 경우 distinct_orders (5,564)가 items_sold (5,713)보다 작습니다. AGG(orders_total_orders)는 order_id에 따라 중복 삭제된 다중 상품 장바구니를 계산한 반면, AGG(order_items_total_items_sold)는 모든 광고 항목을 계산했습니다.

9. 사용 사례 2: 멀티 터치 기여 분석 비교 (GRAPH_TABLE)

GQL 패턴 읽기

GRAPH_TABLE는 SQL FROM 절에 그래프 패턴을 삽입합니다. 이 쿼리의 패턴은 다음과 같습니다.

(t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)
  • (t:touchpoints)는 라벨이 touchpoints인 노드와 일치하고 이를 변수 t에 바인딩합니다.
  • -[i:INFLUENCED]->는 선언된 방향 (터치 포인트 ➔ 주문)으로 INFLUENCED 에지를 따르고 에지를 i에 바인딩하므로 i.linear_weight를 읽을 수 있습니다.
  • (o:orders)는 영향을 받은 주문입니다.
  • <-[:BELONGS_TO]-(oi:order_items)는 주문을 가리키는 BELONGS_TO 에지와 일치합니다 (화살표가 왼쪽을 가리킴). 각 광고 항목 oi는 주문 o에 속합니다. 속성이 필요하지 않으므로 에지에는 변수가 없습니다.
  • COLUMNS (...)는 노드 및 에지 속성을 일반 열에 투영한 후 SUM 및 GROUP BY가 평소와 같이 작동합니다.

쿼리

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;

예상 출력:

campaign_name

채널

first_touch_revenue

last_touch_revenue

linear_revenue

Q4_Email_VIP_Weekly_Drop

이메일 마케팅

$1,844,969.34

$1,852,985.64

1,836,711.27달러

Q4_Email_Cart_Abandonment

이메일 마케팅

$1,846,318.54

$1,818,126.95

1,836,242.50달러

Q4_Search_Generic_Audio

유료 검색

$1,203,174.40

$1,203,055.84

1,208,564.90달러

Q4_Search_Brand_Electronics

유료 검색

$1,204,866.84

$1,204,632.74

1,207,724.05달러

Q4_YouTube_Video_Awareness

동영상

$809,437.33

$821,840.02

$814,035.10

Organic_Search_SEO

유기농

$409,598.88

$420,458.99

$412,996.24

Q4_TikTok_Prospecting_GenZ

유료 소셜

$410,900.27

$401,289.08

407,354.92달러

Q4_Meta_IG_Retargeting

유료 소셜

$398,192.90

$405,069.24

403,816.94달러

확인: linear_revenue 열을 합산합니다 (또는 GROUP BY 삭제). 각 주문의 가중치 합계가 1.0이므로 모든 모델에서 총합은 $8,127,445.92입니다. 수익은 캠페인 간에 재분배되며 생성되거나 손실되지 않습니다.

수치로 보는 성과

  • 모든 모델에서 이메일로 리드를 육성합니다. 두 이메일 캠페인에는 각각 약 184만 달러가 기여합니다.
  • 잠재고객 발굴과 계약 체결. Q4_TikTok_Prospecting_GenZ는 첫 번째 터치 ($410,900.27)에서 마지막 터치 ($401,289.08)보다 더 많은 기여도를 얻으며, 이는 유입경로 상단 역할과 일치합니다. Q4_Meta_IG_Retargeting ($405,069.24) 및 Q4_YouTube_Video_Awareness ($821,840.02)은 마지막 터치에서 증가하며, 이는 종료 역할과 일치합니다.

10. 사용 사례 3: 4홉 수익성 및 총이익률(GRAPH_TABLE)

쿼리

이 패턴은 -[:IS_PRODUCT]->(p:products)를 추가하여 각 광고 항목의 카탈로그 비용에 도달합니다.

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;

예상 출력:

campaign_name

채널

attributed_revenue

attributed_cogs

gross_profit

gross_margin_pct

Q4_Email_VIP_Weekly_Drop

이메일 마케팅

$1,836,711.27

$883,586.30

$953,124.97

51.89%

Q4_Email_Cart_Abandonment

이메일 마케팅

$1,836,242.50

$883,678.75

$952,563.75

51.88%

Q4_Search_Generic_Audio

유료 검색

1,208,564.90달러

$581,095.89

$627,469.01

51.92%

Q4_Search_Brand_Electronics

유료 검색

$1,207,724.05

$580,774.28

$626,949.77

51.91%

Q4_YouTube_Video_Awareness

동영상

$814,035.10

$391,917.60

422,117.50달러

51.85%

Organic_Search_SEO

유기농

$412,996.24

$199,002.75

213,993.48달러

51.81%

Q4_TikTok_Prospecting_GenZ

유료 소셜

$407,354.92

$195,816.75

211,538.17달러

51.93%

Q4_Meta_IG_Retargeting

유료 소셜

$403,816.94

$194,039.16

209,777.78달러

51.95%

확인: attributed_revenue는 사용 사례 2의 linear_revenue와 센트 단위까지 일치합니다. 모든 주문 항목에는 정확히 하나의 제품이 있으므로 products에 홉을 추가해도 수익은 변경되지 않습니다.

보너스: 4홉에 걸친 카테고리 친화성

제품 카테고리별로 동일한 경로를 분류하여 어떤 캠페인이 카테고리를 판매하는지, 쇼핑객이 전환하는 데 걸리는 시간을 확인합니다.

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;

예상 출력:

product_category

marketing_channel

campaign_name

orders_count

attributed_sales

avg_days_to_convert

Outerwear & Coats

이메일 마케팅

Q4_Email_VIP_Weekly_Drop

4,178

$226,054.71

0.6

Outerwear & Coats

이메일 마케팅

Q4_Email_Cart_Abandonment

4,186

$224,058.77

0.6

Outerwear & Coats

유료 검색

Q4_Search_Generic_Audio

3,131

151,458.01달러

0.6

Outerwear & Coats

유료 검색

Q4_Search_Brand_Electronics

3,138

$150,364.63

0.6

Outerwear & Coats

동영상

Q4_YouTube_Video_Awareness

1,246

$97,937.94

0.6

Outerwear & Coats

유기농

Organic_Search_SEO

666

$48,987.74

0.5

Outerwear & Coats

유료 소셜

Q4_TikTok_Prospecting_GenZ

1,158

$48,378.34

0.6

Outerwear & Coats

유료 소셜

Q4_Meta_IG_Retargeting

1,156

$47,820.41

0.6

11. 사용 사례 4: 고객 여정 매핑 (ISO GQL)

쿼리 4A: 쇼핑객 한 명의 전환 경로 추적

구매자 모리스 (user_id = 21)가 두 건의 주문을 했습니다. 이 쿼리는 사용자에서 시작하여 ENGAGED_WITH를 따라 터치 포인트로 이동한 다음 INFLUENCED를 따라 터치 포인트가 유도한 주문으로 이동합니다.

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;

예상 출력:

user_id

first_name

campaign_name

채널

event_type

touchpoint_rank

linear_weight

order_id

21

모리스

Q4_Email_Cart_Abandonment

이메일 마케팅

home

1

0.2

27

21

모리스

Q4_Email_VIP_Weekly_Drop

이메일 마케팅

department

2

0.2

27

21

모리스

Q4_Email_Cart_Abandonment

이메일 마케팅

product

3

0.2

27

21

모리스

Q4_Email_VIP_Weekly_Drop

이메일 마케팅

cart

4

0.2

27

21

모리스

Q4_Email_Cart_Abandonment

이메일 마케팅

purchase

5

0.2

27

21

모리스

Q4_Search_Brand_Electronics

유료 검색

home

1

0.2

28

21

모리스

Q4_Search_Generic_Audio

유료 검색

department

2

0.2

28

21

모리스

Q4_Search_Brand_Electronics

유료 검색

product

3

0.2

28

21

모리스

Q4_Search_Generic_Audio

유료 검색

cart

4

0.2

28

21

모리스

Q4_Search_Brand_Electronics

유료 검색

purchase

5

0.2

28

확인: 각 주문에는 linear_weight = 0.2가 있는 터치 포인트가 5개 있으며, event_type 시퀀스 (home ➔ department ➔ product ➔ cart ➔ purchase)는 탐색 세션처럼 읽힙니다. 주문 27은 이메일, 주문 28은 유료 검색을 통해 발생했습니다.

쿼리 4B: 경로를 그래프 객체로 반환

전체 패턴을 경로 변수 p에 바인딩하고 TO_JSON()로 직렬화합니다. 결과는 경로의 모든 노드와 에지를 하나의 JSON 값으로 전달합니다. 이는 하위 그래프를 애플리케이션 또는 AI 에이전트에 전달하는 데 유용하며 BigQuery Studio의 그래프 시각화에서 읽는 값입니다.

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;

쿼리가 완료되면 쿼리 결과 창에서 결과 옆에 있는 그래프 탭을 선택합니다. BigQuery Studio는 ENGAGED_WITH 에지로 10개의 터치 포인트에 연결된 모리스의 사용자 노드를 그리고, 각 터치 포인트는 INFLUENCED 에지로 연결된 주문에 연결됩니다. 사용자 노드를 클릭하여 first_name: Maurice를 포함한 속성과 10개의 이웃을 확인합니다.

BigQuery Studio의 그래프 탭에 사용자 21의 노드가 10개의 터치포인트 노드에 연결되어 있고, 측면 패널에는 first_name Maurice를 포함한 사용자의 속성이 나열되어 있습니다.

12. 사용 사례 5: 통합 임원 ROAS 스코어카드

쿼리

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;

예상 출력:

채널

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

이메일 마케팅

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%

이메일 마케팅

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%

유료 검색

Q4_Search_Generic_Audio

$1,500,000

$1,374,702.84

$125,297.16

3,780원

1,208,564.90달러

$627,469.01

0.88

0.81

51.92%

유료 검색

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%

동영상

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_Search_SEO

$25,000

$0.00

$25,000.00

$0.00

$412,996.24

213,993.48달러

NULL

16.52

51.81%

유료 소셜

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%

유료 소셜

Q4_Meta_IG_Retargeting

2억 5천만 원

$224,869.35

$25,130.65

$1.85

$403,816.94

209,777.78달러

1.80

1.62

51.95%

확인: Q4_Email_VIP_Weekly_Drop의 roas_on_spend는 33.72 ($1,836,711.27 ÷ $54,463.00)입니다. Organic_Search_SEO는 광고비가 0달러이므로 NULL를 표시합니다. NULLIF는 0으로 나누는 것을 방지합니다.

13. 선택사항: BigQuery 및 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)|
+---------------------------------------------------+

API 및 역할 사용 설정

데이터 에이전트에는 BigQuery 외에도 Gemini Data Analytics, Gemini for Google Cloud, Knowledge Catalog API가 필요합니다. Cloud Shell에서 다음을 실행합니다.

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

에이전트를 만들려면 Gemini 데이터 분석 데이터 에이전트 생성자 역할 (roles/geminidataanalytics.dataAgentCreator)이 필요합니다. 에이전트와 채팅하는 사용자에게는 Gemini 데이터 분석 데이터 에이전트 사용자 (roles/geminidataanalytics.dataAgentUser)가 필요합니다. 자세한 내용은 데이터 에이전트 만들기를 참조하세요.

BigQuery에서 에이전트 만들기 및 게시

  1. Google Cloud 콘솔에서 BigQuery > 에이전트로 이동하여 에이전트 카탈로그 탭을 선택합니다.
  2. 에이전트 만들기를 클릭하고 다음을 설정합니다.
    • 상담사 이름: Marketing-Attribution-Agent
    • 에이전트 설명: Answers questions about marketing campaigns, ad spend, multi-touch attribution, ROAS, and customer conversion journeys.
  3. 지식 소스에서 소스 추가를 클릭하고 속성 그래프 thelook_graph.eCommerce_Integrated를 선택합니다. 데이터 세트뿐만 아니라 그래프 자체를 연결합니다. 측정값은 그래프에 정의됩니다.
  4. 게시를 클릭합니다. 게시 채널 창의 추가 채널에서 Gemini Enterprise가 에이전트에 도달하는 방법을 선택합니다.
    • BigQuery와 Gemini Enterprise가 동일한 프로젝트에 있는 경우 에이전트 레지스트리 섹션에서 이 에이전트 등록을 선택합니다.
    • 그렇지 않으면 A2A (Agent2Agent)를 통해 통합에서 JSON 복사를 클릭하여 에이전트 카드를 복사합니다.
    지식 소스 아래에 eCommerce_Integrated 그래프가 있는 BigQuery의 Marketing-Attribution-Agent 에디터와 이 에이전트 등록 및 A2A용 JSON 복사 버튼이 표시된 게시 채널 창
  5. 게시 (또는 업데이트 게시)를 클릭합니다.

Gemini Enterprise로 에이전트 가져오기

  1. Gemini Enterprise에서 애플리케이션을 열고 에이전트 > 에이전트 추가로 이동합니다.
  2. 에이전트 가져오기 단계에서 에이전트 카드 JSON을 붙여넣고 에이전트 세부정보 미리보기를 클릭합니다. 에이전트 이름이 Marketing-Attribution-Agent인지 확인한 후 다음을 클릭합니다.Gemini Enterprise로 에이전트 카드 가져오기
  3. 에이전트 승인 단계에서 미리 입력된 OAuth 설정을 수락하거나 조직의 설정을 입력하고 완료를 클릭합니다.Gemini Enterprise에서 에이전트 승인

에이전트 검증

Marketing-Attribution-Agent와의 채팅을 열고 다음과 같이 질문합니다.

Q4_Search_Generic_Audio의 총 광고비는 얼마인가요? 연도별로 분류하고 차트를 보여줘.

  • 예상: 총합계 $1,374,702.84—해당 캠페인의 total_ad_spend 측정값 (쿼리 1A 참고) 에이전트는 연간 분석도 반환하며 일반적으로 막대 그래프로 렌더링합니다.
  • 수십억 단위의 숫자가 표시되는 경우: 에이전트가 그래프를 사용하는 대신 원시 테이블을 조인한 것입니다. 속성 그래프 eCommerce_Integrated가 지식 소스로 연결되어 있는지 확인하고 업데이트를 게시한 후 다시 질문합니다.

Marketing-Attribution-Agent와의 Gemini Enterprise 채팅에서 연도별 Q4_Search_Generic_Audio 광고비 지출과 총 지출 결과인 1374702.8399를 보여주는 막대 그래프

시도해 볼 수 있는 다른 프롬프트

  • "사용자 21의 전환 여정을 보여줘. 사용자의 이름을 포함하고, 사용자가 한 각 주문에 대해 영향을 미친 터치포인트를 캠페인 이름, 채널, 이벤트 유형, 선형 가중치와 함께 순위 순서로 나열합니다. 그런 다음 각 주문을 유도한 채널을 요약해 줘." 상담사는 모리스의 이름을 언급하고 그의 두 주문을 설명해야 합니다. 주문 27 전에 이메일 마케팅 터치포인트 5개, 주문 28 전에 유료 검색 터치포인트 5개가 있으며, 각각의 가중치는 0.2입니다.사용자 21에 대한 에이전트의 답변: 모리스의 주문 27은 이메일 마케팅 터치 포인트 5개, 주문 28은 유료 검색 터치 포인트 5개에 의해 발생했으며, 각각 선형 가중치 0.2가 적용되었고, 그 뒤에 결과 표가 표시됩니다.
  • "thelook_graph.eCommerce_Integrated 그래프에서 캠페인 수익성 리더보드를 빌드해 줘. 각 캠페인 보고 채널에 대해 total_ad_spend (조인을 통한 cpc_cost의 합계가 아닌 그래프의 total_ad_spend 측정값 사용), linear_weight로 가중치를 부여한 attributed_revenue 및 gross_profit, roas_on_spend를 표시합니다. gross_profit별로 순위를 매기고 roas_on_spend의 막대 그래프를 그려 줘.' 에이전트는 사용 사례 5에 따라 Q4_Email_VIP_Weekly_Drop (총이익 $953,124.97, ROAS 33.72배)와 Q4_Email_Cart_Abandonment ($952,563.75, 28.10배)를 상위에 표시해야 합니다. total_ad_spend 값이 쿼리 1A와 일치하지 않으면 상담사가 원시 테이블에서 지출을 다시 도출한 것입니다. 측정값을 사용하는 안내를 반복하세요.에이전트의 캠페인 수익성 리더보드: 총이익을 기준으로 순위가 매겨진 8개의 캠페인. Q4_Email_VIP_Weekly_Drop은 지출 대비 ROAS가 33.72배, Q4_Email_Cart_Abandonment는 28.10배입니다.
  • "Q4_Search_Generic_Audio의 남은 예산은 얼마이고 평균 CPC는 얼마였어?" 예상: 클릭당 3.78달러로 125,297.16달러가 남습니다.

14. 결정 가이드 및 정리

연산자 사용 시기

접근 방식

사용 시점

이유

단일 테이블의 일반 SQL SUM()

자체 테이블의 세부사항 (예: SELECT SUM(total_budget) FROM marketing_campaigns)에서 열을 집계합니다.

조인이 없으므로 행이 반복되지 않습니다.

여러 테이블 조인에 걸친 일반 SQL SUM()

1:N 또는 N:M 관계에는 사용하지 마세요.

대략적인 값은 조인된 모든 행에서 반복되므로 단일 캠페인 예산은 클릭 및 광고 항목당 한 번씩 합산됩니다.

GRAPH_TABLE

멀티홉 경로, 에지 필터 또는 리프 단위 가중치 합계(예: sale_price * linear_weight)가 필요합니다.

경로 수준 표현식은 일치하는 경로별로 평가됩니다. 각 주문의 가중치 합계가 1.0이므로 수익 및 비용에 안전합니다.

GRAPH_EXPAND + AGG()

BI 친화적인 SQL에서 대략적인 측정값 (total_campaign_budget)과 세부적인 측정값 (total_clicks, total_ad_spend, unique_reach)을 혼합하는 다중 세분성 롤업이 필요합니다.

각 측정값은 선언된 세분성에서 평가되므로 팬아웃으로 인해 측정값이 부풀려질 수 없습니다.

삭제

완료 후 요금이 청구되지 않도록 하려면 BigQuery Studio에서 그래프와 데이터 세트를 삭제하세요.

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

그런 다음 Cloud Shell에서 예약 할당과 예약을 삭제합니다. 할당 ID는 BigQuery에서 생성되므로 먼저 조회합니다.

# 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}

예상 최종 출력: No reservations found.

선택사항인 데이터 에이전트를 만든 경우 BigQuery > 에이전트 > 에이전트 카탈로그에서 삭제하고 Gemini Enterprise 애플리케이션에서 삭제합니다.

15. 축하합니다

thelook_ecommerce 스냅샷을 통해 BigQuery에서 마케팅 기여 분석 및 ROAS 그래프를 빌드하고, 조인을 통해 중복 집계하는 대신 자체 세부사항에서 예산, 지출, 수익을 롤업하는 측정값을 사용했습니다.

수행한 작업

  • 속성 그래프를 제자리에서 모델링: thelook_graph.eCommerce_Integrated, 노드 6개, 에지 5개, 측정값 10개, 그래프 데이터베이스에 복사된 데이터 없음
  • INFORMATION_SCHEMA.PROPERTY_GRAPHS를 통해 측정값을 검사했습니다.
  • 일반 조인을 사용하여 데카르트 팬아웃을 재현: 60,000달러의 예산이 32,677,800,000달러로 합산되었습니다.
  • GRAPH_EXPAND 및 AGG()를 사용하여 유입경로의 양쪽 끝을 롤업하여 모든 측정값을 자체 세부사항으로 유지합니다.
  • GRAPH_TABLE를 사용하여 첫 번째 터치 포인트, 마지막 터치 포인트, 선형 기여 분석을 비교하고 총계 ($8,127,445.92)가 모델 전반에서 변하지 않는지 확인했습니다.
  • 제품 비용을 고려하여 4홉 총이익 및 이익률을 계산했습니다(모든 캠페인에서 약 51.9%).
  • 순수 ISO GQL로 쇼핑객의 여정을 추적하고 BigQuery Studio에서 시각화했습니다.
  • 두 가지 쿼리 스타일을 하나의 ROAS 스코어카드로 통합했습니다.
  • (선택사항) 그래프에서 대화형 분석 에이전트를 그라운딩하고 Gemini Enterprise에 게시했습니다.

다음 단계 및 추가 자료