1. Giriş
Bu codelab'de, BigQuery Studio'nun tanıdık arayüzünde veri dönüşümü için Apache Spark'ın gücünden nasıl yararlanacağınızı öğreneceksiniz. BigQuery'den veri okuyacak, PySpark kullanarak veri temizleme ve dönüştürme işlemlerini gerçekleştirecek ve sonuçları yeni bir BigQuery tablosuna geri yazacaksınız. Tüm bu işlemler tek bir not defterinden yapılabilir.
Bu codelab'de aşağıdaki gibi adım adım bir yaklaşım kullanacaksınız:
- Google Cloud projenizi hazırlayın ve gerekli tüm API'leri etkinleştirin.
- Geçici klasör için GCS paketi oluşturma
- Apache Spark'ı çalıştırmak için gerekli kitaplıkları içe aktarın.
- BigQuery bağlayıcısı ile Spark oturumunu başlatma
- BigQuery herkese açık veri kümesinden Google Analytics örnek verilerini okuma
- Cihaz tarayıcısına göre toplu verilerle verileri dönüştürme (temel metrikler)
- Gelir hesaplamalarıyla trafik kaynağı analizi kullanarak verileri dönüştürme
- Coğrafi analizle verileri dönüştürme
- Dönüştürme işleminden sonra verileri BigQuery tablosuna yazma
Mimariye Genel Bakış
Ön koşullar
- Faturalandırmanın etkin olduğu bir Google Cloud Platform (GCP) projesi.
- GCP projenizde BigQuery API ve BigQuery Connection API etkinleştirilmiş olmalıdır.
- SQL ve Python hakkında temel düzeyde bilgi
Neler öğreneceksiniz?
- BigQuery Studio Notebook'ta Apache Spark kullanarak verileri ayıklama
- BigQuery Studio Notebook'ta Apache Spark kullanarak verileri dönüştürme veya toplama
- BigQuery Studio Notebook'ta Apache Spark kullanarak verileri dönüştürdükten veya topladıktan sonra verileri yazma
Gerekenler
- Chrome web tarayıcısı
- Gmail hesabı
- Faturalandırmanın etkin olduğu bir Cloud projesi
2. Temel kurulum ve şartlar
Kendi hızınızda ortam kurulumu
- Google Cloud Console'da oturum açın ve yeni bir proje oluşturun veya mevcut bir projeyi yeniden kullanın. Henüz bir Gmail veya Google Workspace hesabınız yoksa oluşturmanız gerekir.
- Proje adı, bu projenin katılımcıları için görünen addır. Google API'leri tarafından kullanılmayan bir karakter dizesidir. Bu bilgiyi istediğiniz zaman güncelleyebilirsiniz.
- Proje kimliği, tüm Google Cloud projelerinde benzersizdir ve sabittir (ayarlandıktan sonra değiştirilemez). Cloud Console, benzersiz bir dizeyi otomatik olarak oluşturur. Genellikle bu dizenin ne olduğuyla ilgilenmezsiniz. Çoğu codelab'de proje kimliğinize (genellikle
PROJECT_ID
olarak tanımlanır) başvurmanız gerekir. Oluşturulan kimliği beğenmezseniz başka bir rastgele kimlik oluşturabilirsiniz. Dilerseniz kendi adınızı deneyerek kullanılabilir olup olmadığını kontrol edebilirsiniz. Bu adım tamamlandıktan sonra değiştirilemez ve proje süresince geçerli kalır. - Bazı API'lerin kullandığı üçüncü bir değer olan Proje Numarası da vardır. Bu üç değer hakkında daha fazla bilgiyi belgelerde bulabilirsiniz.
- Ardından, Cloud kaynaklarını/API'lerini kullanmak için Cloud Console'da faturalandırmayı etkinleştirmeniz gerekir. Bu codelab'i tamamlamak neredeyse hiç maliyetli değildir. Bu eğitimin ötesinde faturalandırılmayı önlemek için kaynakları kapatmak üzere oluşturduğunuz kaynakları veya projeyi silebilirsiniz. Yeni Google Cloud kullanıcıları 300 ABD doları değerinde ücretsiz deneme programından yararlanabilir.
3. Başlamadan önce
API'yi etkinleştirme
BigQuery Studio Not Defterleri'ni kullanmadan önce aşağıdaki API'leri etkinleştirmemiz gerekir:
- Compute Engine API
- Dataform API
- Vertex AI API
Manuel etkinleştirme için BigQuery'ye gidin. Düzenleyici bölmesinin sekme çubuğunda, + işaretinin yanındaki açılır oku tıklayın, işaretçiyi Notebook'un üzerine getirin ve BigQuery şablonu, Boş not defteri veya Spark şablonu'nu seçin.
Temel özellik API'sini etkinleştir penceresinde, BigQuery Unified API'de Etkinleştir'i tıklayın.
İşlemi tamamladıktan sonra etkinleştirin ve Kapat'ı tıklayın. Daha fazla bilgi için lütfen Öğe yönetimi için BigQuery Studio'yu etkinleştirme başlıklı makaleyi inceleyin.
4. Herkese açık bir veri kümesini okuma
Öncelikle, BigQuery Studio not defterlerinde Spark'ı çalıştırabilmek için geçici kullanıma yönelik bir GCS paketi oluşturacağız.
- Google Cloud Console'da BigQuery'ye gidin.
- Düzenleyici bölmesinin sekme çubuğunda, + işaretinin yanındaki açılır oku tıklayın, işaretçiyi Not Defteri'nin üzerine getirin ve Boş Not Defteri'ni seçin.
- Kod hücresini tıklayın, ardından GCS grubu oluşturmak için aşağıdaki CLI komut dosyasını yazın, ardından Hücreyi çalıştır düğmesini tıklayın veya Üst Karakter + Enter tuşlarına basın.
!gsutil mb -p <your_project_id> -c STANDARD -l US gs://ioxid2025-<your_project_id>
Google Cloud projesini oluştururken seçtiklerinize göre <your_project_id> değerlerini güncelleyin. GCS'de benzersiz paket adı oluşturmak için <your_project_id> değerlerini proje kimliğinizle güncelleyin. Ardından, kod hücresini çalıştırmak için Hücreyi çalıştır düğmesini tıklayın veya üst karakter + Enter tuşlarına basın.
Ardından, bir Spark oturumu başlatacağız. Bu codelab'de, BigQuery Studio Notebook'ta Spark'ı çalıştırmak için Dataproc özelliklerinden yararlanmak üzere DataprocSession
kullanabilsek de SparkSession
kitaplığını kullanacağız.
- Kod hücresini tıklayın ve Spark oturumunu başlatmak için aşağıdaki CLI komut dosyasını yazın. Hücreyi çalıştır düğmesini tıklayın veya üst karakter + enter tuşlarına basın.
# Import required libraries
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count, countDistinct, when, expr, date_format
from pyspark.sql.types import DecimalType
# Initialize Spark session with BigQuery connector
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count, countDistinct, when, expr, date_format
from pyspark.sql.types import DecimalType
# Initialize Spark session with BigQuery connector
spark = SparkSession.builder \
.appName("Google Analytics ETL with Apache Spark") \
.config("spark.jars.packages", "com.google.cloud.spark:spark-bigquery-with-dependencies_2.12:0.32.0") \
.getOrCreate()
spark
Beklenen Çıkış :
SparkSession - in-memory SparkContext Spark UI Version v3.5.4 Master local[*] AppName Google Analytics ETL with Apache Spark
- Kod hücresini tıklayın, ardından GCP projesini ve GCS geçici paketini ayarlamak için aşağıdaki CLI komut dosyasını yazın.
# Set GCP project and temporary bucket
project_id = "your-gcp-project-id" # Replace with your GCP project ID
bucket = "your-gcs-bucket" # Replace with your GCS bucket for temporary files spark.conf.set("temporaryGcsBucket", bucket)
Google Analytics Örnek Veritabanı
Google Analytics Örnek Veritabanı, Google Cloud'un herkese açık veri kümesi programı aracılığıyla BigQuery'de sağlanır. Veri kümesi, BigQuery'de Google markalı ürünler satan gerçek bir e-ticaret mağazası olan Google Merchandise Store 'dan alınmış ve kod karartma uygulanmış 12 aylık (Ağustos 2016 - Ağustos 2017) Google Analytics 360 verilerini sağlar. Bu sayede iş verilerini analiz edebilir ve Analytics 360 verilerini analiz etmek için BigQuery kullanmanın avantajlarını öğrenebilirsiniz. Veriler hakkında daha fazla bilgi edinin.
Veriler, normal bir e-ticaret web sitesinde görebileceğiniz cinstendir ve aşağıdaki bilgileri içerir:
- Trafik kaynağı verileri: Web sitesi ziyaretçilerinin geldiği kaynaklarla ilgili bilgiler (organik trafik, ücretli arama trafiği ve görüntülü reklam trafiğiyle ilgili veriler dahil)
- İçerik verileri: Kullanıcıların sitedeki davranışları hakkında bilgiler (ör. ziyaretçilerin baktığı sayfaların URL'leri, içerikle nasıl etkileşim kurdukları vb.)
- İşlem verileri: Google Merchandise Store web sitesindeki işlemlerle ilgili bilgilerdir.
Apache Spark'ta örnek ilk 5 veriyi görüntülemek için aşağıdaki kodu çalıştırın.
# EXTRACT: Read data from BigQuery
print("Extracting data from BigQuery...")
ga_df = spark.read.format("bigquery") \
.option("table", "bigquery-public-data.google_analytics_sample.ga_sessions_20170801") \
.load()
# Show schema sample data
print("Sample data:")
ga_df.show(5, truncate=False)
Beklenen çıktı :
Extracting data from BigQuery... Sample data: +---------+-----------+----------+--------------+--------+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------+------+--------+---------------+--------------------+ |visitorId|visitNumber|visitId |visitStartTime|date |totals |trafficSource |device |geoNetwork |customDimensions |hits |fullVisitorId |userId|clientId|channelGrouping|socialEngagementType| +---------+-----------+----------+--------------+--------+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------+------+--------+---------------+--------------------+ |NULL |1 |1501591568|1501591568 |20170801|{1, 1, 1, NULL, 1, NULL, NULL, 1, NULL, NULL, NULL, NULL, 1} |{NULL, (not set), (direct), (none), NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, not available in demo dataset, NULL, NULL, NULL, NULL, NULL}, NULL, NULL} |{Chrome, not available in demo dataset, not available in demo dataset, Windows, not available in demo dataset, false, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, NULL, not available in demo dataset, not available in demo dataset, not available in demo dataset, desktop} |{Europe, Southern Europe, Greece, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, tellas.gr, not available in demo dataset, not available in demo dataset, not available in demo dataset} |[] |[{1, 0, 5, 46, NULL, true, true, true, https://www.google.gr/, {/google+redesign/bags/google+zipper+front+sports+bag.axd, shop.googlemerchandisestore.com, Page Unavailable, NULL, NULL, /google+redesign/, /bags/, /google+zipper+front+sports+bag.axd, }, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, shop.googlemerchandisestore.com/google+redesign/bags/google+zipper+front+sports+bag.axd, shop.googlemerchandisestore.com/google+redesign/bags/google+zipper+front+sports+bag.axd, shop.googlemerchandisestore.com/google+redesign/bags/google+zipper+front+sports+bag.axd, 0}, {NULL, true, NULL, NULL}, NULL, [], [], NULL, NULL, {0, 1, NULL}, [], NULL, [], [], [], PAGE, {NULL, NULL, NULL, NULL, (not set), NULL, No, : }, NULL, NULL, {(not set), Bags, (not set), (not set), (not set), (entrance), (entrance), (entrance), (entrance), (entrance), NULL, 1, NULL, NULL, NULL}, web, []}] |3418334011779872055|NULL |NULL |Organic Search |Not Socially Engaged| |NULL |2 |1501589647|1501589647 |20170801|{1, 1, 1, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1}|{/analytics/web/, (not set), analytics.google.com, referral, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, not available in demo dataset, NULL, NULL, NULL, NULL, NULL}, NULL, NULL}|{Chrome, not available in demo dataset, not available in demo dataset, Windows, not available in demo dataset, false, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, NULL, not available in demo dataset, not available in demo dataset, not available in demo dataset, desktop} |{Asia, Southern Asia, India, Maharashtra, (not set), Mumbai, not available in demo dataset, unknown.unknown, not available in demo dataset, not available in demo dataset, not available in demo dataset} |[{4, APAC}] |[{1, 0, 5, 14, NULL, true, true, true, https://analytics.google.com/analytics/web/, {/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com, Page Unavailable, NULL, NULL, /google+redesign/, /shop+by+brand/, /youtube, }, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, 0}, {NULL, true, NULL, NULL}, NULL, [], [], NULL, NULL, {0, 1, NULL}, [], NULL, [], [], [], PAGE, {NULL, NULL, NULL, NULL, (not set), NULL, No, : }, NULL, NULL, {(not set), Brands, (not set), (not set), (not set), (entrance), (entrance), (entrance), (entrance), (entrance), NULL, 1, NULL, NULL, NULL}, web, []}] |2474397855041322408|NULL |NULL |Referral |Not Socially Engaged| |NULL |1 |1501616621|1501616621 |20170801|{1, 1, 1, NULL, 1, NULL, NULL, 1, NULL, NULL, NULL, NULL, 1} |{/analytics/web/, (not set), analytics.google.com, referral, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, not available in demo dataset, NULL, NULL, NULL, NULL, NULL}, NULL, NULL}|{Chrome, not available in demo dataset, not available in demo dataset, Windows, not available in demo dataset, false, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, NULL, not available in demo dataset, not available in demo dataset, not available in demo dataset, desktop} |{Europe, Northern Europe, United Kingdom, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, as9105.com, not available in demo dataset, not available in demo dataset, not available in demo dataset} |[{4, EMEA}] |[{1, 0, 12, 43, NULL, true, true, true, https://analytics.google.com/analytics/web/?utm_source=demoaccount&utm_medium=demoaccount&utm_campaign=demoaccount, {/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com, Page Unavailable, NULL, NULL, /google+redesign/, /shop+by+brand/, /youtube, }, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, 0}, {NULL, true, NULL, NULL}, NULL, [], [], NULL, NULL, {0, 1, NULL}, [], NULL, [], [], [], PAGE, {NULL, NULL, NULL, NULL, (not set), NULL, No, : }, NULL, NULL, {(not set), Brands, (not set), (not set), (not set), (entrance), (entrance), (entrance), (entrance), (entrance), NULL, 1, NULL, NULL, NULL}, web, []}]|5870462820713110108|NULL |NULL |Referral |Not Socially Engaged| |NULL |1 |1501601200|1501601200 |20170801|{1, 1, 1, NULL, 1, NULL, NULL, 1, NULL, NULL, NULL, NULL, 1} |{/analytics/web/, (not set), analytics.google.com, referral, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, not available in demo dataset, NULL, NULL, NULL, NULL, NULL}, NULL, NULL}|{Firefox, not available in demo dataset, not available in demo dataset, Windows, not available in demo dataset, false, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, NULL, not available in demo dataset, not available in demo dataset, not available in demo dataset, desktop}|{Americas, Northern America, United States, Texas, Dallas-Ft. Worth TX, Dallas, not available in demo dataset, h5colo.com, not available in demo dataset, not available in demo dataset, not available in demo dataset} |[{4, North America}]|[{1, 0, 8, 26, NULL, true, true, true, https://analytics.google.com/analytics/web/, {/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com, Page Unavailable, NULL, NULL, /google+redesign/, /shop+by+brand/, /youtube, }, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, 0}, {NULL, true, NULL, NULL}, NULL, [], [], NULL, NULL, {0, 1, NULL}, [], NULL, [], [], [], PAGE, {NULL, NULL, NULL, NULL, (not set), NULL, No, : }, NULL, NULL, {(not set), Brands, (not set), (not set), (not set), (entrance), (entrance), (entrance), (entrance), (entrance), NULL, 1, NULL, NULL, NULL}, web, []}] |9397809171349480379|NULL |NULL |Referral |Not Socially Engaged| |NULL |1 |1501615525|1501615525 |20170801|{1, 1, 1, NULL, 1, NULL, NULL, 1, NULL, NULL, NULL, NULL, 1} |{/analytics/web/, (not set), adwords.google.com, referral, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, not available in demo dataset, NULL, NULL, NULL, NULL, NULL}, NULL, NULL} |{Chrome, not available in demo dataset, not available in demo dataset, Windows, not available in demo dataset, false, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, NULL, not available in demo dataset, not available in demo dataset, not available in demo dataset, desktop} |{Americas, Northern America, United States, not available in demo dataset, not available in demo dataset, not available in demo dataset, not available in demo dataset, (not set), not available in demo dataset, not available in demo dataset, not available in demo dataset}|[{4, North America}]|[{1, 0, 12, 25, NULL, true, true, true, https://adwords.google.com/analytics/web/?__o=cues&authuser=0, {/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com, Page Unavailable, NULL, NULL, /google+redesign/, /shop+by+brand/, /youtube, }, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, shop.googlemerchandisestore.com/google+redesign/shop+by+brand/youtube, 0}, {NULL, true, NULL, NULL}, NULL, [], [], NULL, NULL, {0, 1, NULL}, [], NULL, [], [], [], PAGE, {NULL, NULL, NULL, NULL, (not set), NULL, No, : }, NULL, NULL, {(not set), Brands, (not set), (not set), (not set), (entrance), (entrance), (entrance), (entrance), (entrance), NULL, 1, NULL, NULL, NULL}, web, []}] |6089902943184578335|NULL |NULL |Referral |Not Socially Engaged| +---------+-----------+----------+--------------+--------+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------+------+--------+---------------+--------------------+ only showing top 5 rows
5. Cihaz tarayıcısına göre veri toplama (temel metrikler)
Bu kod, Google Analytics verilerini cihaz tarayıcısına göre toplar, toplam oturum, ziyaret, isabet, sayfa görüntüleme, hemen çıkma, sitede kalma süresi, benzersiz ziyaretçi ve ziyaret başına ortalama süre gibi çeşitli metrikleri hesaplar, ardından bir sütunu yeniden adlandırır ve sonuçları sıralar.
print("Transformation 1: Aggregating by device browser...")
device_agg = ga_df.groupBy("device.browser") \
.agg(
count("*").alias("total_sessions"),
sum("totals.visits").alias("total_visits"),
sum("totals.hits").alias("total_hits"),
sum("totals.pageviews").alias("total_pageviews"),
sum("totals.bounces").alias("total_bounces"),
sum("totals.timeOnSite").alias("total_time_on_site"),
countDistinct("fullVisitorId").alias("unique_visitors"),
(sum("totals.timeOnSite")/sum("totals.visits")).alias("avg_time_per_visit")
) \
.withColumnRenamed("browser", "device_browser") \
.orderBy("total_sessions", ascending=False)
# Show sample transformed data
print("\nDevice Aggregation Sample:")
device_agg.show(5)
Beklenen çıktı :
Transformation 1: Aggregating by device browser... Device Aggregation Sample: +-----------------+--------------+------------+----------+---------------+-------------+------------------+---------------+------------------+ | device_browser|total_sessions|total_visits|total_hits|total_pageviews|total_bounces|total_time_on_site|unique_visitors|avg_time_per_visit| +-----------------+--------------+------------+----------+---------------+-------------+------------------+---------------+------------------+ | Chrome| 1900| 1900| 10896| 8956| 870| 354691| 1689|186.67947368421054| | Safari| 397| 397| 1260| 1137| 218| 43150| 364|108.69017632241814| | Firefox| 101| 101| 390| 343| 59| 10659| 95|105.53465346534654| |Internet Explorer| 54| 54| 107| 102| 36| 5589| 50| 103.5| | Edge| 23| 23| 63| 55| 12| 2623| 23|114.04347826086956| +-----------------+--------------+------------+----------+---------------+-------------+------------------+---------------+------------------+ only showing top 5 rows
6. Gelir hesaplamalarıyla trafik kaynağını analiz etme
Bu kod, Google Analytics verilerini trafik kaynağına ve aracıya göre analiz eder. Oturum sayısı, işlemler, toplam gelir, oturum başına gelir ve benzersiz ziyaretçi sayısı gibi metrikleri hesaplar, ardından sütunları yeniden adlandırır ve sonuçları toplam gelire göre sıralar.
print("Transformation 2: Analyzing traffic sources...")
traffic_source_agg = ga_df.groupBy("trafficSource.source", "trafficSource.medium") \
.agg(
count("*").alias("session_count"),
sum(when(col("totals.transactions").isNotNull(), 1).otherwise(0)).alias("transactions"),
sum("totals.totalTransactionRevenue").cast(DecimalType(20,2)).alias("total_revenue"),
(sum("totals.totalTransactionRevenue")/count("*")).cast(DecimalType(10,2)).alias("revenue_per_session"),
countDistinct("fullVisitorId").alias("unique_visitors")
) \
.withColumnRenamed("source", "traffic_source") \
.withColumnRenamed("medium", "traffic_medium") \
.orderBy("total_revenue", ascending=False)
print("\nTraffic Source Aggregation Sample:")
traffic_source_agg.show(5)
Beklenen çıktı :
Transformation 2: Analyzing traffic sources... Traffic Source Aggregation Sample: +--------------------+--------------+-------------+------------+-------------+-------------------+---------------+ | traffic_source|traffic_medium|session_count|transactions|total_revenue|revenue_per_session|unique_visitors| +--------------------+--------------+-------------+------------+-------------+-------------------+---------------+ | (direct)| (none)| 2166| 42|8872040000.00| 4096048.01| 1943| | mail.google.com| referral| 2| 1| 17960000.00| 8980000.00| 2| | google.com.tw| referral| 1| 0| NULL| NULL| 1| |analytics.google.com| referral| 57| 0| NULL| NULL| 53| | quora.com| referral| 6| 0| NULL| NULL| 5| +--------------------+--------------+-------------+------------+-------------+-------------------+---------------+ only showing top 5 rows
7. Coğrafi analiz
Bu kod, Google Analytics verileri üzerinde ülke ve bölgeye göre coğrafi analiz gerçekleştirir. Oturum sayısı, toplam sayfa görüntüleme sayısı, sitede geçirilen toplam süre, oturum başına ortalama süre ve benzersiz ziyaretçi sayısını hesaplar. Ardından sütunları yeniden adlandırır ve oturum sayısına göre sıralar.
print("Transformation 3: Geographic analysis...")
geo_agg = ga_df.groupBy("geoNetwork.country", "geoNetwork.region") \
.agg(
count("*").alias("session_count"),
sum("totals.pageviews").alias("total_pageviews"),
sum("totals.timeOnSite").alias("total_time_on_site"),
(sum("totals.timeOnSite")/count("*")).alias("avg_time_per_session"),
countDistinct("fullVisitorId").alias("unique_visitors")
) \
.withColumnRenamed("country", "country") \
.withColumnRenamed("region", "region") \
.orderBy("session_count", ascending=False)
print("\nGeographic Aggregation Sample:")
geo_agg.show(5)
Beklenen çıktı :
Transformation 3: Geographic analysis... Geographic Aggregation Sample: +--------------+--------------------+-------------+---------------+------------------+--------------------+---------------+ | country| region|session_count|total_pageviews|total_time_on_site|avg_time_per_session|unique_visitors| +--------------+--------------------+-------------+---------------+------------------+--------------------+---------------+ | United States|not available in ...| 564| 2326| 97829| 173.45567375886526| 494| | United States| California| 420| 3102| 116563| 277.5309523809524| 347| | United States| New York| 109| 845| 39976| 366.7522935779817| 84| |United Kingdom|not available in ...| 82| 161| 7791| 95.01219512195122| 79| | India|not available in ...| 62| 139| 2869| 46.274193548387096| 61| +--------------+--------------------+-------------+---------------+------------------+--------------------+---------------+ only showing top 5 rows
8. Zamana dayalı analiz
Bu kod, visitStartTime
sütunundan saati çıkararak zamana dayalı analiz gerçekleştirir. Ardından, oturum sayısını, işlemleri, toplam geliri ve toplam sayfa görüntülemelerini hesaplamak için verileri saate göre gruplandırır ve sonuçları saate göre sıralar.
print("Transformation 4: Time-based analysis...")
hourly_agg = ga_df.withColumn("hour", date_format(col("visitStartTime").cast("timestamp"), "H")) \
.groupBy("hour") \
.agg(
count("*").alias("session_count"),
sum("totals.transactions").alias("transactions"),
sum("totals.totalTransactionRevenue").cast(DecimalType(20,2)).alias("total_revenue"),
sum("totals.pageviews").alias("total_pageviews")
) \
.orderBy("hour")
print("\nHourly Aggregation Sample:")
hourly_agg.show(5)
Beklenen Çıkış :
Transformation 4: Time-based analysis... Hourly Aggregation Sample: +----+-------------+------------+-------------+---------------+ |hour|session_count|transactions|total_revenue|total_pageviews| +----+-------------+------------+-------------+---------------+ | 0| 87| NULL| NULL| 372| | 1| 102| NULL| NULL| 494| | 10| 67| NULL| NULL| 149| | 11| 73| NULL| NULL| 167| | 12| 99| NULL| NULL| 313| +----+-------------+------------+-------------+---------------+ only showing top 5 rows
9. Sonucu BigQuery tablosuna yazma
Bu kod, dört toplu veri çerçevesini (device_agg
, traffic_source_agg
, geo_agg
ve hourly_agg
) doğrudan yazma yöntemini kullanarak Google BigQuery'deki ayrı tablolara aktarır ve mevcut tabloları varsa üzerine yazar.
# Write to BigQuery tables
print("\nLoading data to BigQuery...")
# Set output tables
device_output_table = f"{project_id}.analytics_sample.device_aggregation"
traffic_output_table = f"{project_id}.analytics_sample.traffic_source_aggregation"
geo_output_table = f"{project_id}.analytics_sample.geo_aggregation"
hourly_output_table = f"{project_id}.analytics_sample.hourly_aggregation"
dataset_id = "demo" # Replace with your BigQuery dataset ID
# Set BigQuery output table
device_output_table = f"{project_id}.{dataset_id}.device_aggregation"
traffic_output_table = f"{project_id}.{dataset_id}.traffic_source_aggregation"
geo_output_table = f"{project_id}.{dataset_id}.geo_aggregation"
hourly_output_table = f"{project_id}.{dataset_id}.hourly_aggregation"
# Write each DataFrame to BigQuery
device_agg.write \
.format("bigquery") \
.option("table", device_output_table) \
.option("writeMethod", "direct") \
.mode("overwrite") \
.save()
traffic_source_agg.write \
.format("bigquery") \
.option("table", traffic_output_table) \
.option("writeMethod", "direct") \
.mode("overwrite") \
.save()
geo_agg.write \
.format("bigquery") \
.option("table", geo_output_table) \
.option("writeMethod", "direct") \
.mode("overwrite") \
.save()
hourly_agg.write \
.format("bigquery") \
.option("table", hourly_output_table) \
.option("writeMethod", "direct") \
.mode("overwrite") \
.save()
Bazı dönüşümlerden sonra verilerin başarıyla kaydedildiğinden emin olmak için BigQuery'deki çıkış tablosunu kontrol edin.
device_aggregation tablosu
geo_aggregation tablosu
hourly_aggregation tablosu
traffic_source_aggregation
10. BigQuery Studio not defteri kodunu düzenleme (isteğe bağlı)
BigQuery Studio not defteri kodunu aşağıdaki şekillerde düzenleyebilirsiniz:
- Google Cloud Console'dan not defteri kodu planlayın ( not defteri fiyatlandırması geçerlidir).
- Not defteri kodunu Dataproc Serverless toplu iş yükü olarak çalıştırma ( Dataproc Serverless fiyatlandırması geçerlidir).
Bu codelab'de, Google Cloud Console'dan not defteri kodunu planlama özelliğini kullanacağız.
- Not defteri araç çubuğunda Planla'yı tıklayın.
- Not Defteri Planla bölmesindeki Plan adı alanına plan için bir ad girin.
- Kimlik doğrulama bölümünde, not defterini Google Hesabı kullanıcı kimlik bilgilerinizle veya bir hizmet hesabıyla yetkilendirin.
- Google Hesabı kullanıcı kimlik bilgilerinizi kullanmak için ( Önizleme) Kullanıcı kimlik bilgilerimle yürüt'ü seçin.
- Hizmet hesabı kullanmak için Seçili hizmet hesabıyla yürüt'ü ve ardından bir hizmet hesabını seçin.
- Notebook options (Not defteri seçenekleri) bölümündeki Runtime template (Çalışma zamanı şablonu) alanında bir Colab not defteri çalışma zamanı şablonu veya varsayılan çalışma zamanı özelliklerini seçin. Colab not defteri çalışma zamanı şablonu oluşturma hakkında ayrıntılı bilgi için Çalışma zamanı şablonu oluşturma başlıklı makaleyi inceleyin.
- Cloud Storage paketi alanında Göz at'ı tıklayın ve bir Cloud Storage paketi seçin veya oluşturun. Seçili hizmet hesabına, seçili pakette Depolama Yöneticisi (
roles/storage.admin
) IAM rolü verilmelidir. Daha fazla bilgi için Not defteri planlamayı etkinleştirme başlıklı makaleyi inceleyin. - Planlama sıklığı bölümünde aşağıdakileri yapın:
- Tekrarlanma menüsünde, planlanmış not defteri çalıştırmalarının sıklığını seçin.
- At time (Saat) alanına planlanmış not defteri çalıştırmalarının saatini girin.
- Saat dilimi menüsünde, planın saat dilimini seçin.
- Program oluştur'u tıklayın. Kimlik doğrulama yönteminiz için Kullanıcı kimlik bilgilerimle yürüt'ü seçtiyseniz Google Hesabınızı yetkilendirmeniz gerekir ( Önizleme).
11. Temizleme
Bu codelab'de kullanılan kaynaklar için Google Cloud hesabınızın ücretlendirilmesini istemiyorsanız şu adımları uygulayın:
- Google Cloud Console'da Kaynakları yönetin sayfasına gidin.
- Proje listesinde silmek istediğiniz projeyi seçin ve Sil'i tıklayın.
- İletişim kutusunda proje kimliğini yazın ve projeyi silmek için Kapat'ı tıklayın.
12. Tebrikler
BigQuery Studio not defterlerinde Apache Spark sunucusuz özelliğinden yararlanarak veri dönüşümlerini ve analizlerini tamamladınız. Bu süreçte Google Cloud'un herkese açık veri kümelerini keşfettiniz, BigQuery Studio Notebook'ta Apache Spark ile sunucusuz ETL gerçekleştirdiniz ve BigQuery Studio Notebook'u düzenlediniz. Tebrikler!
Sonraki adımlar :
- Otomasyon amacıyla hizmet hesabı kullanarak not defterini düzenleyin.
- ETL işi çalıştırıldığında süreyi izlemek için komut dosyası ekleyin.
- Not defterleri dağıtın.
- BigQuery Studio not defterlerinde sunucusuz Dataproc ile gerçek dağıtılmış Apache Spark özelliklerinden yararlanmak için DataprocSparkSession'ı kullanın.
- BigQuery Studio'da Apache Spark için saklanmış yordam oluşturun. Bu şekilde, daha iyi düzenleme, yeniden kullanılabilirlik ve sürdürülebilirlik için PySpark kodunuzu yapılandırmak üzere OOP ilkelerini uygulayabilirsiniz.
Referanslar :