๐Ÿ“Š Data Engineering

BigQuery

Google BigQuery

Google's serverless data warehouse. Petabyte-scale analytics.

Detailed Explanation

Google BigQuery is a fully managed, serverless data warehouse on Google Cloud Platform that can analyze petabyte-scale data with SQL. It scales automatically as needed without infrastructure management, and it supports standard SQL, so it can be used right away with existing SQL knowledge.

The core architecture of BigQuery is the separation of compute and storage. The Dremel-based distributed query engine processes in parallel across thousands of worker nodes, and the Colossus file system stores data in a columnar format. Thanks to this structure, storage and compute can be scaled independently, and flexible slot-based resource allocation is possible.

There are two pricing models: on-demand and capacity reservation. On-demand is billed by the amount of data processed ($5โ€“6.25 per TB) and suits intermittent use, while capacity reservation (slot-based) involves purchasing fixed compute capacity to process large-scale workloads at a predictable cost. Storage is divided into active data ($0.02/GB/month) and long-term data ($0.01/GB/month).

BigQuery lets you train machine learning models using only SQL with BigQuery ML, provides interactive analysis with sub-second responses through BigQuery BI Engine, and can analyze data in AWS/Azure through a single interface with BigQuery Omni. It integrates seamlessly with Google Cloud services such as GCS, Pub/Sub, and Dataflow.

Code Example

-- BigQuery SQL ์ฟผ๋ฆฌ ๋ฐ ๋น„์šฉ ์ตœ์ ํ™” ์˜ˆ์ œ

-- ============================================
-- 1. ๊ธฐ๋ณธ ๋ถ„์„ ์ฟผ๋ฆฌ
-- ============================================

-- ์ผ๋ณ„ ๋งค์ถœ ์ง‘๊ณ„ (ํŒŒํ‹ฐ์…˜ ํ™œ์šฉ)
SELECT
    DATE(order_timestamp) as order_date,
    product_category,
    COUNT(*) as order_count,
    SUM(order_amount) as total_revenue,
    AVG(order_amount) as avg_order_value,
    COUNT(DISTINCT customer_id) as unique_customers
FROM `project.dataset.orders`
WHERE order_timestamp BETWEEN '2024-01-01' AND '2024-01-31'
GROUP BY 1, 2
ORDER BY order_date, total_revenue DESC;

-- ============================================
-- 2. ๋น„์šฉ ์ตœ์ ํ™” ๊ธฐ๋ฒ•
-- ============================================

-- [1] ํ•„์š”ํ•œ ์ปฌ๋Ÿผ๋งŒ ์„ ํƒ (SELECT * ์ง€์–‘)
-- Bad: ์ „์ฒด ํ…Œ์ด๋ธ” ์Šค์บ”
SELECT * FROM `project.dataset.orders`;

-- Good: ํ•„์š”ํ•œ ์ปฌ๋Ÿผ๋งŒ ์„ ํƒ
SELECT order_id, customer_id, order_amount
FROM `project.dataset.orders`;

-- [2] ํŒŒํ‹ฐ์…˜ ํ•„ํ„ฐ ํ™œ์šฉ
-- Bad: ํŒŒํ‹ฐ์…˜ ํ”„๋ฃจ๋‹ ์—†์Œ
SELECT * FROM `project.dataset.orders`
WHERE EXTRACT(MONTH FROM order_timestamp) = 1;

-- Good: ํŒŒํ‹ฐ์…˜ ํ”„๋ฃจ๋‹ ํ™œ์„ฑํ™”
SELECT * FROM `project.dataset.orders`
WHERE order_timestamp >= '2024-01-01'
  AND order_timestamp < '2024-02-01';

-- [3] ํด๋Ÿฌ์Šคํ„ฐ๋ง ํ™œ์šฉ
-- ์ž์ฃผ ํ•„ํ„ฐ/๊ทธ๋ฃนํ•˜๋Š” ์ปฌ๋Ÿผ์œผ๋กœ ํด๋Ÿฌ์Šคํ„ฐ๋ง
CREATE OR REPLACE TABLE `project.dataset.orders_clustered`
PARTITION BY DATE(order_timestamp)
CLUSTER BY customer_id, product_category
AS SELECT * FROM `project.dataset.orders`;

-- [4] Dry Run์œผ๋กœ ๋น„์šฉ ์˜ˆ์ธก
-- bq query --dry_run์œผ๋กœ ์ฒ˜๋ฆฌํ•  ๋ฐ”์ดํŠธ ํ™•์ธ
-- ๋˜๋Š” BigQuery Console์—์„œ ์ฟผ๋ฆฌ ๊ฒ€์ฆ

-- ============================================
-- 3. ์œˆ๋„์šฐ ํ•จ์ˆ˜ ํ™œ์šฉ
-- ============================================

-- ๊ณ ๊ฐ๋ณ„ ๊ตฌ๋งค ์ˆœ์„œ ๋ฐ ๋ˆ„์  ๊ธˆ์•ก
SELECT
    customer_id,
    order_id,
    order_timestamp,
    order_amount,
    ROW_NUMBER() OVER (
        PARTITION BY customer_id
        ORDER BY order_timestamp
    ) as purchase_sequence,
    SUM(order_amount) OVER (
        PARTITION BY customer_id
        ORDER BY order_timestamp
        ROWS UNBOUNDED PRECEDING
    ) as cumulative_spend,
    LAG(order_timestamp) OVER (
        PARTITION BY customer_id
        ORDER BY order_timestamp
    ) as previous_order_date,
    DATE_DIFF(
        DATE(order_timestamp),
        DATE(LAG(order_timestamp) OVER (
            PARTITION BY customer_id
            ORDER BY order_timestamp
        )),
        DAY
    ) as days_since_last_order
FROM `project.dataset.orders`
ORDER BY customer_id, order_timestamp;

-- ============================================
-- 4. ARRAY ๋ฐ STRUCT ์ฒ˜๋ฆฌ
-- ============================================

-- ์ค‘์ฒฉ ๋ฐ์ดํ„ฐ ์ฟผ๋ฆฌ
SELECT
    user_id,
    event_date,
    event_name,
    -- STRUCT์—์„œ ๊ฐ’ ์ถ”์ถœ
    event_params.value.string_value as page_location,
    -- ARRAY ํ’€๊ธฐ
    item.item_name,
    item.price
FROM `project.dataset.events`,
    UNNEST(event_params) as event_params,
    UNNEST(items) as item
WHERE event_params.key = 'page_location'
  AND event_date = '2024-01-15';

-- ARRAY_AGG๋กœ ๊ทธ๋ฃนํ™”
SELECT
    customer_id,
    ARRAY_AGG(STRUCT(
        product_id,
        product_name,
        order_amount
    ) ORDER BY order_timestamp LIMIT 5) as recent_purchases
FROM `project.dataset.orders` o
JOIN `project.dataset.products` p USING (product_id)
GROUP BY customer_id;

-- ============================================
-- 5. ๊ทผ์‚ฌ ์ง‘๊ณ„ (๋น„์šฉ/์„ฑ๋Šฅ ์ตœ์ ํ™”)
-- ============================================

-- ์ •ํ™•ํ•œ COUNT DISTINCT (๋น„์šฉ ๋†’์Œ)
SELECT COUNT(DISTINCT user_id) as exact_users
FROM `project.dataset.events`;

-- ๊ทผ์‚ฌ COUNT DISTINCT (๋” ๋น ๋ฅด๊ณ  ์ €๋ ด)
SELECT APPROX_COUNT_DISTINCT(user_id) as approx_users
FROM `project.dataset.events`;

-- HyperLogLog++ ํ™œ์šฉ
SELECT
    DATE(event_timestamp) as event_date,
    APPROX_COUNT_DISTINCT(user_id) as daily_users,
    APPROX_QUANTILES(session_duration, 100)[OFFSET(50)] as median_duration,
    APPROX_QUANTILES(session_duration, 100)[OFFSET(95)] as p95_duration
FROM `project.dataset.sessions`
GROUP BY event_date;

-- ============================================
-- 6. BigQuery ML (SQL๋กœ ML)
-- ============================================

-- ๊ณ ๊ฐ ์„ธ๊ทธ๋จผํ…Œ์ด์…˜ ๋ชจ๋ธ ํ•™์Šต
CREATE OR REPLACE MODEL `project.dataset.customer_segments`
OPTIONS (
    model_type = 'KMEANS',
    num_clusters = 5,
    standardize_features = TRUE
) AS
SELECT
    customer_id,
    COUNT(*) as order_count,
    SUM(order_amount) as total_spend,
    AVG(order_amount) as avg_order_value,
    DATE_DIFF(CURRENT_DATE(), MAX(DATE(order_timestamp)), DAY) as recency_days,
    DATE_DIFF(
        MAX(DATE(order_timestamp)),
        MIN(DATE(order_timestamp)),
        DAY
    ) as customer_lifetime_days
FROM `project.dataset.orders`
GROUP BY customer_id
HAVING order_count >= 2;

-- ๋ชจ๋ธ๋กœ ์˜ˆ์ธก
SELECT
    customer_id,
    CENTROID_ID as segment,
    total_spend,
    order_count
FROM ML.PREDICT(
    MODEL `project.dataset.customer_segments`,
    (
        SELECT
            customer_id,
            COUNT(*) as order_count,
            SUM(order_amount) as total_spend,
            AVG(order_amount) as avg_order_value,
            DATE_DIFF(CURRENT_DATE(), MAX(DATE(order_timestamp)), DAY) as recency_days,
            DATE_DIFF(
                MAX(DATE(order_timestamp)),
                MIN(DATE(order_timestamp)),
                DAY
            ) as customer_lifetime_days
        FROM `project.dataset.orders`
        GROUP BY customer_id
    )
);

-- ============================================
-- 7. ์Šค์ผ€์ค„ ์ฟผ๋ฆฌ ๋ฐ Materialized View
-- ============================================

-- Materialized View ์ƒ์„ฑ (์ž๋™ ์ƒˆ๋กœ๊ณ ์นจ)
CREATE MATERIALIZED VIEW `project.dataset.daily_sales_mv`
OPTIONS (
    enable_refresh = TRUE,
    refresh_interval_minutes = 60
) AS
SELECT
    DATE(order_timestamp) as order_date,
    product_category,
    SUM(order_amount) as total_revenue,
    COUNT(*) as order_count
FROM `project.dataset.orders`
GROUP BY 1, 2;

-- ============================================
-- 8. Python ํด๋ผ์ด์–ธํŠธ ์˜ˆ์ œ
-- ============================================
"""
from google.cloud import bigquery
import pandas as pd

# ํด๋ผ์ด์–ธํŠธ ์ƒ์„ฑ
client = bigquery.Client(project='your-project-id')

# ์ฟผ๋ฆฌ ์‹คํ–‰ (๋น„์šฉ ์˜ˆ์ธก)
query = '''
SELECT product_category, SUM(order_amount) as revenue
FROM `project.dataset.orders`
WHERE order_timestamp >= '2024-01-01'
GROUP BY product_category
ORDER BY revenue DESC
LIMIT 10
'''

# Dry run์œผ๋กœ ๋น„์šฉ ์˜ˆ์ธก
job_config = bigquery.QueryJobConfig(dry_run=True, use_query_cache=False)
dry_run_job = client.query(query, job_config=job_config)
print(f"์˜ˆ์ƒ ์ฒ˜๋ฆฌ ๋ฐ”์ดํŠธ: {dry_run_job.total_bytes_processed:,}")
print(f"์˜ˆ์ƒ ๋น„์šฉ: ${dry_run_job.total_bytes_processed / 1e12 * 5:.4f}")

# ์‹ค์ œ ์ฟผ๋ฆฌ ์‹คํ–‰
df = client.query(query).to_dataframe()
print(df)

# ๋ฐ์ดํ„ฐ ์ ์žฌ
table_id = 'project.dataset.new_table'
job_config = bigquery.LoadJobConfig(
    write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
    source_format=bigquery.SourceFormat.PARQUET,
)

# GCS์—์„œ ์ ์žฌ
uri = 'gs://bucket/path/to/file.parquet'
load_job = client.load_table_from_uri(uri, table_id, job_config=job_config)
load_job.result()

# DataFrame์—์„œ ์ง์ ‘ ์ ์žฌ
job_config = bigquery.LoadJobConfig(
    write_disposition=bigquery.WriteDisposition.WRITE_APPEND,
)
client.load_table_from_dataframe(df, table_id, job_config=job_config).result()
"""

How it is used in practice

Data Analyst: "BigQuery costs went up 50% compared to last month, and I can't tell where the problem is."

Data Engineer: "Shall we check the cost per query with INFORMATION_SCHEMA.JOBS? Usually, using SELECT * or doing a full scan without a partition filter makes costs spike."

Data Analyst: "When I do ad-hoc analysis, I sometimes forget to include a partition filter."

Data Engineer: "If you set the require_partition_filter option on the table, queries can't run without a partition filter. Also, if you build frequently used aggregations as Materialized Views, you can reduce costs significantly."

Interviewer: "Please explain strategies for optimizing costs in BigQuery."

Candidate: "The key is to reduce the amount of data scanned. First, avoid SELECT * and select only the columns you need. Second, use date-based partitioning and clustering on frequently filtered columns. Third, use approximate functions such as APPROX_COUNT_DISTINCT to save costs by slightly sacrificing accuracy. Fourth, precompute recurring aggregations with Materialized Views or scheduled queries. Finally, if the workload is predictable, you can use Flex Slots or reservations to pay less than on-demand."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "COUNT(DISTINCT user_id) is being run on a 10TB table. It's going to cost quite a bit."

Developer: "I don't need an exact figure. I just need to know the approximate DAU."

Reviewer: "Then switch to APPROX_COUNT_DISTINCT. With an error rate under 1%, it's much faster and cheaper. Also, this query seems to run every day, so if you build it as a Materialized View with incremental updates, costs drop significantly."

Cautions

Related Terms

Learn More