<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emre Evcimen on Medium]]></title>
        <description><![CDATA[Stories by Emre Evcimen on Medium]]></description>
        <link>https://medium.com/@emreevcimen?source=rss-7b35c26c88e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Rnw5JJPbYQ_Mkk2NAKi-1A.jpeg</url>
            <title>Stories by Emre Evcimen on Medium</title>
            <link>https://medium.com/@emreevcimen?source=rss-7b35c26c88e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:49:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emreevcimen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spark ve Iceberg ile Uçtan Uca Data Lineage: OpenLineage, OpenMetadata, Marquez ve MCP]]></title>
            <link>https://emreevcimen.medium.com/spark-ve-iceberg-ile-u%C3%A7tan-uca-data-lineage-openlineage-openmetadata-marquez-ve-mcp-0344d86b3368?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0344d86b3368</guid>
            <category><![CDATA[marquez]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[openlineage]]></category>
            <category><![CDATA[open-metadata]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 05:01:11 GMT</pubDate>
            <atom:updated>2026-10-12T17:28:19.703Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar, bu yazımda sizlere OpenMetadata, OpenLineage ve Marquez kullanılarak mevcut yapınızdaki verilerin hikâyesini ve şeffaflığını nasıl sistemleştirebileceğinizi,LLM ve MCP yardımıyla bunu nasıl hızlı şekilde elde edebileceğinizi göstereceğim ancak buna geçmeden önce bazı sorulara cevap vermeliyiz.</p><p><strong>Neden veri yönetişimi?</strong></p><p>Veri yönetişimi, verinin kime ait olduğunu, ne anlama geldiğini, nereden geldiğini ve ne kadar güvenilir olduğunu kurala bağlamaktır. Tablo sayısı azken bu bilgi ekipteki birkaç kişinin kafasında taşınabilir. Tablolar, işler ve ekipler çoğaldıkça aynı bilgi kaybolur ve her soru bir araştırmaya dönüşür.</p><p>Yönetişim eksik olduğunda tipik olarak şunlar yaşanır:</p><ul><li><strong>Yanlış tablo kullanılır.</strong> Biri raporu ara katmandaki stg_product tablosundan çeker; tablo her çalıştırmada silinip yeniden yazıldığı için rapor zaman zaman boş görünür.</li><li><strong>Değişikliklerin etkisi bilinmez.</strong> Kaynak sistemde bir sütunun adı değişir; hangi tabloların ve raporların bozulacağı ancak bozulduktan sonra anlaşılır.</li><li><strong>Sorun geç fark edilir.</strong> İş hatasız biter ama eksik veri yazar; bunu ilk gören raporu okuyan kişi olur.</li><li><strong>Uyum soruları cevapsız kalır.</strong> KVKK ya da GDPR denetiminde “Kişisel veri hangi tablolara aktı?” sorusunun cevabı lineage olmadan verilemez.</li></ul><p><strong>Neden tablolar için metadata tutulmalı?</strong></p><p>Tablonun kendisi yalnızca veriyi taşır; o veriyi anlamlı ve güvenilir kılan bilgi metadatadır. Bu yazıda her tablo için dört tür metadata tutuluyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*URzNnGmsAKgjBVvwx05tlQ.png" /></figure><p>Bu bilgilerin elle güncellenen bir wiki sayfasında değil, işin kendisi tarafından üretilmesi gerekiyor. Aksi hâlde ilk kod değişikliğinde belge eskir ve kimse ona güvenmez.</p><p><strong>Neden OpenLineage, OpenMetadata ve Marquez birlikte?</strong></p><p>Bu üç araç aynı işi yapmıyor; her biri bir parçayı üstleniyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*2KJjksskDxoLBjaghJhZAA.png" /></figure><p><strong>OpenLineage </strong>lineage’ı kodun içinden çıkarıp otomatik hâle getiriyor; <strong>Spark </strong>işi her çalıştığında lineage kendiliğinden güncelleniyor. <strong>OpenMetadata </strong>bu lineage’ı iş anlamı ve kalite bilgisiyle birleştirerek “Bu tabloya güvenebilir miyim?” sorusuna cevap veriyor. <strong>Marquez</strong> ise “Bu tablo hangi çalıştırmayla, ne zaman, ne kadar sürede üretildi?” sorusunu cevaplıyor.</p><p><strong>Kullanılan Teknolojilerin Sürümleri:</strong></p><p>Spark 3.5.1 · Iceberg 1.5.0 · openlineage-spark 1.53.0 · OpenMetadata 2.0.3 · Marquez 0.50.0 · Python MCP SDK</p><p><strong>Mimari:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLckrX8-LJBoatKjaX1CDw.png" /></figure><p>Belirli sorulara cevap verip mimariyi de incelediğimize göre artık yapmamız gereken kurulumlara geçelim. Benim Linux makinemde Spark,Hdfs(Iceberg tables) ve Sql Server kurulu olarak mevcut zaten ek olarak kurmam gereken 2 servis vardı. Bunlar Openmetadata ve Marquez bunları da Docker servisini kullanarak ayağa kaldırdım.</p><p>Openmetadata için <a href="https://docs.open-metadata.org/v2.0.x/quick-start/local-docker-deployment">bu linki</a> takip edebilirsiniz. Buradaki adımları takip ettikten sonra docker compose ps dediğinizde aşağıdaki gibi bir çıktı elde etmelisiniz.</p><pre>[emre@DESKTOP-0F69LIK openmetadata-docker]$ docker compose ps<br>NAME                         COMMAND                  SERVICE               STATUS              PORTS<br>execute_migrate_all          &quot;/bin/bash ./bootstr…&quot;   execute-migrate-all   exited (0)<br>openmetadata_elasticsearch   &quot;/bin/tini -- /usr/l…&quot;   elasticsearch         running (healthy)   0.0.0.0:9200-&gt;9200/tcp, 0.0.0.0:9300-&gt;9300/tcp, :::9200-&gt;9200/tcp, :::9300-&gt;9300/tcp<br>openmetadata_ingestion       &quot;/bin/bash /opt/airf…&quot;   ingestion             running             0.0.0.0:8080-&gt;8080/tcp, :::8080-&gt;8080/tcp<br>openmetadata_mysql           &quot;/entrypoint.sh --so…&quot;   mysql                 running (healthy)   0.0.0.0:3306-&gt;3306/tcp, :::3306-&gt;3306/tcp<br>openmetadata_postgresql      &quot;docker-entrypoint.s…&quot;   postgresql            running (healthy)   0.0.0.0:5432-&gt;5432/tcp, :::5432-&gt;5432/tcp<br>openmetadata_server          &quot;/bin/bash /openmeta…&quot;   openmetadata-server   running (healthy)   0.0.0.0:8585-8586-&gt;8585-8586/tcp, :::8585-8586-&gt;8585-8586/tcp</pre><p>Marquez için de aşağıdaki gibi bir docker compose dosyası oluşturdum.</p><pre>version: &quot;3.9&quot;<br><br>services:<br>  marquez-db:<br>    image: postgres:14<br>    container_name: marquez-db<br>    environment:<br>      POSTGRES_USER: marquez<br>      POSTGRES_PASSWORD: marquez<br>      POSTGRES_DB: marquez<br>    volumes:<br>      - marquez-db-data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U marquez -d marquez&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 20<br>    restart: unless-stopped<br><br>  marquez-api:<br>    image: marquezproject/marquez:0.50.0<br>    container_name: marquez-api<br>    environment:<br>      MARQUEZ_PORT: 5000<br>      MARQUEZ_ADMIN_PORT: 5001<br>      POSTGRES_HOST: marquez-db<br>      POSTGRES_PORT: 5432<br>      POSTGRES_DB: marquez<br>      POSTGRES_USER: marquez<br>      POSTGRES_PASSWORD: marquez<br>      SEARCH_ENABLED: &quot;false&quot;<br>    ports:<br>      - &quot;5000:5000&quot;<br>      - &quot;5001:5001&quot;<br>    depends_on:<br>      marquez-db:<br>        condition: service_healthy<br>    restart: unless-stopped<br><br>  marquez-web:<br>    image: marquezproject/marquez-web:0.50.0<br>    container_name: marquez-web<br>    environment:<br>      MARQUEZ_HOST: marquez-api<br>      MARQUEZ_PORT: 5000<br>      WEB_PORT: 3000<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - marquez-api<br>    restart: unless-stopped<br><br>volumes:<br>  marquez-db-data:</pre><p>Sizde bu yaml dosyasını bir dizinde yaratıp daha sonrasında docker compose up -d komutunu çalıştırdığınızda aşağıdaki gibi bir çıktı elde etmelisiniz.</p><pre>[emre@DESKTOP-0F69LIK marquez]$ docker compose ps<br>NAME                COMMAND                  SERVICE             STATUS              PORTS<br>marquez-api         &quot;/usr/src/app/entryp…&quot;   marquez-api         running             0.0.0.0:5000-5001-&gt;5000-5001/tcp, :::5000-5001-&gt;5000-5001/tcp<br>marquez-db          &quot;docker-entrypoint.s…&quot;   marquez-db          running (healthy)   5432/tcp<br>marquez-web         &quot;/usr/src/app/entryp…&quot;   marquez-web         running             0.0.0.0:3000-&gt;3000/tcp, :::3000-&gt;3000/tcp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jn1qk1OU93TkYEvrrt3HzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuZbyt4ExidEVhp01aq2xQ.png" /></figure><p>Yukarıdaki portlara gidip ilgili servislerin başarılı bir şekilde ayağa kalktığını kontrol edebilirsiniz.</p><p>Bir de kodlarımızda kullanacağımız home dizini altında tutacağınız .om_token dosyası için de erişmeniz gereken bir sekme var Openmetadata &gt; Settings &gt; Bots &gt; ingestion-bot bu sekmedeki token’ı dosyaya kaydetmelisiniz.</p><p>Her şey hazır olduğuna göre, gelin sizle bir data pipeline akışı tasarlayalım ve bunu Openmetadata, OpenLineage ve Marquez ile entegre edelim.</p><pre>#!/usr/bin/env bash<br># Kullanım:<br>#   ./run_om_lineage.sh                     -&gt; ETL + lineage yayını (OpenMetadata, Marquez) + veri kalitesi + performans<br>#   OL_TRANSPORT=file ./run_om_lineage.sh   (lineage&#39;ı yalnızca dosyaya yaz, hiçbir yere gönderme)<br>#   SKIP_DQ=1 / SKIP_MARQUEZ=1 / SKIP_PERF=1  (ilgili adımı atla)<br>#   PERF_STRICT=1                           (performans sorunu varsa çıkış kodu 3)<br># Token: ~/.om_token (chmod 600) ya da OM_JWT_TOKEN ortam değişkeni<br>set -euo pipefail<br>cd &quot;$(dirname &quot;$0&quot;)&quot;<br><br>if [[ -z &quot;${OM_JWT_TOKEN:-}&quot; &amp;&amp; -f &quot;$HOME/.om_token&quot; ]]; then<br>  export OM_JWT_TOKEN=&quot;$(tr -d &#39;[:space:]&#39; &lt; &quot;$HOME/.om_token&quot;)&quot;<br>fi<br>export OM_URL=&quot;${OM_URL:-http://192.168.1.104:8585}&quot;<br>export MARQUEZ_URL=&quot;${MARQUEZ_URL:-http://192.168.1.104:5000}&quot;<br>[[ -n &quot;${SKIP_MARQUEZ:-}&quot; ]] &amp;&amp; export MARQUEZ_URL=&quot;&quot;<br>export OL_FILE=&quot;${OL_FILE:-/tmp/openlineage_events.ndjson}&quot;<br>OL_VERSION=&quot;${OL_VERSION:-1.53.0}&quot;<br>MASTER=&quot;${SPARK_MASTER:-local[*]}&quot;<br><br># spark-submit ile çalışırken paketler --packages ile verilmeli<br># (kod içindeki spark.jars.packages, JVM zaten açık olduğu için listener&#39;ı yükleyemez)<br>BASE_PKGS=&quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.5.0,com.microsoft.sqlserver:mssql-jdbc:12.2.0.jre8&quot;<br><br># Olay dosyası her çalıştırmada sıfırlanır (yalnızca bu çalıştırmanın olayları yayınlansın)<br>rm -f &quot;$OL_FILE&quot;<br><br>echo &quot;&gt;&gt;&gt; 1/4 ETL iş akışı (OpenLineage -&gt; yerel dosya)&quot;<br>spark-submit --master &quot;$MASTER&quot; \<br>  --packages &quot;${BASE_PKGS},io.openlineage:openlineage-spark_2.12:${OL_VERSION}&quot; \<br>  om_lineage_job.py<br><br>if [[ &quot;${OL_TRANSPORT:-http}&quot; != &quot;file&quot; ]]; then<br>  echo &quot;&gt;&gt;&gt; 2/4 Lineage yayını (OpenMetadata + Marquez)&quot;<br>  python3 ol_publish.py &quot;$OL_FILE&quot;<br>fi<br><br>DQ_EXIT=0<br>if [[ -z &quot;${SKIP_DQ:-}&quot; &amp;&amp; -n &quot;${OM_JWT_TOKEN:-}&quot; ]]; then<br>  echo &quot;&gt;&gt;&gt; 3/4 Veri kalitesi testleri + profil (OpenMetadata)&quot;<br>  # Testler başarısız olursa çıkış kodu 2 (zamanlayıcı/Airflow için kalite kapısı)<br>  spark-submit --master &quot;$MASTER&quot; --packages &quot;$BASE_PKGS&quot; om_quality.py run || DQ_EXIT=$?<br>fi<br><br>if [[ -z &quot;${SKIP_PERF:-}&quot; &amp;&amp; -n &quot;$MARQUEZ_URL&quot; ]]; then<br>  echo &quot;&gt;&gt;&gt; 4/4 Performans kontrolü (Marquez çalıştırma geçmişi)&quot;<br>  if ! python3 marquez_perf_check.py; then<br>    [[ -n &quot;${PERF_STRICT:-}&quot; ]] &amp;&amp; exit 3<br>  fi<br>fi<br><br>exit &quot;$DQ_EXIT&quot;</pre><p>Yukarıdaki sh dosyasında çalışan 4 scripti de aşağıda paylaşıyorum.</p><pre>&quot;&quot;&quot;<br>om_lineage_job.py<br>AdventureWorks -&gt; Apache Iceberg iş akışı<br>OpenLineage (openlineage-spark listener) ile OpenMetadata&#39;ya lineage gönderir.<br><br>Akış:<br>  SQL Server (AdventureWorks2019)<br>    Production.Product<br>    Production.ProductSubcategory   --JOIN--&gt;  hive_prod.de.stg_product          (Iceberg, staging, createOrReplace)<br>    Production.ProductCategory                       |<br>                                                     | MERGE INTO (upsert, SCD1)<br>                                                     v<br>                                          hive_prod.de.dim_product_enriched   (Iceberg, HEDEF, kategoriye göre partition)<br>                                                     |<br>                                                     | GROUP BY<br>                                                     v<br>                                          hive_prod.de.agg_category_pricing   (Iceberg, özet)<br><br>Çalıştırma:<br>  export OM_JWT_TOKEN=&#39;&lt;ingestion-bot JWT&gt;&#39;      # OpenMetadata &gt; Settings &gt; Bots &gt; ingestion-bot<br>  spark-submit --master local[*] om_lineage_job.py<br>  # Token&#39;sız kuru test (eventler dosyaya yazılır):<br>  OL_TRANSPORT=file spark-submit --master local[*] om_lineage_job.py<br>&quot;&quot;&quot;<br>import os<br>import uuid<br><br>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as F<br><br># ---------------------------------------------------------------------------<br># Ortam ayarları<br># ---------------------------------------------------------------------------<br>HOST_IP = os.getenv(&quot;SPARK_HOST_IP&quot;, &quot;192.168.1.110&quot;)          # Linux (Spark/Hive/SQL Server) makinesi<br>OM_URL = os.getenv(&quot;OM_URL&quot;, &quot;http://192.168.1.104:8585&quot;)     # Windows Docker&#39;daki OpenMetadata<br>OM_JWT_TOKEN = os.getenv(&quot;OM_JWT_TOKEN&quot;, &quot;&quot;)<br>OL_TRANSPORT = os.getenv(&quot;OL_TRANSPORT&quot;, &quot;http&quot; if OM_JWT_TOKEN else &quot;file&quot;)<br>OL_NAMESPACE = os.getenv(&quot;OL_NAMESPACE&quot;, &quot;spark_iceberg_lab&quot;)<br>OL_JOB_NAME = os.getenv(&quot;OL_JOB_NAME&quot;, &quot;adventureworks_product_pipeline&quot;)<br>OL_VERSION = os.getenv(&quot;OL_VERSION&quot;, &quot;1.53.0&quot;)<br>OL_FILE = os.getenv(&quot;OL_FILE&quot;, &quot;/tmp/openlineage_events.ndjson&quot;)<br><br># Not: localhost yerine IP kullanıyoruz; OpenLineage dataset namespace&#39;leri bu adresle<br># oluşur (sqlserver://192.168.1.110:1433, hive://192.168.1.110:9083) ve OpenMetadata<br># tarafında servis eşlemesi yaparken anlamlı olur.<br>JDBC_URL = (<br>    f&quot;jdbc:sqlserver://{HOST_IP}:1433;databaseName=AdventureWorks2019;&quot;<br>    &quot;encrypt=true;trustServerCertificate=true&quot;<br>)<br>JDBC_PROPS = {<br>    &quot;user&quot;: os.getenv(&quot;MSSQL_USER&quot;, &quot;sa&quot;),<br>    &quot;password&quot;: os.getenv(&quot;MSSQL_PASSWORD&quot;, &quot;Pa55w.rd&quot;),<br>    &quot;driver&quot;: &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;,<br>}<br><br>CATALOG = &quot;hive_prod&quot;<br>DB = &quot;de&quot;<br>STG = f&quot;{CATALOG}.{DB}.stg_product&quot;<br>TARGET = f&quot;{CATALOG}.{DB}.dim_product_enriched&quot;<br>AGG = f&quot;{CATALOG}.{DB}.agg_category_pricing&quot;<br><br><br>def build_spark() -&gt; SparkSession:<br>    &quot;&quot;&quot;code1.py&#39;deki SparkSession + OpenLineage listener.&quot;&quot;&quot;<br>    builder = (<br>        SparkSession.builder.appName(&quot;Apache-Iceberg-OpenLineage&quot;)<br>        # --- code1.py&#39;deki Iceberg / Hive Metastore ayarları (korundu) ---<br>        .config(<br>            &quot;spark.jars.packages&quot;,<br>            &quot;,&quot;.join([<br>                &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.5.0&quot;,<br>                &quot;com.microsoft.sqlserver:mssql-jdbc:12.2.0.jre8&quot;,<br>                f&quot;io.openlineage:openlineage-spark_2.12:{OL_VERSION}&quot;,<br>            ]),<br>        )<br>        .config(&quot;spark.sql.extensions&quot;,<br>                &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)<br>        .config(f&quot;spark.sql.catalog.{CATALOG}&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>        .config(f&quot;spark.sql.catalog.{CATALOG}.type&quot;, &quot;hive&quot;)<br>        .config(f&quot;spark.sql.catalog.{CATALOG}.uri&quot;, f&quot;thrift://{HOST_IP}:9083&quot;)<br>        .config(f&quot;spark.sql.catalog.{CATALOG}.warehouse&quot;, &quot;hdfs://localhost:9000/user/hive/warehouse&quot;)<br>        # --- OpenLineage ---<br>        .config(&quot;spark.extraListeners&quot;, &quot;io.openlineage.spark.agent.OpenLineageSparkListener&quot;)<br>        .config(&quot;spark.openlineage.namespace&quot;, OL_NAMESPACE)<br>        # parentJobName/parentRunId kullanılmıyor: Marquez&#39;de hiç kapanmayan (RUNNING) &quot;hayalet&quot; üst run&#39;lar<br>        # oluşturuyordu. İş adları appName ile zaten sabit: &lt;OL_JOB_NAME&gt;.&lt;adım&gt;<br>        .config(&quot;spark.openlineage.appName&quot;, OL_JOB_NAME)<br>        # Büyük/gereksiz facet&#39;leri kapat (OM&#39;ye giden payload küçülür)<br>        .config(&quot;spark.openlineage.facets.disabled&quot;, &quot;[spark_unknown;spark.logicalPlan;debug]&quot;)<br>    )<br><br>    # Spark olayları YALNIZCA yerel dosyaya yazar; OpenMetadata/Marquez&#39;e gönderimi iş bitince ol_publish.py yapar.<br>    # Neden: listener eşzamanlı HTTP gönderiminde yavaş hedefi beklerken geride kalıyor ve bazı adımların<br>    # START olayları kayboluyordu (&quot;Query execution is null: can&#39;t emit event&quot;).<br>    builder = (<br>        builder.config(&quot;spark.openlineage.transport.type&quot;, &quot;file&quot;)<br>        .config(&quot;spark.openlineage.transport.location&quot;, OL_FILE)<br>    )<br>    return builder.getOrCreate()<br><br><br>def extract(spark: SparkSession):<br>    product = (<br>        spark.read.jdbc(JDBC_URL, &quot;Production.Product&quot;, properties=JDBC_PROPS)<br>        .select(&quot;ProductID&quot;, &quot;Name&quot;, &quot;ProductNumber&quot;, &quot;MakeFlag&quot;, &quot;Color&quot;,<br>                &quot;ProductSubcategoryID&quot;, &quot;StandardCost&quot;, &quot;ListPrice&quot;,<br>                &quot;SellStartDate&quot;, &quot;SellEndDate&quot;, &quot;ModifiedDate&quot;)<br>    )<br>    subcat = (<br>        spark.read.jdbc(JDBC_URL, &quot;Production.ProductSubcategory&quot;, properties=JDBC_PROPS)<br>        .select(&quot;ProductSubcategoryID&quot;, &quot;ProductCategoryID&quot;,<br>                F.col(&quot;Name&quot;).alias(&quot;SubcategoryName&quot;))<br>    )<br>    cat = (<br>        spark.read.jdbc(JDBC_URL, &quot;Production.ProductCategory&quot;, properties=JDBC_PROPS)<br>        .select(&quot;ProductCategoryID&quot;, F.col(&quot;Name&quot;).alias(&quot;CategoryName&quot;))<br>    )<br>    return product, subcat, cat<br><br><br>def transform(product, subcat, cat):<br>    return (<br>        product.join(subcat, &quot;ProductSubcategoryID&quot;, &quot;left&quot;)<br>        .join(cat, &quot;ProductCategoryID&quot;, &quot;left&quot;)<br>        .select(<br>            F.col(&quot;ProductID&quot;).cast(&quot;int&quot;).alias(&quot;product_id&quot;),<br>            F.col(&quot;Name&quot;).alias(&quot;product_name&quot;),<br>            F.col(&quot;ProductNumber&quot;).alias(&quot;product_number&quot;),<br>            F.col(&quot;MakeFlag&quot;).cast(&quot;boolean&quot;).alias(&quot;make_flag&quot;),<br>            F.coalesce(&quot;Color&quot;, F.lit(&quot;N/A&quot;)).alias(&quot;color&quot;),<br>            F.coalesce(&quot;CategoryName&quot;, F.lit(&quot;Uncategorized&quot;)).alias(&quot;category&quot;),<br>            F.coalesce(&quot;SubcategoryName&quot;, F.lit(&quot;Uncategorized&quot;)).alias(&quot;subcategory&quot;),<br>            F.col(&quot;StandardCost&quot;).cast(&quot;decimal(19,4)&quot;).alias(&quot;standard_cost&quot;),<br>            F.col(&quot;ListPrice&quot;).cast(&quot;decimal(19,4)&quot;).alias(&quot;list_price&quot;),<br>            (F.col(&quot;ListPrice&quot;) - F.col(&quot;StandardCost&quot;)).cast(&quot;decimal(19,4)&quot;).alias(&quot;unit_margin&quot;),<br>            F.when(F.col(&quot;ListPrice&quot;) &gt; 0,<br>                   F.round((F.col(&quot;ListPrice&quot;) - F.col(&quot;StandardCost&quot;)) / F.col(&quot;ListPrice&quot;) * 100, 2))<br>             .cast(&quot;decimal(7,2)&quot;).alias(&quot;margin_pct&quot;),<br>            F.col(&quot;SellEndDate&quot;).isNull().alias(&quot;is_active&quot;),<br>            F.col(&quot;SellStartDate&quot;).alias(&quot;sell_start_date&quot;),<br>            F.col(&quot;ModifiedDate&quot;).alias(&quot;source_modified_at&quot;),<br>            F.current_timestamp().alias(&quot;etl_loaded_at&quot;),<br>        )<br>    )<br><br><br>def ensure_tables(spark: SparkSession):<br>    spark.sql(f&quot;CREATE NAMESPACE IF NOT EXISTS {CATALOG}.{DB}&quot;)<br>    spark.sql(f&quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS {TARGET} (<br>            product_id          INT       COMMENT &#39;AdventureWorks ProductID&#39;,<br>            product_name        STRING,<br>            product_number      STRING,<br>            make_flag           BOOLEAN,<br>            color               STRING,<br>            category            STRING,<br>            subcategory         STRING,<br>            standard_cost       DECIMAL(19,4),<br>            list_price          DECIMAL(19,4),<br>            unit_margin         DECIMAL(19,4) COMMENT &#39;list_price - standard_cost&#39;,<br>            margin_pct          DECIMAL(7,2),<br>            is_active           BOOLEAN,<br>            sell_start_date     TIMESTAMP,<br>            source_modified_at  TIMESTAMP,<br>            etl_loaded_at       TIMESTAMP<br>        )<br>        USING iceberg<br>        PARTITIONED BY (category)<br>        COMMENT &#39;Kategori/alt kategori ile zenginleştirilmiş ürün boyutu (SCD1)&#39;<br>        TBLPROPERTIES (&#39;format-version&#39;=&#39;2&#39;, &#39;write.merge.mode&#39;=&#39;merge-on-read&#39;)<br>    &quot;&quot;&quot;)<br><br><br>def load(spark: SparkSession, enriched):<br>    # 1) Staging: her çalışmada yeniden oluşturulur<br>    enriched.writeTo(STG).using(&quot;iceberg&quot;).createOrReplace()<br><br>    # 2) Hedef: MERGE INTO ile upsert<br>    spark.sql(f&quot;&quot;&quot;<br>        MERGE INTO {TARGET} t<br>        USING {STG} s<br>        ON t.product_id = s.product_id<br>        WHEN MATCHED AND (<br>               t.list_price &lt;&gt; s.list_price OR t.standard_cost &lt;&gt; s.standard_cost<br>            OR t.color &lt;&gt; s.color OR t.is_active &lt;&gt; s.is_active<br>            OR t.source_modified_at &lt;&gt; s.source_modified_at)<br>          THEN UPDATE SET *<br>        WHEN NOT MATCHED THEN INSERT *<br>    &quot;&quot;&quot;)<br><br>    # 3) Özet tablo<br>    agg = (<br>        spark.table(TARGET)<br>        .where(&quot;is_active&quot;)<br>        .groupBy(&quot;category&quot;, &quot;subcategory&quot;)<br>        .agg(<br>            F.count(&quot;*&quot;).alias(&quot;product_count&quot;),<br>            F.avg(&quot;list_price&quot;).cast(&quot;decimal(19,4)&quot;).alias(&quot;avg_list_price&quot;),<br>            F.avg(&quot;margin_pct&quot;).cast(&quot;decimal(7,2)&quot;).alias(&quot;avg_margin_pct&quot;),<br>            F.max(&quot;list_price&quot;).alias(&quot;max_list_price&quot;),<br>        )<br>        .withColumn(&quot;snapshot_at&quot;, F.current_timestamp())<br>    )<br>    agg.writeTo(AGG).using(&quot;iceberg&quot;).createOrReplace()<br><br><br>def main():<br>    spark = build_spark()<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br>    print(f&quot;OpenLineage -&gt; {OL_FILE} | job: {OL_NAMESPACE}/{OL_JOB_NAME} (yayın: ol_publish.py)&quot;)<br><br>    product, subcat, cat = extract(spark)<br>    enriched = transform(product, subcat, cat)<br>    ensure_tables(spark)<br>    load(spark, enriched)<br><br>    spark.sql(f&quot;SELECT committed_at, snapshot_id, operation, summary[&#39;added-records&#39;] added, &quot;<br>              f&quot;summary[&#39;total-records&#39;] total FROM {TARGET}.snapshots ORDER BY committed_at&quot;).show(truncate=False)<br>    spark.table(AGG).orderBy(&quot;category&quot;, &quot;subcategory&quot;).show(50, truncate=False)<br>    spark.stop()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>&quot;&quot;&quot;<br>ol_publish.py<br>Spark işinin yerel OpenLineage dosyasındaki olayları OpenMetadata&#39;ya ve Marquez&#39;e gönderir.<br><br>  python3 ol_publish.py [/tmp/openlineage_events.ndjson]<br><br>Neden Spark içinden değil? OpenLineage Spark listener&#39;ı olayları eşzamanlı (blocking) gönderir. Hedef yavaş<br>yanıt verdiğinde listener geride kalır, Spark bir SQL çalıştırmasının bilgisini silmiş olur ve o adımın START<br>olayı hiç üretilmez (&quot;Query execution is null: can&#39;t emit event&quot;). Spark yalnızca yerel dosyaya yazınca bu<br>risk ortadan kalkar; ağ gecikmesi burada, iş bittikten sonra karşılanır.<br><br>Hedefler (ortam değişkenleri):<br>  OM_URL + OM_JWT_TOKEN (ya da ~/.om_token)  -&gt; OpenMetadata  /api/v1/openlineage/lineage<br>  MARQUEZ_URL                                 -&gt; Marquez       /api/v1/lineage<br>Boş bırakılan hedef atlanır. Aynı run&#39;ın olayları zaman sırasıyla, farklı run&#39;lar paralel gönderilir.<br>Çıkış kodu: 0 = tamam, 4 = OpenMetadata&#39;ya gönderimde hata (Marquez hataları yalnızca uyarı).<br>&quot;&quot;&quot;<br>import json<br>import os<br>import sys<br>import time<br>import urllib.error<br>import urllib.request<br>from collections import defaultdict<br>from concurrent.futures import ThreadPoolExecutor<br><br>EVENTS = sys.argv[1] if len(sys.argv) &gt; 1 else os.getenv(&quot;OL_FILE&quot;, &quot;/tmp/openlineage_events.ndjson&quot;)<br>WORKERS = int(os.getenv(&quot;OL_PUBLISH_WORKERS&quot;, &quot;4&quot;))<br><br><br>def om_token():<br>    tok = os.getenv(&quot;OM_JWT_TOKEN&quot;)<br>    path = os.path.expanduser(&quot;~/.om_token&quot;)<br>    if not tok and os.path.exists(path):<br>        tok = open(path).read().strip()<br>    return tok<br><br><br>def targets():<br>    t = []<br>    om_url, tok = os.getenv(&quot;OM_URL&quot;, &quot;http://192.168.1.104:8585&quot;), om_token()<br>    if om_url and tok:<br>        t.append((&quot;OpenMetadata&quot;, om_url + &quot;/api/v1/openlineage/lineage&quot;,<br>                  {&quot;Authorization&quot;: f&quot;Bearer {tok}&quot;}, True))<br>    mq = os.getenv(&quot;MARQUEZ_URL&quot;, &quot;http://192.168.1.104:5000&quot;)<br>    if mq:<br>        t.append((&quot;Marquez&quot;, mq + &quot;/api/v1/lineage&quot;, {}, False))<br>    return t<br><br><br>RETRIES = int(os.getenv(&quot;OL_PUBLISH_RETRIES&quot;, &quot;3&quot;))<br><br><br>def _post_once(url, headers, event):<br>    req = urllib.request.Request(url, method=&quot;POST&quot;, data=json.dumps(event).encode(),<br>                                 headers={&quot;Content-Type&quot;: &quot;application/json&quot;, **headers})<br>    try:<br>        with urllib.request.urlopen(req, timeout=60) as r:<br>            return r.status, r.read()<br>    except urllib.error.HTTPError as e:<br>        return e.code, e.read()[:200]<br>    except Exception as e:  # noqa<br>        return 0, str(e)[:200].encode()<br><br><br>def post(url, headers, event):<br>    &quot;&quot;&quot;Sunucu hatası (5xx) ya da bağlantı hatasında artan beklemeyle yeniden dener.<br>    Örn. Marquez boş bir veritabanında paralel olaylar aynı yeni namespace/dataset&#39;i oluşturmaya<br>    çalışınca ilk denemede 500 dönebiliyor; ikinci deneme kayıt artık var olduğu için başarılı olur.&quot;&quot;&quot;<br>    for attempt in range(RETRIES + 1):<br>        st, body = _post_once(url, headers, event)<br>        if st &lt; 500 and st != 0:<br>            return st, body<br>        if attempt &lt; RETRIES:<br>            time.sleep(1 + attempt * 2)<br>    return st, body<br><br><br>def main():<br>    if not os.path.exists(EVENTS):<br>        sys.exit(f&quot;Olay dosyası yok: {EVENTS}&quot;)<br>    by_run = defaultdict(list)<br>    for line in open(EVENTS):<br>        if line.strip():<br>            e = json.loads(line)<br>            by_run[e[&quot;run&quot;][&quot;runId&quot;]].append(e)<br>    runs = [sorted(v, key=lambda x: x[&quot;eventTime&quot;]) for v in by_run.values()]<br>    n = sum(len(r) for r in runs)<br>    print(f&quot;{n} olay, {len(runs)} run  ({EVENTS})&quot;)<br><br>    exit_code = 0<br>    for name, url, headers, critical in targets():<br>        t0 = time.time()<br>        stats = {&quot;ok&quot;: 0, &quot;fail&quot;: 0, &quot;edges&quot;: 0}<br>        errors = []<br><br>        def send_run(evts):<br>            out = []<br>            for e in evts:<br>                st, body = post(url, headers, e)<br>                out.append((e, st, body))<br>            return out<br><br>        with ThreadPoolExecutor(WORKERS) as ex:<br>            for res in ex.map(send_run, runs):<br>                for e, st, body in res:<br>                    if 200 &lt;= st &lt; 300:<br>                        stats[&quot;ok&quot;] += 1<br>                        if name == &quot;OpenMetadata&quot;:<br>                            try:<br>                                stats[&quot;edges&quot;] += json.loads(body).get(&quot;lineageEdgesCreated&quot;, 0)<br>                            except Exception:  # noqa<br>                                pass<br>                    else:<br>                        stats[&quot;fail&quot;] += 1<br>                        errors.append(f&quot;    {st} {e[&#39;eventType&#39;]} {e[&#39;job&#39;][&#39;name&#39;]}: {body[:150]!r}&quot;)<br>        extra = f&quot;, {stats[&#39;edges&#39;]} lineage kenarı&quot; if name == &quot;OpenMetadata&quot; else &quot;&quot;<br>        print(f&quot;  {name:12s}: {stats[&#39;ok&#39;]} başarılı, {stats[&#39;fail&#39;]} hatalı{extra}  ({time.time() - t0:.0f} sn)&quot;)<br>        for line in errors[:10]:<br>            print(line)<br>        if stats[&quot;fail&quot;] and critical:<br>            exit_code = 4<br>    sys.exit(exit_code)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br></pre><pre>&quot;&quot;&quot;<br>om_quality.py<br>OpenMetadata veri kalitesi testleri + iş metrikleri (Spark ile çalıştırılır).<br><br>  python3 om_quality.py setup          # test case&#39;leri, metrikleri ve metrik lineage&#39;ını OM&#39;de oluşturur/günceller<br>  spark-submit --packages &lt;iceberg,mssql&gt; om_quality.py run<br>                                       # testleri Spark ile çalıştırır, sonuçları + profil bilgisini OM&#39;ye yazar<br>  (run_om_lineage.sh ikisini de iş akışından sonra otomatik çalıştırır)<br><br>Neden Spark? OpenMetadata, Windows&#39;taki Docker&#39;da çalışıyor ve Iceberg tablolarını doğrudan okuyamayabilir.<br>Testleri veri hattının kendisi çalıştırıp sonucu OM&#39;ye bildiriyor; OM&#39;de tanım, geçmiş, bildirim ve<br>&quot;incident&quot; yönetimi yine tamamen OM&#39;nin.<br>&quot;&quot;&quot;<br>import json<br>import ospy<br>import sys<br>import time<br>import urllib.error<br>import urllib.parse<br>import urllib.request<br><br>OM = os.getenv(&quot;OM_URL&quot;, &quot;http://192.168.1.104:8585&quot;) + &quot;/api/v1&quot;<br>TOKEN = os.getenv(&quot;OM_JWT_TOKEN&quot;) or open(os.path.expanduser(&quot;~/.om_token&quot;)).read().strip()<br>HOST_IP = os.getenv(&quot;SPARK_HOST_IP&quot;, &quot;192.168.1.110&quot;)<br><br>ICE_OM = &quot;hive_iceberg.default.de&quot;      # OpenMetadata FQN öneki<br>ICE_SP = &quot;hive_prod.de&quot;                 # Spark katalog öneki<br>DIM, AGG, STG = &quot;dim_product_enriched&quot;, &quot;agg_category_pricing&quot;, &quot;stg_product&quot;<br><br><br>def bi(tr, en):<br>    return f&quot;{tr}\n\n*EN:* {en}&quot;<br><br><br># ---------------------------------------------------------------------------<br># TEST TANIMLARI  (name, tablo, sütun|None, testDefinition, parametreler, açıklama)<br># tableCustomSQLQuery ifadeleri Spark SQL&#39;dir; satır döndürürse (COUNT &gt; 0) test başarısız olur.<br># ---------------------------------------------------------------------------<br>TESTS = [<br>    # --- dim_product_enriched: yapı ve hacim ---<br>    (&quot;dim_row_count_between&quot;, DIM, None, &quot;tableRowCountToBeBetween&quot;, {&quot;minValue&quot;: 400, &quot;maxValue&quot;: 1000},<br>     bi(&quot;Satır sayısı beklenen aralıkta (AdventureWorks&#39;te 504 ürün var).&quot;, &quot;Row count within expected range.&quot;)),<br>    (&quot;dim_column_count&quot;, DIM, None, &quot;tableColumnCountToEqual&quot;, {&quot;columnCount&quot;: 15},<br>     bi(&quot;Şema değişikliğini yakalar: 15 sütun bekleniyor.&quot;, &quot;Detects schema drift: 15 columns expected.&quot;)),<br>    # --- anahtarlar ---<br>    (&quot;dim_product_id_unique&quot;, DIM, &quot;product_id&quot;, &quot;columnValuesToBeUnique&quot;, {},<br>     bi(&quot;MERGE anahtarı tekil olmalı; mükerrer satır olmamalı.&quot;, &quot;MERGE key must be unique.&quot;)),<br>    (&quot;dim_product_id_not_null&quot;, DIM, &quot;product_id&quot;, &quot;columnValuesToBeNotNull&quot;, {},<br>     bi(&quot;MERGE anahtarı boş olamaz.&quot;, &quot;MERGE key must not be null.&quot;)),<br>    (&quot;dim_product_number_unique&quot;, DIM, &quot;product_number&quot;, &quot;columnValuesToBeUnique&quot;, {},<br>     bi(&quot;SKU tekil olmalı.&quot;, &quot;SKU must be unique.&quot;)),<br>    (&quot;dim_product_number_format&quot;, DIM, &quot;product_number&quot;, &quot;columnValuesToMatchRegex&quot;,<br>     {&quot;regex&quot;: &quot;^[A-Z]{2}-[A-Z0-9]{4}(-[A-Z0-9]{1,2})?$&quot;},<br>     bi(&quot;SKU biçimi: iki harf, tire, 4 karakter, isteğe bağlı beden/renk eki (ör. `BK-R93R-62`).&quot;,<br>        &quot;SKU format, e.g. BK-R93R-62.&quot;)),<br>    # --- içerik ---<br>    (&quot;dim_product_name_not_null&quot;, DIM, &quot;product_name&quot;, &quot;columnValuesToBeNotNull&quot;, {},<br>     bi(&quot;Ürün adı boş olamaz.&quot;, &quot;Product name must not be null.&quot;)),<br>    (&quot;dim_product_name_length&quot;, DIM, &quot;product_name&quot;, &quot;columnValueLengthsToBeBetween&quot;, {&quot;minLength&quot;: 1, &quot;maxLength&quot;: 50},<br>     bi(&quot;Ürün adı 1–50 karakter (kaynakta nvarchar(50)).&quot;, &quot;Name length 1-50 (nvarchar(50) at source).&quot;)),<br>    (&quot;dim_category_in_set&quot;, DIM, &quot;category&quot;, &quot;columnValuesToBeInSet&quot;,<br>     {&quot;allowedValues&quot;: [&quot;Bikes&quot;, &quot;Components&quot;, &quot;Clothing&quot;, &quot;Accessories&quot;, &quot;Uncategorized&quot;]},<br>     bi(&quot;Kategori yalnızca bilinen 4 kategori ya da `Uncategorized` olabilir.&quot;, &quot;Category must be a known value.&quot;)),<br>    (&quot;dim_list_price_range&quot;, DIM, &quot;list_price&quot;, &quot;columnValuesToBeBetween&quot;, {&quot;minValue&quot;: 0, &quot;maxValue&quot;: 10000},<br>     bi(&quot;Liste fiyatı negatif olamaz, 10.000 USD&#39;yi aşmamalı.&quot;, &quot;List price between 0 and 10,000.&quot;)),<br>    (&quot;dim_standard_cost_range&quot;, DIM, &quot;standard_cost&quot;, &quot;columnValuesToBeBetween&quot;, {&quot;minValue&quot;: 0, &quot;maxValue&quot;: 10000},<br>     bi(&quot;Standart maliyet negatif olamaz.&quot;, &quot;Standard cost must be non-negative.&quot;)),<br>    (&quot;dim_margin_pct_range&quot;, DIM, &quot;margin_pct&quot;, &quot;columnValuesToBeBetween&quot;, {&quot;minValue&quot;: -100, &quot;maxValue&quot;: 100},<br>     bi(&quot;Marj yüzdesi -100 ile 100 arasında olmalı.&quot;, &quot;Margin % between -100 and 100.&quot;)),<br>    # --- iş kuralları (Spark SQL) ---<br>    (&quot;dim_unit_margin_consistent&quot;, DIM, None, &quot;tableCustomSQLQuery&quot;,<br>     {&quot;sqlExpression&quot;: f&quot;SELECT product_id FROM {ICE_SP}.{DIM} &quot;<br>                       &quot;WHERE unit_margin &lt;&gt; list_price - standard_cost&quot;,<br>      &quot;strategy&quot;: &quot;COUNT&quot;, &quot;operator&quot;: &quot;==&quot;, &quot;threshold&quot;: 0},<br>     bi(&quot;`unit_margin = list_price − standard_cost` kuralı her satırda tutmalı.&quot;, &quot;unit_margin formula must hold.&quot;)),<br>    (&quot;dim_merge_complete&quot;, DIM, None, &quot;tableCustomSQLQuery&quot;,<br>     {&quot;sqlExpression&quot;: f&quot;SELECT s.product_id FROM {ICE_SP}.{STG} s LEFT ANTI JOIN {ICE_SP}.{DIM} d &quot;<br>                       &quot;ON s.product_id = d.product_id&quot;,<br>      &quot;strategy&quot;: &quot;COUNT&quot;, &quot;operator&quot;: &quot;==&quot;, &quot;threshold&quot;: 0},<br>     bi(&quot;MERGE tamamlığı: staging&#39;deki her ürün hedefte de olmalı.&quot;, &quot;Every staging row must exist in target.&quot;)),<br>    (&quot;dim_source_reconciliation&quot;, DIM, None, &quot;tableCustomSQLQuery&quot;,<br>     {&quot;sqlExpression&quot;: f&quot;SELECT 1 FROM (SELECT COUNT(*) c FROM src_product) s, &quot;<br>                       f&quot;(SELECT COUNT(*) c FROM {ICE_SP}.{DIM}) d WHERE s.c &lt;&gt; d.c&quot;,<br>      &quot;strategy&quot;: &quot;COUNT&quot;, &quot;operator&quot;: &quot;==&quot;, &quot;threshold&quot;: 0},<br>     bi(&quot;Kaynakla mutabakat: SQL Server `Production.Product` satır sayısı hedefle aynı olmalı &quot;<br>        &quot;(`src_product`, Spark&#39;ın JDBC ile okuduğu kaynak tablodur).&quot;,<br>        &quot;Row count must match SQL Server Production.Product.&quot;)),<br>    (&quot;dim_freshness_24h&quot;, DIM, None, &quot;tableCustomSQLQuery&quot;,<br>     {&quot;sqlExpression&quot;: f&quot;SELECT 1 FROM {ICE_SP}.{DIM} &quot;<br>                       &quot;HAVING max(etl_loaded_at) &lt; current_timestamp() - INTERVAL 24 HOURS&quot;,<br>      &quot;strategy&quot;: &quot;COUNT&quot;, &quot;operator&quot;: &quot;==&quot;, &quot;threshold&quot;: 0},<br>     bi(&quot;Tazelik: son yükleme 24 saatten eski olmamalı.&quot;, &quot;Freshness: last load within 24 hours.&quot;)),<br>    # --- agg_category_pricing ---<br>    (&quot;agg_row_count_between&quot;, AGG, None, &quot;tableRowCountToBeBetween&quot;, {&quot;minValue&quot;: 10, &quot;maxValue&quot;: 60},<br>     bi(&quot;Kategori/alt kategori kombinasyonu sayısı makul aralıkta.&quot;, &quot;Group count within expected range.&quot;)),<br>    (&quot;agg_product_count_min&quot;, AGG, &quot;product_count&quot;, &quot;columnValueMinToBeBetween&quot;,<br>     {&quot;minValueForMinInCol&quot;: 1, &quot;maxValueForMinInCol&quot;: 1000},<br>     bi(&quot;Her grupta en az 1 aktif ürün olmalı.&quot;, &quot;Each group has at least one product.&quot;)),<br>    (&quot;agg_reconciles_with_dim&quot;, AGG, None, &quot;tableCustomSQLQuery&quot;,<br>     {&quot;sqlExpression&quot;: f&quot;SELECT 1 FROM (SELECT SUM(product_count) c FROM {ICE_SP}.{AGG}) a, &quot;<br>                       f&quot;(SELECT COUNT(*) c FROM {ICE_SP}.{DIM} WHERE is_active) d WHERE a.c &lt;&gt; d.c&quot;,<br>      &quot;strategy&quot;: &quot;COUNT&quot;, &quot;operator&quot;: &quot;==&quot;, &quot;threshold&quot;: 0},<br>     bi(&quot;Özet tablodaki toplam ürün sayısı, hedefteki aktif ürün sayısına eşit olmalı.&quot;,<br>        &quot;Sum of product_count must equal active products in the dimension.&quot;)),<br>]<br><br># ---------------------------------------------------------------------------<br># METRİKLER  (name, displayName, açıklama, SQL, metricType, unit, granularity, kaynak tablolar, sözlük terimi)<br># ---------------------------------------------------------------------------<br>METRICS = [<br>    (&quot;aktif_urun_sayisi&quot;, &quot;Aktif Ürün Sayısı&quot;,<br>     bi(&quot;Hâlâ satışta olan ürünlerin sayısı.&quot;, &quot;Number of products currently on sale.&quot;),<br>     f&quot;SELECT COUNT(*) FROM {ICE_SP}.{DIM} WHERE is_active&quot;, &quot;COUNT&quot;, &quot;COUNT&quot;, &quot;DAY&quot;, [DIM], &quot;AktifUrun&quot;),<br>    (&quot;ortalama_liste_fiyati&quot;, &quot;Ortalama Liste Fiyatı&quot;,<br>     bi(&quot;Aktif ürünlerin ortalama liste fiyatı (USD).&quot;, &quot;Average list price of active products (USD).&quot;),<br>     f&quot;SELECT AVG(list_price) FROM {ICE_SP}.{DIM} WHERE is_active&quot;, &quot;AVERAGE&quot;, &quot;DOLLARS&quot;, &quot;DAY&quot;, [DIM], &quot;ListeFiyati&quot;),<br>    (&quot;ortalama_birim_marj&quot;, &quot;Ortalama Birim Marj&quot;,<br>     bi(&quot;Aktif ürünlerde birim başına ortalama brüt kâr (USD).&quot;, &quot;Average gross profit per unit (USD).&quot;),<br>     f&quot;SELECT AVG(unit_margin) FROM {ICE_SP}.{DIM} WHERE is_active&quot;, &quot;AVERAGE&quot;, &quot;DOLLARS&quot;, &quot;DAY&quot;, [DIM], &quot;BirimMarj&quot;),<br>    (&quot;ortalama_marj_yuzdesi&quot;, &quot;Ortalama Marj Yüzdesi&quot;,<br>     bi(&quot;Aktif ürünlerin ortalama marj yüzdesi.&quot;, &quot;Average margin % of active products.&quot;),<br>     f&quot;SELECT AVG(margin_pct) FROM {ICE_SP}.{DIM} WHERE is_active&quot;, &quot;AVERAGE&quot;, &quot;PERCENTAGE&quot;, &quot;DAY&quot;, [DIM], &quot;MarjYuzdesi&quot;),<br>    (&quot;kategori_bazinda_marj&quot;, &quot;Kategori Bazında Marj Yüzdesi&quot;,<br>     bi(&quot;Kategori ve alt kategori kırılımında ortalama marj yüzdesi; raporlama özetinden okunur.&quot;,<br>        &quot;Average margin % by category/subcategory, from the reporting aggregate.&quot;),<br>     f&quot;SELECT category, subcategory, avg_margin_pct FROM {ICE_SP}.{AGG}&quot;, &quot;AVERAGE&quot;, &quot;PERCENTAGE&quot;, &quot;DAY&quot;, [AGG],<br>     &quot;MarjYuzdesi&quot;),<br>]<br><br><br># ---------------------------------------------------------------------------<br># OM API<br># ---------------------------------------------------------------------------<br>def call(method, path, body=None, ctype=&quot;application/json&quot;):<br>    req = urllib.request.Request(OM + path, method=method,<br>                                 data=json.dumps(body).encode() if body is not None else None,<br>                                 headers={&quot;Authorization&quot;: f&quot;Bearer {TOKEN}&quot;, &quot;Content-Type&quot;: ctype})<br>    try:<br>        with urllib.request.urlopen(req, timeout=30) as r:<br>            return r.status, json.loads(r.read() or b&quot;{}&quot;)<br>    except urllib.error.HTTPError as e:<br>        return e.code, e.read().decode()[:300]<br><br><br>def report(label, st, res):<br>    ok = 200 &lt;= st &lt; 300<br>    print(f&quot;  {&#39;OK &#39; if ok else &#39;ERR&#39;} {label} -&gt; {st}&quot; + (&quot;&quot; if ok else f&quot; {res}&quot;))<br>    return res if ok else None<br><br><br>def get_table(name):<br>    st, t = call(&quot;GET&quot;, f&quot;/tables/name/{urllib.parse.quote(f&#39;{ICE_OM}.{name}&#39;)}?fields=columns&quot;)<br>    return t if st == 200 else None<br><br><br>def entity_link(table, column=None):<br>    link = f&quot;&lt;#E::table::{ICE_OM}.{table}&quot;<br>    return link + (f&quot;::columns::{column}&gt;&quot; if column else &quot;&gt;&quot;)<br><br><br>def test_fqn(table, column, name):<br>    return f&quot;{ICE_OM}.{table}&quot; + (f&quot;.{column}&quot; if column else &quot;&quot;) + f&quot;.{name}&quot;<br><br><br>def setup():<br>    st, team = call(&quot;GET&quot;, &quot;/teams/name/DataEngineering&quot;)<br>    owners = [{&quot;id&quot;: team[&quot;id&quot;], &quot;type&quot;: &quot;team&quot;}] if st == 200 else []<br><br>    print(&quot;Test case&#39;ler&quot;)<br>    for name, table, col, definition, params, desc in TESTS:<br>        pv = [{&quot;name&quot;: k, &quot;value&quot;: json.dumps(v) if isinstance(v, list) else str(v)} for k, v in params.items()]<br>        report(name, *call(&quot;PUT&quot;, &quot;/dataQuality/testCases&quot;, {<br>            &quot;name&quot;: name, &quot;displayName&quot;: name, &quot;description&quot;: desc,<br>            &quot;entityLink&quot;: entity_link(table, col), &quot;testDefinition&quot;: definition,<br>            &quot;parameterValues&quot;: pv, &quot;owners&quot;: owners}))<br><br>    print(&quot;Metrikler&quot;)<br>    for name, disp, desc, sql, mtype, unit, gran, tables, term in METRICS:<br>        m = report(name, *call(&quot;PUT&quot;, &quot;/metrics&quot;, {<br>            &quot;name&quot;: name, &quot;displayName&quot;: disp, &quot;description&quot;: desc,<br>            &quot;metricExpression&quot;: {&quot;language&quot;: &quot;SQL&quot;, &quot;code&quot;: sql},<br>            &quot;metricType&quot;: mtype, &quot;unitOfMeasurement&quot;: unit, &quot;granularity&quot;: gran, &quot;owners&quot;: owners,<br>            &quot;tags&quot;: [{&quot;tagFQN&quot;: f&quot;UrunSatis.{term}&quot;, &quot;source&quot;: &quot;Glossary&quot;,<br>                      &quot;labelType&quot;: &quot;Manual&quot;, &quot;state&quot;: &quot;Confirmed&quot;}]}))<br>        if not m:<br>            continue<br>        st, dom = call(&quot;GET&quot;, &quot;/domains/name/Urun&quot;)<br>        if st == 200:<br>            call(&quot;PUT&quot;, &quot;/domains/name/Urun/assets/add&quot;, {&quot;assets&quot;: [{&quot;id&quot;: m[&quot;id&quot;], &quot;type&quot;: &quot;metric&quot;}]})<br>        for t in tables:<br>            tbl = get_table(t)<br>            report(f&quot;   lineage {t} -&gt; {name}&quot;, *call(&quot;PUT&quot;, &quot;/lineage&quot;, {&quot;edge&quot;: {<br>                &quot;fromEntity&quot;: {&quot;id&quot;: tbl[&quot;id&quot;], &quot;type&quot;: &quot;table&quot;},<br>                &quot;toEntity&quot;: {&quot;id&quot;: m[&quot;id&quot;], &quot;type&quot;: &quot;metric&quot;},<br>                &quot;lineageDetails&quot;: {&quot;sqlQuery&quot;: sql, &quot;source&quot;: &quot;Manual&quot;}}}))<br><br><br># ---------------------------------------------------------------------------<br># SPARK ile çalıştırma<br># ---------------------------------------------------------------------------<br>def run():<br>    from pyspark.sql import SparkSession<br>    import pyspark.sql.functions as F<br><br>    spark = (SparkSession.builder.appName(&quot;om-data-quality&quot;)<br>             .config(&quot;spark.sql.extensions&quot;, &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)<br>             .config(&quot;spark.sql.catalog.hive_prod&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>             .config(&quot;spark.sql.catalog.hive_prod.type&quot;, &quot;hive&quot;)<br>             .config(&quot;spark.sql.catalog.hive_prod.uri&quot;, f&quot;thrift://{HOST_IP}:9083&quot;)<br>             .config(&quot;spark.sql.catalog.hive_prod.warehouse&quot;, &quot;hdfs://localhost:9000/user/hive/warehouse&quot;)<br>             .getOrCreate())<br>    spark.sparkContext.setLogLevel(&quot;ERROR&quot;)<br><br>    # Mutabakat testi için kaynak tablo<br>    (spark.read.jdbc(f&quot;jdbc:sqlserver://{HOST_IP}:1433;databaseName=AdventureWorks2019;&quot;<br>                     &quot;encrypt=true;trustServerCertificate=true&quot;, &quot;Production.Product&quot;,<br>                     properties={&quot;user&quot;: os.getenv(&quot;MSSQL_USER&quot;, &quot;sa&quot;),<br>                                 &quot;password&quot;: os.getenv(&quot;MSSQL_PASSWORD&quot;, &quot;Pa55w.rd&quot;),<br>                                 &quot;driver&quot;: &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;})<br>     .createOrReplaceTempView(&quot;src_product&quot;))<br><br>    dfs = {t: spark.table(f&quot;{ICE_SP}.{t}&quot;).cache() for t in (DIM, AGG)}<br>    now = int(time.time() * 1000)<br>    summary = {&quot;Success&quot;: 0, &quot;Failed&quot;: 0, &quot;Aborted&quot;: 0}<br><br>    def evaluate(table, col, definition, p):<br>        df = dfs[table]<br>        if definition == &quot;tableRowCountToBeBetween&quot;:<br>            n = df.count()<br>            return p[&quot;minValue&quot;] &lt;= n &lt;= p[&quot;maxValue&quot;], f&quot;Satır sayısı {n}&quot;, [(&quot;rowCount&quot;, n)]<br>        if definition == &quot;tableColumnCountToEqual&quot;:<br>            n = len(df.columns)<br>            return n == p[&quot;columnCount&quot;], f&quot;Sütun sayısı {n}&quot;, [(&quot;columnCount&quot;, n)]<br>        c = F.col(col) if col else None<br>        if definition == &quot;columnValuesToBeUnique&quot;:<br>            r = df.agg(F.count(c).alias(&quot;v&quot;), F.countDistinct(c).alias(&quot;u&quot;)).first()<br>            return r.v == r.u, f&quot;{r.v} değer, {r.u} tekil&quot;, [(&quot;valuesCount&quot;, r.v), (&quot;uniqueCount&quot;, r.u)]<br>        if definition == &quot;columnValuesToBeNotNull&quot;:<br>            n = df.where(c.isNull()).count()<br>            return n == 0, f&quot;{n} boş değer&quot;, [(&quot;nullCount&quot;, n)]<br>        if definition == &quot;columnValuesToMatchRegex&quot;:<br>            bad = df.where(c.isNotNull() &amp; ~c.rlike(p[&quot;regex&quot;]))<br>            n = bad.count()<br>            ex = [r[0] for r in bad.select(col).limit(5).collect()]<br>            return n == 0, f&quot;{n} değer kalıba uymuyor&quot; + (f&quot; (ör. {ex})&quot; if ex else &quot;&quot;), [(&quot;unmatchedCount&quot;, n)]<br>        if definition == &quot;columnValuesToBeInSet&quot;:<br>            bad = df.where(~c.isin(p[&quot;allowedValues&quot;]))<br>            n = bad.count()<br>            ex = [r[0] for r in bad.select(col).distinct().limit(5).collect()]<br>            return n == 0, f&quot;{n} değer izinli kümede değil&quot; + (f&quot; ({ex})&quot; if ex else &quot;&quot;), [(&quot;unexpectedCount&quot;, n)]<br>        if definition == &quot;columnValuesToBeBetween&quot;:<br>            r = df.agg(F.min(c).alias(&quot;mn&quot;), F.max(c).alias(&quot;mx&quot;)).first()<br>            mn, mx = float(r.mn), float(r.mx)<br>            return p[&quot;minValue&quot;] &lt;= mn and mx &lt;= p[&quot;maxValue&quot;], f&quot;min={mn}, max={mx}&quot;, [(&quot;min&quot;, mn), (&quot;max&quot;, mx)]<br>        if definition == &quot;columnValueLengthsToBeBetween&quot;:<br>            r = df.agg(F.min(F.length(c)).alias(&quot;mn&quot;), F.max(F.length(c)).alias(&quot;mx&quot;)).first()<br>            return p[&quot;minLength&quot;] &lt;= r.mn and r.mx &lt;= p[&quot;maxLength&quot;], f&quot;uzunluk {r.mn}–{r.mx}&quot;, \<br>                [(&quot;minValueLength&quot;, r.mn), (&quot;maxValueLength&quot;, r.mx)]<br>        if definition == &quot;columnValueMinToBeBetween&quot;:<br>            mn = float(df.agg(F.min(c)).first()[0])<br>            return p[&quot;minValueForMinInCol&quot;] &lt;= mn &lt;= p[&quot;maxValueForMinInCol&quot;], f&quot;min={mn}&quot;, [(&quot;min&quot;, mn)]<br>        if definition == &quot;tableCustomSQLQuery&quot;:<br>            n = spark.sql(p[&quot;sqlExpression&quot;]).count()<br>            return n == p[&quot;threshold&quot;], f&quot;Sorgu {n} satır döndürdü (beklenen {p[&#39;threshold&#39;]})&quot;, [(&quot;resultRowCount&quot;, n)]<br>        raise ValueError(definition)<br><br>    print(&quot;Test sonuçları&quot;)<br>    for name, table, col, definition, params, _ in TESTS:<br>        try:<br>            ok, msg, vals = evaluate(table, col, definition, params)<br>            status = &quot;Success&quot; if ok else &quot;Failed&quot;<br>        except Exception as e:  # noqa<br>            status, msg, vals = &quot;Aborted&quot;, f&quot;Hata: {str(e)[:200]}&quot;, []<br>        summary[status] += 1<br>        body = {&quot;timestamp&quot;: now, &quot;testCaseStatus&quot;: status, &quot;result&quot;: msg,<br>                &quot;testResultValue&quot;: [{&quot;name&quot;: k, &quot;value&quot;: str(v)} for k, v in vals]}<br>        fqn = test_fqn(table, col, name)<br>        st, res = call(&quot;POST&quot;, f&quot;/dataQuality/testCases/testCaseResults/{urllib.parse.quote(fqn)}&quot;, body)<br>        if not 200 &lt;= st &lt; 300:<br>            st, res = call(&quot;PUT&quot;, f&quot;/dataQuality/testCases/{urllib.parse.quote(fqn)}/testCaseResult&quot;, body)<br>        mark = {&quot;Success&quot;: &quot;✔&quot;, &quot;Failed&quot;: &quot;✘&quot;, &quot;Aborted&quot;: &quot;!&quot;}[status]<br>        print(f&quot;  {mark} {name:30s} {msg}&quot; + (&quot;&quot; if 200 &lt;= st &lt; 300 else f&quot;   [OM {st}: {res}]&quot;))<br><br>    # --- Profil (Profiler sekmesi) ---<br>    print(&quot;Profil&quot;)<br>    for t, df in dfs.items():<br>        tbl = get_table(t)<br>        n = df.count()<br>        cprof = []<br>        for f in df.schema.fields:<br>            c = F.col(f.name)<br>            numeric = f.dataType.typeName() in (&quot;integer&quot;, &quot;long&quot;, &quot;double&quot;, &quot;float&quot;, &quot;decimal&quot;, &quot;short&quot;)<br>            aggs = [F.count(c).alias(&quot;v&quot;), F.countDistinct(c).alias(&quot;d&quot;)]<br>            if numeric:<br>                aggs += [F.min(c).alias(&quot;mn&quot;), F.max(c).alias(&quot;mx&quot;), F.avg(c).alias(&quot;avg&quot;),<br>                         F.stddev(c).alias(&quot;sd&quot;), F.sum(c).alias(&quot;s&quot;)]<br>            r = df.agg(*aggs).first()<br>            nulls = n - r.v<br>            # OM tanımı: uniqueCount = yalnızca bir kez geçen değer sayısı<br>            uq = df.where(c.isNotNull()).groupBy(c).count().where(&quot;count = 1&quot;).count()<br>            cp = {&quot;name&quot;: f.name, &quot;timestamp&quot;: now, &quot;valuesCount&quot;: r.v, &quot;nullCount&quot;: nulls,<br>                  &quot;nullProportion&quot;: round(nulls / n, 4) if n else 0, &quot;distinctCount&quot;: r.d,<br>                  &quot;distinctProportion&quot;: round(r.d / n, 4) if n else 0,<br>                  &quot;uniqueCount&quot;: uq, &quot;uniqueProportion&quot;: round(uq / n, 4) if n else 0}<br>            if numeric and r.v:<br>                cp.update(min=float(r.mn), max=float(r.mx), mean=float(r.avg),<br>                          stddev=float(r.sd or 0), sum=float(r.s))<br>            cprof.append(cp)<br>        body = {&quot;tableProfile&quot;: {&quot;timestamp&quot;: now, &quot;rowCount&quot;: n, &quot;columnCount&quot;: len(df.columns)},<br>                &quot;columnProfile&quot;: cprof}<br>        report(f&quot;profile {t} ({n} satır)&quot;, *call(&quot;PUT&quot;, f&quot;/tables/{tbl[&#39;id&#39;]}/tableProfile&quot;, body))<br><br>    # --- Metrik değerleri (konsola; OM Metric varlığı tanımı tutar, değerleri tutmaz) ---<br>    print(&quot;Metrik değerleri&quot;)<br>    for name, disp, _, sql, *_ in METRICS[:4]:<br>        print(f&quot;  {disp:28s} = {spark.sql(sql).first()[0]}&quot;)<br><br>    print(f&quot;\nÖzet: {summary}&quot;)<br>    spark.stop()<br>    if summary[&quot;Failed&quot;] or summary[&quot;Aborted&quot;]:<br>        sys.exit(2)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    mode = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;setup&quot;<br>    {&quot;setup&quot;: setup, &quot;run&quot;: run}[mode]()</pre><pre>&quot;&quot;&quot;<br>marquez_perf_check.py<br>Marquez çalıştırma geçmişinden performans kontrolü.<br><br>Her Spark adımının (job) son çalıştırma süresini, önceki başarılı çalıştırmaların medyanıyla karşılaştırır.<br>  - YAVAŞ  : son süre &gt; medyan × ORAN  ve  fark &gt; MIN_FARK saniye<br>  - HATA   : son çalıştırma FAILED/ABORTED<br>  - AZ VERİ: karşılaştırma için MIN_GECMIS&#39;ten az geçmiş çalıştırma var<br><br>  python3 marquez_perf_check.py                # rapor<br>  PERF_RATIO=1.3 python3 marquez_perf_check.py # eşiği değiştir<br>Çıkış kodu: 0 = sorun yok, 3 = yavaşlama ya da hata var.<br>&quot;&quot;&quot;<br>import json<br>import os<br>import statistics<br>import sys<br>import urllib.parse<br>import urllib.request<br>from datetime import datetime<br><br>MARQUEZ = os.getenv(&quot;MARQUEZ_URL&quot;, &quot;http://192.168.1.104:5000&quot;) + &quot;/api/v1&quot;<br>NAMESPACE = os.getenv(&quot;OL_NAMESPACE&quot;, &quot;spark_iceberg_lab&quot;)<br>RATIO = float(os.getenv(&quot;PERF_RATIO&quot;, &quot;1.5&quot;))       # medyanın kaç katı &quot;yavaş&quot; sayılır<br>MIN_DIFF_S = float(os.getenv(&quot;PERF_MIN_DIFF&quot;, &quot;5&quot;)) # küçük işlerde gürültüyü önlemek için mutlak fark eşiği<br>MIN_HISTORY = int(os.getenv(&quot;PERF_MIN_HISTORY&quot;, &quot;3&quot;))<br>HISTORY = int(os.getenv(&quot;PERF_HISTORY&quot;, &quot;20&quot;))      # bakılacak geçmiş çalıştırma sayısı<br>SKIP = (&quot;take_ordered_and_project&quot;,)                # .show() gibi raporlama adımları<br><br># Okunaklı adlar<br>LABELS = {<br>    &quot;atomic_replace_table_as_select.de_stg_product&quot;: &quot;Staging yaz (JDBC → stg_product)&quot;,<br>    &quot;write_delta.hive_prod_de_dim_product_enriched&quot;: &quot;MERGE INTO dim_product_enriched&quot;,<br>    &quot;atomic_replace_table_as_select.de_agg_category_pricing&quot;: &quot;Özet yaz (agg_category_pricing)&quot;,<br>    &quot;create_table.de_dim_product_enriched&quot;: &quot;CREATE TABLE IF NOT EXISTS&quot;,<br>}<br><br><br>def get(path):<br>    with urllib.request.urlopen(MARQUEZ + path, timeout=15) as r:<br>        return json.loads(r.read())<br><br><br>def label(job):<br>    if &quot;.&quot; not in job:  # &lt;ad&gt; = Spark uygulamasının tamamı<br>        return &quot;Tüm iş (uçtan uca)&quot;<br>    return LABELS.get(job.partition(&quot;.&quot;)[2], job.partition(&quot;.&quot;)[2])<br><br><br>def is_skipped(job):<br>    head, _, short = job.partition(&quot;.&quot;)<br>    # &lt;ad&gt;.&lt;ad&gt;: eski parentJobName ayarından kalan job; artık kullanılmıyor<br>    return any(s in job for s in SKIP) or short == head<br><br><br>def main():<br>    jobs = get(f&quot;/namespaces/{urllib.parse.quote(NAMESPACE)}/jobs?limit=200&quot;)[&quot;jobs&quot;]<br>    rows, problems = [], 0<br>    for j in sorted(jobs, key=lambda x: x[&quot;name&quot;]):<br>        name = j[&quot;name&quot;]<br>        if is_skipped(name):<br>            continue<br>        runs = get(f&quot;/namespaces/{urllib.parse.quote(NAMESPACE)}/jobs/&quot;<br>                   f&quot;{urllib.parse.quote(name, safe=&#39;&#39;)}/runs?limit={HISTORY}&quot;)[&quot;runs&quot;]<br>        runs = [r for r in runs if r.get(&quot;endedAt&quot;)]<br>        if not runs:<br>            continue<br>        last, prev = runs[0], runs[1:]<br>        dur = last[&quot;durationMs&quot;] / 1000 if last.get(&quot;durationMs&quot;) is not None else None<br>        base = [r[&quot;durationMs&quot;] / 1000 for r in prev<br>                if r.get(&quot;state&quot;) == &quot;COMPLETED&quot; and (r.get(&quot;durationMs&quot;) or 0) &gt; 0]<br>        med = statistics.median(base) if base else None<br>        if last[&quot;state&quot;] != &quot;COMPLETED&quot;:<br>            status = f&quot;HATA ({last[&#39;state&#39;]})&quot;<br>            problems += 1<br>        elif dur is None:<br>            status = &quot;SÜRE YOK (START olayı eksik)&quot;<br>        elif med is None or len(base) &lt; MIN_HISTORY:<br>            status = f&quot;AZ VERİ ({len(base)}/{MIN_HISTORY})&quot;<br>        elif dur &gt; med * RATIO and dur - med &gt; MIN_DIFF_S:<br>            status = f&quot;YAVAŞ (×{dur / med:.1f})&quot;<br>            problems += 1<br>        else:<br>            status = &quot;OK&quot;<br>        when = datetime.fromisoformat(last[&quot;endedAt&quot;].replace(&quot;Z&quot;, &quot;+00:00&quot;)).astimezone().strftime(&quot;%d.%m %H:%M&quot;)<br>        rows.append((label(name), when, dur, med, len(base), status))<br><br>    print(f&quot;Marquez performans kontrolü  |  namespace={NAMESPACE}  eşik=×{RATIO} ve +{MIN_DIFF_S:.0f}s\n&quot;)<br>    print(f&quot;{&#39;Adım&#39;:38s} {&#39;Son çalışma&#39;:12s} {&#39;Süre&#39;:&gt;8s} {&#39;Medyan&#39;:&gt;8s} {&#39;Geçmiş&#39;:&gt;7s}  Durum&quot;)<br>    print(&quot;-&quot; * 92)<br>    rows.sort(key=lambda r: (not r[0].startswith(&quot;Tüm iş&quot;), r[0]))<br>    for lbl, when, dur, med, n, status in rows:<br>        med_s = f&quot;{med:7.1f}s&quot; if med is not None else &quot;      -&quot;<br>        dur_s = f&quot;{dur:7.1f}s&quot; if dur is not None else &quot;       -&quot;<br>        print(f&quot;{lbl[:38]:38s} {when:12s} {dur_s} {med_s} {n:7d}  {status}&quot;)<br>    print()<br>    if problems:<br>        print(f&quot;⚠ {problems} adımda yavaşlama ya da hata var. Ayrıntı: Marquez → Jobs → {NAMESPACE}&quot;)<br>        sys.exit(3)<br>    print(&quot;Sorun yok.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Sh scriptinde gerçekleşen veri akışının görsel olarak görüntüsünü de aşağıda iletiyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WNa8nlb6TOg-1DGXEF31A.png" /></figure><p>Yukarıdaki sh scriptini aşağıdaki gibi çalıştırabilirsiniz.</p><pre>./run_om_lineage.sh</pre><pre>Output:<br>&gt;&gt;&gt; 1/4 ETL iş akışı (OpenLineage -&gt; yerel dosya)<br>+-----------------------+-------------------+---------+-----+-----+<br>|committed_at           |snapshot_id        |operation|added|total|<br>+-----------------------+-------------------+---------+-----+-----+<br>|2026-10-10 23:29:47.101|3261588688941100883|overwrite|504  |504  |<br>|2026-10-10 23:31:56.789|3070318001008816397|overwrite|NULL |504  |<br>|2026-10-10 23:36:23.7  |6652873982019933813|overwrite|NULL |504  |<br>|2026-10-10 23:38:04.885|1282513339778485401|overwrite|NULL |504  |<br>|2026-10-10 23:38:36.623|8176040465029103990|overwrite|NULL |504  |<br>|2026-10-10 23:53:50.963|5422147008920248379|overwrite|NULL |504  |<br>|2026-10-11 19:00:53.367|8187938824098249010|overwrite|NULL |504  |<br>|2026-10-11 19:32:24.265|8219358929870517708|overwrite|NULL |504  |<br>|2026-10-11 19:37:52.442|8579644677379363963|overwrite|NULL |504  |<br>|2026-10-11 19:47:39.755|6353586952174432367|overwrite|NULL |504  |<br>|2026-10-11 19:49:38.491|2010455089629809462|overwrite|NULL |504  |<br>|2026-10-11 19:52:46.494|7886783081961436454|overwrite|NULL |504  |<br>|2026-10-11 19:53:08.114|7181876886921388015|overwrite|NULL |504  |<br>|2026-10-11 19:56:56.851|5773377113270455876|overwrite|NULL |504  |<br>|2026-10-11 20:11:29.846|8778242645686601550|overwrite|NULL |504  |<br>|2026-10-12 07:05:40.478|7758142291751740100|overwrite|NULL |504  |<br>|2026-10-12 07:07:30.076|993850637686312864 |overwrite|NULL |504  |<br>|2026-10-12 07:09:14.821|2032093076245815079|overwrite|NULL |504  |<br>|2026-10-12 07:21:43.108|6188790233450868440|overwrite|NULL |504  |<br>+-----------------------+-------------------+---------+-----+-----+<br>+-------------+-----------------+-------------+--------------+--------------+--------------+--------------------------+<br>|category     |subcategory      |product_count|avg_list_price|avg_margin_pct|max_list_price|snapshot_at               |<br>+-------------+-----------------+-------------+--------------+--------------+--------------+--------------------------+<br>|Accessories  |Bike Racks       |1            |120.0000      |62.60         |120.0000      |2026-10-12 07:21:43.338444|<br>|Accessories  |Bike Stands      |1            |159.0000      |62.60         |159.0000      |2026-10-12 07:21:43.338444|<br>|Accessories  |Bottles and Cages|3            |7.9900        |62.60         |9.9900        |2026-10-12 07:21:43.338444|<br>|Accessories  |Cleaners         |1            |7.9500        |62.60         |7.9500        |2026-10-12 07:21:43.338444|<br>|Accessories  |Fenders          |1            |21.9800       |62.60         |21.9800       |2026-10-12 07:21:43.338444|<br>|Accessories  |Helmets          |3            |34.9900       |62.60         |34.9900       |2026-10-12 07:21:43.338444|<br>|Accessories  |Hydration Packs  |1            |54.9900       |62.60         |54.9900       |2026-10-12 07:21:43.338444|<br>|Accessories  |Tires and Tubes  |11           |19.4827       |62.60         |35.0000       |2026-10-12 07:21:43.338444|<br>|Bikes        |Mountain Bikes   |20           |1122.3900     |45.45         |2319.9900     |2026-10-12 07:21:43.338444|<br>|Bikes        |Road Bikes       |18           |1487.9511     |36.36         |2443.3500     |2026-10-12 07:21:43.338444|<br>|Bikes        |Touring Bikes    |22           |1425.2482     |37.84         |2384.0700     |2026-10-12 07:21:43.338444|<br>|Clothing     |Caps             |1            |8.9900        |23.00         |8.9900        |2026-10-12 07:21:43.338444|<br>|Clothing     |Gloves           |3            |24.4900       |62.60         |24.4900       |2026-10-12 07:21:43.338444|<br>|Clothing     |Jerseys          |8            |51.9900       |23.00         |53.9900       |2026-10-12 07:21:43.338444|<br>|Clothing     |Shorts           |3            |69.9900       |62.60         |69.9900       |2026-10-12 07:21:43.338444|<br>|Clothing     |Socks            |2            |8.9900        |62.60         |8.9900        |2026-10-12 07:21:43.338444|<br>|Clothing     |Vests            |3            |63.5000       |62.60         |63.5000       |2026-10-12 07:21:43.338444|<br>|Components   |Bottom Brackets  |3            |92.2400       |55.60         |121.4900      |2026-10-12 07:21:43.338444|<br>|Components   |Brakes           |2            |106.5000      |55.60         |106.5000      |2026-10-12 07:21:43.338444|<br>|Components   |Chains           |1            |20.2400       |55.60         |20.2400       |2026-10-12 07:21:43.338444|<br>|Components   |Cranksets        |3            |278.9900      |55.60         |404.9900      |2026-10-12 07:21:43.338444|<br>|Components   |Derailleurs      |2            |106.4750      |55.60         |121.4600      |2026-10-12 07:21:43.338444|<br>|Components   |Handlebars       |8            |73.8900       |55.60         |120.2700      |2026-10-12 07:21:43.338444|<br>|Components   |Mountain Frames  |20           |608.3930      |45.24         |1364.5000     |2026-10-12 07:21:43.338444|<br>|Components   |Pedals           |7            |64.0186       |55.60         |80.9900       |2026-10-12 07:21:43.338444|<br>|Components   |Road Frames      |22           |942.9077      |38.11         |1431.5000     |2026-10-12 07:21:43.338444|<br>|Components   |Saddles          |9            |39.6333       |55.60         |52.6400       |2026-10-12 07:21:43.338444|<br>|Components   |Touring Frames   |18           |631.4156      |40.06         |1003.9100     |2026-10-12 07:21:43.338444|<br>|Uncategorized|Uncategorized    |209          |6.8526        |25.93         |196.9200      |2026-10-12 07:21:43.338444|<br>+-------------+-----------------+-------------+--------------+--------------+--------------+--------------------------+<br><br>&gt;&gt;&gt; 2/4 Lineage yayını (OpenMetadata + Marquez)<br>37 olay, 9 run  (/tmp/openlineage_events.ndjson)<br>  OpenMetadata: 37 başarılı, 0 hatalı, 10 lineage kenarı  (1 sn)<br>  Marquez     : 37 başarılı, 0 hatalı  (4 sn)<br>&gt;&gt;&gt; 3/4 Veri kalitesi testleri + profil (OpenMetadata)<br>Test sonuçları<br>WARNING: An illegal reflective access operation has occurred<br>WARNING: Illegal reflective access by org.apache.spark.util.SizeEstimator$ (file:/home/emre/spark-3.5.1-bin-hadoop3/jars/spark-core_2.12-3.5.1.jar) to field java.math.BigDecimal.intVal<br>WARNING: Please consider reporting this to the maintainers of org.apache.spark.util.SizeEstimator$<br>WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations<br>WARNING: All illegal access operations will be denied in a future release<br>  ✔ dim_row_count_between          Satır sayısı 504<br>  ✔ dim_column_count               Sütun sayısı 15<br>  ✔ dim_product_id_unique          504 değer, 504 tekil<br>  ✔ dim_product_id_not_null        0 boş değer<br>  ✔ dim_product_number_unique      504 değer, 504 tekil<br>  ✔ dim_product_number_format      0 değer kalıba uymuyor<br>  ✔ dim_product_name_not_null      0 boş değer<br>  ✔ dim_product_name_length        uzunluk 4–32<br>  ✔ dim_category_in_set            0 değer izinli kümede değil<br>  ✔ dim_list_price_range           min=0.0, max=3578.27<br>  ✔ dim_standard_cost_range        min=0.0, max=2171.2942<br>  ✔ dim_margin_pct_range           min=23.0, max=64.25<br>  ✔ dim_unit_margin_consistent     Sorgu 0 satır döndürdü (beklenen 0)<br>  ✔ dim_merge_complete             Sorgu 0 satır döndürdü (beklenen 0)<br>  ✔ dim_source_reconciliation      Sorgu 0 satır döndürdü (beklenen 0)<br>  ✘ dim_freshness_24h              Sorgu 1 satır döndürdü (beklenen 0)<br>  ✔ agg_row_count_between          Satır sayısı 29<br>  ✔ agg_product_count_min          min=1.0<br>  ✔ agg_reconciles_with_dim        Sorgu 0 satır döndürdü (beklenen 0)<br>Profil<br>  OK  profile dim_product_enriched (504 satır) -&gt; 200<br>  OK  profile agg_category_pricing (29 satır) -&gt; 200<br>Metrik değerleri<br>  Aktif Ürün Sayısı            = 406<br>  Ortalama Liste Fiyatı        = 322.35399015<br>  Ortalama Birim Marj          = 129.31325714<br>  Ortalama Marj Yüzdesi        = 45.205728<br><br>Özet: {&#39;Success&#39;: 18, &#39;Failed&#39;: 1, &#39;Aborted&#39;: 0}<br>&gt;&gt;&gt; 4/4 Performans kontrolü (Marquez çalıştırma geçmişi)<br>Marquez performans kontrolü  |  namespace=spark_iceberg_lab  eşik=×1.5 ve +5s<br><br>Adım                                   Son çalışma      Süre   Medyan  Geçmiş  Durum<br>--------------------------------------------------------------------------------------------<br>Tüm iş (uçtan uca)                     12.10 04:21      7.3s    13.7s       2  AZ VERİ (2/3)<br>CREATE TABLE IF NOT EXISTS             12.10 04:21      0.3s     0.4s       2  AZ VERİ (2/3)<br>MERGE INTO dim_product_enriched        12.10 04:21      0.2s     0.2s       2  AZ VERİ (2/3)<br>Staging yaz (JDBC → stg_product)       12.10 04:21      3.3s     3.2s       2  AZ VERİ (2/3)<br>append_data.hive_prod_de_agg_category_ 12.10 04:21      0.1s     0.1s       2  AZ VERİ (2/3)<br>append_data.hive_prod_de_stg_product   12.10 04:21      1.2s     1.1s       2  AZ VERİ (2/3)<br>Özet yaz (agg_category_pricing)        12.10 04:21      0.8s     0.9s       2  AZ VERİ (2/3)<br><br>Sorun yok.</pre><p>Yukarıdaki sh’ı çalıştırmayla birlikte aslında bir veri akışını tetikledik. Bu veri akışı çalışırken bizim belirttiğimiz /tmp/openlineage_events.ndjson dizinine lineage bilgilerini aktardı. Daha sonraki adımda ol_publish.py scriptiyle bu dosyayı kullanarak Openmetadata ve Marquez araçlarına bu lineage bilgilerini yayınlamış olduk. 3.adımda Openmetadata tarafında tanımlamış olduğumuz veri kalitesi testleri kontrol edildi ve 4. ve son adımda da Marquez aracı kullanılarak performans kontrolü yapıldı.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6pDXD2x8IJ848NM9P96fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsGT0DqcE0BINHg7RmR-DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxRH96AIb_xaX9m6sY0wog.png" /></figure><p>Servisleri kontrol ettiğimizde sıkıntısız bir şekilde veri akışının çalıştığını ve OpenMetadata’ya ve Marquez’e bilgilerin geldiğini görebiliriz.</p><p>Şimdi sırada MCP Server’ları ayağa kaldırıp Claude Code üzerinden bu sistemlerle bağlantı sağlayıp cevap almak kaldı.</p><pre>&quot;&quot;&quot;<br>Marquez MCP sunucusu (salt okunur) — Claude Desktop gibi bir MCP istemcisinin Marquez&#39;deki<br>OpenLineage verisini (job&#39;lar, çalıştırmalar, dataset&#39;ler, lineage, ham olaylar) sorgulamasını sağlar.<br><br>Kurulum (Windows, Python 3.10+):<br>    pip install &quot;mcp[cli]&quot;        (mcp 1.x ve 2.x ile çalışır)<br>Claude Desktop yapılandırması: claude_desktop_config.example.json<br><br>Test (MCP kütüphanesi gerekmez, Python 3.8+):<br>    MARQUEZ_URL=http://192.168.1.104:5000 python3 marquez_mcp_server.py --selftest<br>&quot;&quot;&quot;<br>import json<br>import os<br>import sys<br>import urllib.error<br>import urllib.parse<br>import urllib.request<br>from typing import Optional<br><br>MARQUEZ_URL = os.getenv(&quot;MARQUEZ_URL&quot;, &quot;http://localhost:5000&quot;).rstrip(&quot;/&quot;)<br>DEFAULT_NAMESPACE = os.getenv(&quot;MARQUEZ_NAMESPACE&quot;, &quot;spark_iceberg_lab&quot;)<br><br><br>def _get(path: str, **params) -&gt; dict:<br>    q = {k: v for k, v in params.items() if v is not None}<br>    url = f&quot;{MARQUEZ_URL}/api/v1/{path}&quot; + ((&quot;?&quot; + urllib.parse.urlencode(q)) if q else &quot;&quot;)<br>    try:<br>        with urllib.request.urlopen(url, timeout=30) as r:<br>            return json.loads(r.read())<br>    except urllib.error.HTTPError as e:<br>        return {&quot;error&quot;: f&quot;HTTP {e.code}&quot;, &quot;detail&quot;: e.read().decode()[:300], &quot;url&quot;: url}<br>    except Exception as e:  # noqa<br>        return {&quot;error&quot;: str(e), &quot;url&quot;: url}<br><br><br>def _q(s: str) -&gt; str:<br>    return urllib.parse.quote(s, safe=&quot;&quot;)<br><br><br>def _out(obj) -&gt; str:<br>    return json.dumps(obj, ensure_ascii=False, indent=1, default=str)<br><br><br>def _run(r: dict) -&gt; dict:<br>    return {&quot;id&quot;: r.get(&quot;id&quot;), &quot;state&quot;: r.get(&quot;state&quot;), &quot;startedAt&quot;: r.get(&quot;startedAt&quot;),<br>            &quot;endedAt&quot;: r.get(&quot;endedAt&quot;),<br>            &quot;durationSec&quot;: round(r[&quot;durationMs&quot;] / 1000, 2) if r.get(&quot;durationMs&quot;) is not None else None}<br><br><br>def _physical(namespace: str, name: str):<br>    &quot;&quot;&quot;Hive tablo adını (hive://..., &#39;de.tablo&#39;) Marquez&#39;in asıl kaydı olan fiziksel yola çevirir<br>    (hdfs://..., &#39;/user/hive/warehouse/de.db/tablo&#39;). Spark/Iceberg olaylarında tablo adı yalnızca<br>    bir takma ad (symlink); sürüm geçmişi ve sütun lineage&#39;ı fiziksel yol altında tutulur.&quot;&quot;&quot;<br>    if not namespace.startswith(&quot;hive://&quot;) or &quot;.&quot; not in name:<br>        return namespace, name<br>    db, table = name.split(&quot;.&quot;, 1)<br>    suffix = f&quot;/{db}.db/{table}&quot;<br>    for n in _get(&quot;namespaces&quot;).get(&quot;namespaces&quot;, []):<br>        ns = n[&quot;name&quot;]<br>        if not ns.startswith((&quot;hdfs://&quot;, &quot;file://&quot;, &quot;s3://&quot;, &quot;s3a://&quot;, &quot;abfss://&quot;, &quot;gs://&quot;)):<br>            continue<br>        for d in _get(f&quot;namespaces/{_q(ns)}/datasets&quot;, limit=500).get(&quot;datasets&quot;, []):<br>            if d[&quot;name&quot;].rstrip(&quot;/&quot;).endswith(suffix):<br>                return ns, d[&quot;name&quot;]<br>    return namespace, name<br><br><br># ---------------------------------------------------------------------------<br># Araçlar<br># ---------------------------------------------------------------------------<br>def list_namespaces() -&gt; str:<br>    &quot;&quot;&quot;Marquez&#39;deki tüm namespace&#39;leri listeler. Job namespace&#39;i (ör. spark_iceberg_lab) ile<br>    veri kaynağı namespace&#39;lerini (sqlserver://..., hive://..., hdfs://...) içerir.&quot;&quot;&quot;<br>    d = _get(&quot;namespaces&quot;)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;name&quot;: n[&quot;name&quot;], &quot;description&quot;: n.get(&quot;description&quot;), &quot;updatedAt&quot;: n.get(&quot;updatedAt&quot;)}<br>                 for n in d.get(&quot;namespaces&quot;, [])])<br><br><br>def list_jobs(namespace: Optional[str] = None) -&gt; str:<br>    &quot;&quot;&quot;Bir namespace&#39;teki job&#39;ları (Spark adımlarını) son çalıştırma durumu ve süresiyle listeler.<br>    namespace verilmezse varsayılan job namespace&#39;i kullanılır.&quot;&quot;&quot;<br>    ns = namespace or DEFAULT_NAMESPACE<br>    d = _get(f&quot;namespaces/{_q(ns)}/jobs&quot;, limit=200)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;name&quot;: j[&quot;name&quot;], &quot;type&quot;: j.get(&quot;type&quot;),<br>                  &quot;inputs&quot;: [f&#39;{i[&quot;namespace&quot;]}::{i[&quot;name&quot;]}&#39; for i in j.get(&quot;inputs&quot;, [])],<br>                  &quot;outputs&quot;: [f&#39;{o[&quot;namespace&quot;]}::{o[&quot;name&quot;]}&#39; for o in j.get(&quot;outputs&quot;, [])],<br>                  &quot;latestRun&quot;: _run(j[&quot;latestRun&quot;]) if j.get(&quot;latestRun&quot;) else None}<br>                 for j in d.get(&quot;jobs&quot;, [])])<br><br><br>def get_job_runs(job: str, namespace: Optional[str] = None, limit: int = 10) -&gt; str:<br>    &quot;&quot;&quot;Bir job&#39;ın son çalıştırmalarını (durum, başlangıç, bitiş, süre) en yeniden eskiye döndürür.<br>    Süre karşılaştırması ve yavaşlama analizi için kullanın.&quot;&quot;&quot;<br>    ns = namespace or DEFAULT_NAMESPACE<br>    d = _get(f&quot;namespaces/{_q(ns)}/jobs/{_q(job)}/runs&quot;, limit=limit)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    runs = [_run(r) for r in d.get(&quot;runs&quot;, [])]<br>    durs = [r[&quot;durationSec&quot;] for r in runs if r[&quot;state&quot;] == &quot;COMPLETED&quot; and r[&quot;durationSec&quot;]]<br>    stats = {&quot;count&quot;: len(runs), &quot;completed&quot;: len(durs),<br>             &quot;minSec&quot;: min(durs) if durs else None, &quot;maxSec&quot;: max(durs) if durs else None,<br>             &quot;avgSec&quot;: round(sum(durs) / len(durs), 2) if durs else None}<br>    return _out({&quot;job&quot;: job, &quot;namespace&quot;: ns, &quot;stats&quot;: stats, &quot;runs&quot;: runs})<br><br><br>def get_run_facets(run_id: str) -&gt; str:<br>    &quot;&quot;&quot;Bir çalıştırmanın (run id) facet&#39;lerini döndürür: Spark sürümü, hata mesajı (errorMessage),<br>    işlem planı bilgileri vb. Başarısız bir çalıştırmanın nedenini incelemek için kullanın.&quot;&quot;&quot;<br>    return _out(_get(f&quot;jobs/runs/{_q(run_id)}/facets&quot;, type=&quot;run&quot;))<br><br><br>def list_datasets(namespace: str) -&gt; str:<br>    &quot;&quot;&quot;Bir veri kaynağı namespace&#39;indeki dataset&#39;leri (tabloları) listeler.<br>    Örnek namespace&#39;ler: &#39;hive://192.168.1.110:9083&#39;, &#39;sqlserver://192.168.1.110:1433&#39;.&quot;&quot;&quot;<br>    d = _get(f&quot;namespaces/{_q(namespace)}/datasets&quot;, limit=200)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;name&quot;: x[&quot;name&quot;], &quot;fields&quot;: len(x.get(&quot;fields&quot;, [])), &quot;updatedAt&quot;: x.get(&quot;updatedAt&quot;),<br>                  &quot;lastModifiedAt&quot;: x.get(&quot;lastModifiedAt&quot;)} for x in d.get(&quot;datasets&quot;, [])])<br><br><br>def get_dataset(namespace: str, name: str) -&gt; str:<br>    &quot;&quot;&quot;Bir dataset&#39;in şemasını (alanlar ve tipleri), son değiştirilme zamanını ve facet adlarını döndürür.&quot;&quot;&quot;<br>    d = _get(f&quot;namespaces/{_q(namespace)}/datasets/{_q(name)}&quot;)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out({&quot;namespace&quot;: d.get(&quot;namespace&quot;), &quot;name&quot;: d.get(&quot;name&quot;),<br>                 &quot;fields&quot;: [{&quot;name&quot;: f[&quot;name&quot;], &quot;type&quot;: f.get(&quot;type&quot;)} for f in d.get(&quot;fields&quot;, [])],<br>                 &quot;currentVersion&quot;: d.get(&quot;currentVersion&quot;), &quot;updatedAt&quot;: d.get(&quot;updatedAt&quot;),<br>                 &quot;lastModifiedAt&quot;: d.get(&quot;lastModifiedAt&quot;), &quot;facets&quot;: sorted((d.get(&quot;facets&quot;) or {}).keys())})<br><br><br>def get_dataset_versions(namespace: str, name: str, limit: int = 10) -&gt; str:<br>    &quot;&quot;&quot;Bir dataset&#39;in sürüm geçmişi: her sürümü hangi çalıştırma üretti, alan listesi (şema değişikliği takibi).<br>    Hive tablo adı (hive://..., &#39;de.tablo&#39;) verilebilir; fiziksel yola otomatik çevrilir.&quot;&quot;&quot;<br>    namespace, name = _physical(namespace, name)<br>    d = _get(f&quot;namespaces/{_q(namespace)}/datasets/{_q(name)}/versions&quot;, limit=limit)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;version&quot;: v.get(&quot;version&quot;), &quot;createdAt&quot;: v.get(&quot;createdAt&quot;),<br>                  &quot;fields&quot;: [f[&quot;name&quot;] for f in v.get(&quot;fields&quot;, [])],<br>                  &quot;createdByRun&quot;: (v.get(&quot;createdByRun&quot;) or {}).get(&quot;id&quot;)} for v in d.get(&quot;versions&quot;, [])])<br><br><br>def get_lineage(namespace: str, name: str, node_type: str = &quot;dataset&quot;, depth: int = 2) -&gt; str:<br>    &quot;&quot;&quot;Bir dataset&#39;in ya da job&#39;ın lineage grafiğini kenar listesi olarak döndürür (kaynak -&gt; hedef).<br>    node_type: &#39;dataset&#39; veya &#39;job&#39;. Etki analizi (bu tablo değişirse ne etkilenir) için kullanın.&quot;&quot;&quot;<br>    d = _get(&quot;lineage&quot;, nodeId=f&quot;{node_type}:{namespace}:{name}&quot;, depth=depth)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    edges = set()<br>    for n in d.get(&quot;graph&quot;, []):<br>        for e in n.get(&quot;outEdges&quot;, []) + n.get(&quot;inEdges&quot;, []):<br>            edges.add((e[&quot;origin&quot;], e[&quot;destination&quot;]))<br>    return _out({&quot;root&quot;: f&quot;{node_type}:{namespace}:{name}&quot;, &quot;depth&quot;: depth,<br>                 &quot;edges&quot;: [{&quot;from&quot;: a, &quot;to&quot;: b} for a, b in sorted(edges)]})<br><br><br>def get_column_lineage(namespace: str, dataset: str, depth: int = 1) -&gt; str:<br>    &quot;&quot;&quot;Bir dataset&#39;in her sütununun hangi kaynak sütunlardan üretildiğini döndürür.<br>    Hive tablo adı (hive://..., &#39;de.tablo&#39;) verilebilir; fiziksel yola otomatik çevrilir.&quot;&quot;&quot;<br>    namespace, dataset = _physical(namespace, dataset)<br>    d = _get(&quot;column-lineage&quot;, nodeId=f&quot;dataset:{namespace}:{dataset}&quot;, depth=depth)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    cols = []<br>    for n in d.get(&quot;graph&quot;, []):<br>        data = n.get(&quot;data&quot;) or {}<br>        if data.get(&quot;dataset&quot;) != dataset or not data.get(&quot;inputFields&quot;):<br>            continue<br>        cols.append({&quot;field&quot;: data.get(&quot;field&quot;), &quot;type&quot;: data.get(&quot;fieldType&quot;),<br>                     &quot;inputs&quot;: [{&quot;from&quot;: f&#39;{i[&quot;dataset&quot;]}.{i[&quot;field&quot;]}&#39;,<br>                                 &quot;transformation&quot;: i.get(&quot;transformationType&quot;) or data.get(&quot;transformationType&quot;),<br>                                 &quot;description&quot;: i.get(&quot;transformationDescription&quot;)<br>                                 or data.get(&quot;transformationDescription&quot;)}<br>                                for i in data.get(&quot;inputFields&quot;, [])]})<br>    return _out({&quot;dataset&quot;: f&quot;{namespace}::{dataset}&quot;, &quot;columns&quot;: cols})<br><br><br>def search(query: str, limit: int = 20) -&gt; str:<br>    &quot;&quot;&quot;Job ve dataset adlarında arama yapar (ör. &#39;product&#39;, &#39;merge&#39;, &#39;agg&#39;).&quot;&quot;&quot;<br>    d = _get(&quot;search&quot;, q=query, limit=limit)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;type&quot;: r.get(&quot;type&quot;), &quot;name&quot;: r.get(&quot;name&quot;), &quot;namespace&quot;: r.get(&quot;namespace&quot;),<br>                  &quot;updatedAt&quot;: r.get(&quot;updatedAt&quot;)} for r in d.get(&quot;results&quot;, [])])<br><br><br>def recent_events(limit: int = 20) -&gt; str:<br>    &quot;&quot;&quot;En son gelen ham OpenLineage olaylarının özeti: zaman, tür (START/COMPLETE/FAIL), job, giriş/çıkış.<br>    Lineage entegrasyonunu doğrulamak ve eksik olayları bulmak için kullanın.&quot;&quot;&quot;<br>    d = _get(&quot;events/lineage&quot;, limit=limit)<br>    if &quot;error&quot; in d:<br>        return _out(d)<br>    return _out([{&quot;eventTime&quot;: e.get(&quot;eventTime&quot;), &quot;eventType&quot;: e.get(&quot;eventType&quot;),<br>                  &quot;job&quot;: (e.get(&quot;job&quot;) or {}).get(&quot;name&quot;), &quot;runId&quot;: (e.get(&quot;run&quot;) or {}).get(&quot;runId&quot;),<br>                  &quot;inputs&quot;: [i[&quot;name&quot;] for i in e.get(&quot;inputs&quot;, [])],<br>                  &quot;outputs&quot;: [o[&quot;name&quot;] for o in e.get(&quot;outputs&quot;, [])]} for e in d.get(&quot;events&quot;, [])])<br><br><br>TOOLS = [list_namespaces, list_jobs, get_job_runs, get_run_facets, list_datasets, get_dataset,<br>         get_dataset_versions, get_lineage, get_column_lineage, search, recent_events]<br><br><br>def _is_error(out: str) -&gt; bool:<br>    return &#39;&quot;error&quot;&#39; in out[:40]<br><br><br>def _selftest():<br>    hive = &quot;hive://192.168.1.110:9083&quot;<br>    checks = [<br>        (&quot;list_namespaces&quot;, lambda: list_namespaces()),<br>        (&quot;list_jobs&quot;, lambda: list_jobs()),<br>        (&quot;get_job_runs&quot;, lambda: get_job_runs(&quot;adventureworks_product_pipeline&quot;, limit=3)),<br>        (&quot;list_datasets&quot;, lambda: list_datasets(hive)),<br>        (&quot;get_dataset&quot;, lambda: get_dataset(hive, &quot;de.dim_product_enriched&quot;)),<br>        (&quot;get_dataset_versions&quot;, lambda: get_dataset_versions(hive, &quot;de.dim_product_enriched&quot;, 3)),<br>        (&quot;get_lineage&quot;, lambda: get_lineage(hive, &quot;de.dim_product_enriched&quot;)),<br>        (&quot;get_column_lineage&quot;, lambda: get_column_lineage(hive, &quot;de.dim_product_enriched&quot;)),<br>        (&quot;search&quot;, lambda: search(&quot;product&quot;, 5)),<br>        (&quot;recent_events&quot;, lambda: recent_events(3)),<br>    ]<br>    ok = True<br>    for name, fn in checks:<br>        out = fn()<br>        err = _is_error(out)<br>        ok = ok and not err<br>        print(f&quot;{&#39;FAIL&#39; if err else &#39;OK  &#39;} {name:22s} {len(out):6d} karakter  {out[:110]!r}&quot;)<br>    runs = json.loads(get_job_runs(&quot;adventureworks_product_pipeline&quot;, limit=1))[&quot;runs&quot;]<br>    if runs:<br>        out = get_run_facets(runs[0][&quot;id&quot;])<br>        print(f&quot;{&#39;FAIL&#39; if _is_error(out) else &#39;OK  &#39;} {&#39;get_run_facets&#39;:22s} {len(out):6d} karakter&quot;)<br>    sys.exit(0 if ok else 1)<br><br><br>def main():<br>    if &quot;--selftest&quot; in sys.argv:<br>        _selftest()<br>    server = _build_server()<br>    server.run()  # stdio<br><br><br>def _build_server():<br>    # pip install &quot;mcp[cli]&quot;  (Python 3.10+). mcp 2.x&#39;te FastMCP -&gt; MCPServer olarak yeniden adlandırıldı.<br>    try:<br>        from mcp.server.mcpserver import MCPServer as Server  # mcp &gt;= 2<br>    except ImportError:<br>        from mcp.server.fastmcp import FastMCP as Server  # mcp 1.x<br>    server = Server(&quot;marquez&quot;)<br>    for fn in TOOLS:<br>        server.tool()(fn)<br>    return server<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>&quot;&quot;&quot;<br>OpenMetadata MCP köprüsü (stdio &lt;-&gt; HTTP) — yalnızca Python standart kütüphanesi.<br><br>Claude Desktop gibi stdio konuşan bir MCP istemcisini, OpenMetadata&#39;nın HTTP MCP uç noktasına<br>(/mcp) token başlığıyla bağlar.<br><br>Neden mcp-remote değil? mcp-remote (tüm sürümleri) bağlanmadan önce OAuth keşfi yapıyor; OpenMetadata<br>2.0.3 keşif yanıtında yetkilendirme sunucusunu göreli (&quot;/mcp&quot;) bildirdiği için &quot;Invalid URL&quot; ile çöküyor.<br>Bu köprü OAuth&#39;a hiç girmez: her JSON-RPC mesajını Authorization başlığıyla POST eder, yanıtı geri yazar.<br><br>Ortam değişkenleri:<br>    OM_MCP_URL    (varsayılan http://localhost:8585/mcp)<br>    OM_TOKEN      OpenMetadata JWT (bot ya da kişisel token; &quot;Bearer &quot; öneki olsa da olmasa da olur)<br>    OM_BRIDGE_LOG (isteğe bağlı) hata ayıklama log dosyası<br><br>Claude Desktop:<br>    &quot;OpenMetadata&quot;: {&quot;command&quot;: &quot;python&quot;, &quot;args&quot;: [&quot;C:\\\\mcp\\\\openmetadata_mcp_bridge.py&quot;],<br>                     &quot;env&quot;: {&quot;OM_MCP_URL&quot;: &quot;http://localhost:8585/mcp&quot;, &quot;OM_TOKEN&quot;: &quot;&lt;JWT&gt;&quot;}}<br>&quot;&quot;&quot;<br>import json<br>import os<br>import sys<br>import threading<br>import urllib.error<br>import urllib.request<br><br>URL = os.getenv(&quot;OM_MCP_URL&quot;, &quot;http://localhost:8585/mcp&quot;)<br>TOKEN = os.getenv(&quot;OM_TOKEN&quot;, &quot;&quot;).strip()<br>if TOKEN.lower().startswith(&quot;bearer &quot;):<br>    TOKEN = TOKEN[7:].strip()<br>LOG = os.getenv(&quot;OM_BRIDGE_LOG&quot;)<br>TIMEOUT = float(os.getenv(&quot;OM_BRIDGE_TIMEOUT&quot;, &quot;120&quot;))<br><br>_out_lock = threading.Lock()<br>_session = {&quot;id&quot;: None, &quot;protocol&quot;: None}<br><br><br>def log(msg):<br>    if LOG:<br>        with open(LOG, &quot;a&quot;, encoding=&quot;utf-8&quot;) as f:<br>            f.write(msg + &quot;\n&quot;)<br>    print(f&quot;[om-bridge] {msg}&quot;, file=sys.stderr, flush=True)<br><br><br>def emit(obj):<br>    data = json.dumps(obj, ensure_ascii=False)<br>    with _out_lock:<br>        sys.stdout.write(data + &quot;\n&quot;)<br>        sys.stdout.flush()<br><br><br>def parse_body(body: str, content_type: str):<br>    &quot;&quot;&quot;JSON ya da SSE (text/event-stream) yanıtından JSON-RPC mesajlarını çıkarır.&quot;&quot;&quot;<br>    body = body.strip()<br>    if not body:<br>        return []<br>    if &quot;text/event-stream&quot; in content_type or body.startswith((&quot;event:&quot;, &quot;data:&quot;, &quot;id:&quot;)):<br>        msgs, buf = [], []<br>        for line in body.splitlines() + [&quot;&quot;]:<br>            if line.startswith(&quot;data:&quot;):<br>                buf.append(line[5:].lstrip())<br>            elif line.strip() == &quot;&quot; and buf:<br>                try:<br>                    msgs.append(json.loads(&quot;\n&quot;.join(buf)))<br>                except ValueError:<br>                    log(&quot;SSE verisi çözülemedi: &quot; + &quot;\n&quot;.join(buf)[:200])<br>                buf = []<br>        return msgs<br>    parsed = json.loads(body)<br>    return parsed if isinstance(parsed, list) else [parsed]<br><br><br>def error_for(msg, code, text):<br>    if isinstance(msg, dict) and &quot;id&quot; in msg:<br>        emit({&quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;id&quot;: msg[&quot;id&quot;], &quot;error&quot;: {&quot;code&quot;: code, &quot;message&quot;: text}})<br><br><br>def forward(msg):<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;, &quot;Accept&quot;: &quot;application/json, text/event-stream&quot;}<br>    if TOKEN:<br>        headers[&quot;Authorization&quot;] = f&quot;Bearer {TOKEN}&quot;<br>    if _session[&quot;id&quot;]:<br>        headers[&quot;Mcp-Session-Id&quot;] = _session[&quot;id&quot;]<br>    if _session[&quot;protocol&quot;]:<br>        headers[&quot;MCP-Protocol-Version&quot;] = _session[&quot;protocol&quot;]<br>    req = urllib.request.Request(URL, data=json.dumps(msg).encode(&quot;utf-8&quot;), headers=headers, method=&quot;POST&quot;)<br>    try:<br>        with urllib.request.urlopen(req, timeout=TIMEOUT) as r:<br>            sid = r.headers.get(&quot;Mcp-Session-Id&quot;)<br>            if sid:<br>                _session[&quot;id&quot;] = sid<br>            body = r.read().decode(&quot;utf-8&quot;, &quot;replace&quot;)<br>            for out in parse_body(body, r.headers.get(&quot;Content-Type&quot;, &quot;&quot;)):<br>                if isinstance(out, dict) and out.get(&quot;id&quot;) is not None and &quot;result&quot; in out \<br>                        and isinstance(out[&quot;result&quot;], dict) and out[&quot;result&quot;].get(&quot;protocolVersion&quot;):<br>                    _session[&quot;protocol&quot;] = out[&quot;result&quot;][&quot;protocolVersion&quot;]<br>                emit(out)<br>    except urllib.error.HTTPError as e:<br>        detail = e.read().decode(&quot;utf-8&quot;, &quot;replace&quot;)[:300]<br>        log(f&quot;HTTP {e.code} ({msg.get(&#39;method&#39;) if isinstance(msg, dict) else &#39;?&#39;}): {detail}&quot;)<br>        try:<br>            for out in parse_body(detail, e.headers.get(&quot;Content-Type&quot;, &quot;&quot;)):<br>                if isinstance(out, dict) and (&quot;error&quot; in out or &quot;result&quot; in out):<br>                    if out.get(&quot;id&quot;) is None and isinstance(msg, dict) and &quot;id&quot; in msg:<br>                        out[&quot;id&quot;] = msg[&quot;id&quot;]<br>                    emit(out)<br>                    return<br>        except ValueError:<br>            pass<br>        error_for(msg, -32001, f&quot;OpenMetadata HTTP {e.code}: {detail}&quot;)<br>    except Exception as e:  # noqa<br>        log(f&quot;Bağlantı hatası: {e}&quot;)<br>        error_for(msg, -32002, f&quot;OpenMetadata&#39;ya ulaşılamadı ({URL}): {e}&quot;)<br><br><br>def main():<br>    # Windows&#39;ta stdin/stdout varsayılan olarak UTF-8 değil (ör. cp1254); MCP mesajları UTF-8 ve \n ile ayrılır.<br>    for stream, kw in ((sys.stdin, {}), (sys.stdout, {&quot;newline&quot;: &quot;\n&quot;}), (sys.stderr, {})):<br>        try:<br>            stream.reconfigure(encoding=&quot;utf-8&quot;, **kw)<br>        except (AttributeError, ValueError):<br>            pass<br>    if not TOKEN:<br>        log(&quot;UYARI: OM_TOKEN tanımlı değil; OpenMetadata 401 döndürecek.&quot;)<br>    log(f&quot;başladı -&gt; {URL}&quot;)<br>    for raw in sys.stdin:<br>        raw = raw.strip()<br>        if not raw:<br>            continue<br>        try:<br>            msg = json.loads(raw)<br>        except ValueError:<br>            log(&quot;geçersiz JSON: &quot; + raw[:200])<br>            continue<br>        if isinstance(msg, dict) and msg.get(&quot;method&quot;) == &quot;initialize&quot;:<br>            forward(msg)  # oturum bilgisi sonraki isteklerden önce gelsin<br>        else:<br>            threading.Thread(target=forward, args=(msg,), daemon=True).start()<br>    log(&quot;stdin kapandı, çıkılıyor&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Bu dosyaları tanımladıktan sonra claude_desktop_config.json dosyasına aşağıdaki eklemeleri yapıyoruz.</p><pre>&quot;OpenMetadata&quot;: {<br>      &quot;command&quot;: &quot;python&quot;,<br>      &quot;args&quot;: [<br>        &quot;C:\\mcp\\openmetadata_mcp_bridge.py&quot;<br>      ],<br>      &quot;env&quot;: {<br>        &quot;OM_MCP_URL&quot;: &quot;http://localhost:8585/mcp&quot;,<br>        &quot;OM_TOKEN&quot;: &quot;your_om_token&quot;,<br>        &quot;OM_BRIDGE_LOG&quot;: &quot;C:\\mcp\\openmetadata_bridge.log&quot;<br>      }<br>    },<br>    &quot;Marquez&quot;: {<br>      &quot;command&quot;: &quot;python&quot;,<br>      &quot;args&quot;: [<br>        &quot;C:\\mcp\\marquez_mcp_server.py&quot;<br>      ],<br>      &quot;env&quot;: {<br>        &quot;MARQUEZ_URL&quot;: &quot;http://localhost:5000&quot;,<br>        &quot;MARQUEZ_NAMESPACE&quot;: &quot;spark_iceberg_lab&quot;<br>      }<br>    }</pre><p>Bunları ekledikten sonra Claude Desktop’u kapatıp tekrardan açıyoruz.</p><p>Hadi gelin, Claude Desktop üzerinden belirli sorular sorarak nasıl cevaplar aldığımıza bir bakalım.</p><blockquote>Soru:“Ürün domain’inde hangi tablolar var? Her birinin sahibi, Tier’ı ve sertifikası ne?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFubThe8WNFJFt8L_YjF0g.png" /></figure><blockquote>Soru:“‘Marj Yüzdesi’ sözlük terimi hangi tablolarda, hangi sütunlarda kullanılıyor?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d1-VE2Coq6EvL0FTTGh1A.png" /></figure><blockquote>Soru:“SQL Server’daki Production.ProductSubcategory tablosunda bir sütunun adını değiştirirsem hangi tablolar ve metrikler etkilenir?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmCVUaHTsTzX-04ZlhdCVw.png" /></figure><blockquote>Soru: “dim_product_enriched tablosunun şeması zaman içinde değişti mi?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc1T9IX9426P3Iacq74qKQ.png" /></figure><blockquote>Soru:“dim_product_enriched tablosunun her sütunu hangi kaynak sütunlardan geliyor?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRmPD5xfnjtFSGNvhlO1vw.png" /></figure><p>Evet, MCP Server yardımıyla herhangi bir LLM modeli üzerinden interaktif bir şekilde verilerin hikâyesi veya oluşumuyla alakalı her soruya cevap bulabiliyoruz. Normal akışlarımızda bu sorulara cevap bulmak kurumun bulundurduğu veri boyutuna veya organizasyona göre değişiklik gösterebiliyor. Umarım yazım sizler için faydalı olmuştur. Herhangi bir görüşünüz veya sorunuz varsa, iletişime geçebiliriz. Teşekkürler :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0344d86b3368" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP Server, Claude Sonnet 4 ve Apache Airflow Entegrasyonu]]></title>
            <link>https://emreevcimen.medium.com/mcp-server-claude-sonnet-4-ve-apache-airflow-entegrasyonu-f9c242445c88?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c242445c88</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 03:20:49 GMT</pubDate>
            <atom:updated>2025-06-23T03:21:12.778Z</atom:updated>
            <content:encoded><![CDATA[<p>🚀🚀Herkese Merhabalar, bugünkü yazımda sizlere MCP Server kullanarak Apache Airflow üzerinde promptlar yardımıyla nasıl işlem yapacağımızı anlatacağım ama öncellikle gelin mimariye, bu işlemi yapmak için kurmamız gereken araçlara ve teknik kavramlara bakalım.</p><h4><strong>Mimari</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*dJ58p4TJDln-v9yKFPkf8A.png" /></figure><h4><strong>Kurulum yapılması gereken araçlar</strong></h4><p>→ <a href="https://claude.ai/download">Claude Desktop</a></p><p>→ <a href="https://hub.docker.com/r/apache/airflow">Apache Airflow(Docker)</a></p><p>→ <a href="https://www.python.org/downloads/">Python</a></p><p>→ <a href="https://docs.astral.sh/uv/getting-started/installation/#standalone-installer">uv</a></p><p>→ <a href="https://git-scm.com/downloads">git</a></p><h4><strong>Teknik Kavramlar</strong></h4><p>→ <strong>LLM(Large Language Model)</strong>, çok metin okuyarak eğitilmiş ve insan gibi metin yazıp konuşabilen bir yapay zekadır.</p><p>→ <strong>MCP Server: </strong>Model Context Protocol Server, bir yapay zeka modelinin çalışırken <strong>ihtiyaç duyduğu bağlamı (context)</strong> ona <strong>sağlayan ve yöneten bir sunucudur</strong>.</p><p><strong>Ne işe yarar?</strong></p><p>Bir yapay zeka modeli (örneğin ChatGPT), daha doğru ve tutarlı cevaplar verebilmek için <strong>bazı bilgilere</strong> ihtiyaç duyar:</p><ul><li>Kullanıcının kim olduğu</li><li>Önceki konuşmalar neydi</li><li>Hangi görev üzerinde çalışılıyor</li><li>Hangi araçlar kullanılabilir</li></ul><p>İşte bu bilgileri sağlayan sistemin adı <strong>Model Context Protocol Server</strong>’dır.</p><p>→ <strong>Claude Sonnet 4</strong>, Anthropic tarafından geliştirilen <strong>Claude yapay zeka ailesinin</strong> bir üyesidir. 2024 yılında piyasaya sürülen bu model, <strong>özellikle doğal dil anlama, yazma ve analiz etme konularında güçlü bir büyük dil modeli </strong>olarak öne çıkar.</p><p>Teknik kavramları çok sıkmayacak şekilde basit ve detaya inmeden aktarmaya çalıştım. Çünkü yazımın amacı çok fazla tekniğe boğmadan uygulamalı olarak bunu sizlere aktarmak.</p><p>İlk olarak yapmamız gereken kullanacağımız LLM Modeline(Claude Sonnet 4) Apache Airflow yetkinliği kazandıracak ve ona Apache Airflow ile alakalı bağlamı sunacağımız bir MCP Server oluşturmak. Burada 2 seçeneğimiz var. Kendimiz de sıfırdan bir MCP Server oluşturabiliriz veya mevcutta olan hazır MCP Serverları da kullanabiliriz. Ben bu yazımda aşağıda paylaştığım Github linkinde Apache Airflow için yönlendirilen MCP Server’ı kullanacağım.</p><ul><li><a href="https://github.com/modelcontextprotocol/servers">GitHub - modelcontextprotocol/servers: Model Context Protocol Servers</a></li><li><a href="https://github.com/yangkyeongmo/mcp-server-apache-airflow">GitHub - yangkyeongmo/mcp-server-apache-airflow</a></li></ul><pre>git clone https://github.com/yangkyeongmo/mcp-server-apache-airflow.git</pre><p>Bu işi hallettiğimize göre<strong> Claude Desktop</strong> içerisine girerek bu MCP Server’ı oraya tanımlayalım. Yapmanız gereken <strong>File</strong> altındaki <strong>Settings</strong> kısmına gelerek burada <strong>Developer </strong>altına gitmeniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*Tg9dlYW1M4rw0FOp5KT9_A.png" /></figure><p>Daha sonrasında <strong>Edit Config</strong> butonuna tıklayarak <strong>claude_desktop_config </strong>içerisine girip aşağıdaki gibi bir ayarlama yapmanız gerekli.</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;mcp-server-apache-airflow&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [<br>        &quot;--directory&quot;,<br>        &quot;C:\\Users\\ASUS\\Desktop\\mcp-server-apache-airflow&quot;,<br>        &quot;run&quot;,<br>        &quot;mcp-server-apache-airflow&quot;<br>      ],<br>      &quot;env&quot;: {<br>        &quot;AIRFLOW_HOST&quot;: &quot;http://your_airflow_hostname:your_airflow_port&quot;,<br>        &quot;AIRFLOW_USERNAME&quot;: &quot;your_username&quot;,<br>        &quot;AIRFLOW_PASSWORD&quot;: &quot;your_password&quot;,<br>        &quot;AIRFLOW_API_VERSION&quot;: &quot;v1&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Kendi bilgilerinize göre değişkenleri belirtip dosyayı kaydettikten sonra Claude Desktop ekranını kapatın.</p><blockquote><strong>Not : </strong>Windows kullanılan arkadaşlar Görev Yöneticisinden de Claude Desktop uygulamasının kapalı olup olmadığını kontrol etsin.)</blockquote><p>Claude Desktop ekranını tekrar açıp Developer sekmesine geldiğinizde yukarıdaki ekran görüntüsünde paylaştığım gibi <strong>mcp-server-apache-airflow </strong>adında oluşan server’ı burada görünmeli.</p><p>MCP Server’ı da başarılı şekilde ayağa kaldırdığımıza göre gelin Apache Airlfow üzerinde aktif olan bir DAG’i promt yazarak pasif hale çekelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulmdexP4aFGeL_vdQPVzxg.png" /><figcaption><strong>Prompt Öncesi</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDZG6obtMmr0gIlnp1APIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG4G2BoREW5Pfml-t0aBhA.png" /><figcaption><strong>Prompt Sonrası</strong></figcaption></figure><p>Görmüş olduğunuz gibi yazdığımız prompt ile birlikte artık DAG’ı pasif hale getirdik ve bununla birlikte oluşacak sonuçlarıda kendince maddeliyor.🔥</p><p>Bir de son çalışan DAGRun için tekrardan clear etmesini isteyelim ve Web UI’a gelip nasıl davrandığına bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ePqqVDuRXn3tU1GNNpcjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7w71d-lTNjoHJO5D1aqWw.png" /><figcaption><strong>Prompt Sonrası</strong></figcaption></figure><p>Evet tam da istediğimiz gibi son çalışan işi clear ederek tekrardan çalışmasını sağladı.🔥</p><p>Son olarak Airflow üzerinde tanımlı olan değişkenleri listelettirelim ve seçtiğimiz herhangi bir değişkeni silmesini söyleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jARLzqcshM3WAh98vPmxIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwzCKNtan8S7t1uZGklLAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvTG_V1sns1qLFXlh8bKPg.png" /></figure><p>Ekran görüntülerinde görmüş olduğunuz gibi ilk önce tüm değişkenleri listedi ve sonra istediğim store_id değişkenini sildi.</p><p>Bu MCP Server’ı kullanarak daha birçok işlem yapabiliriz.(DAG yazıp dags klasörüne gönderilmesi,değişken oluşturma,connection oluşturma,pool oluşturma vb.)</p><p>AI Agent’lar kullanarak bunu daha efektif hale getirerek hem Developer hem de Operasyon da çalışan insanlar için daha efektif ve dinamik sistemler kurgulayabiliriz.</p><p>Yazımı okuduğunuz için çok teşekkürler. Umarım sizler için faydalı ve ilham verici bir yazı olmuştur. 🙏🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c242445c88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Airflow da Jupyter Notebook Kodu Çalıştırma]]></title>
            <link>https://emreevcimen.medium.com/apache-airflow-da-jupyter-notebook-kodu-%C3%A7al%C4%B1%C5%9Ft%C4%B1rma-267a72c7d0be?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/267a72c7d0be</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 21:50:15 GMT</pubDate>
            <atom:updated>2024-09-05T04:29:36.160Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar bu yazımda sizlere yazmış olduğumuz bir Jupyter Notebook kodunu Apache Airflow içerisinde tetiklenmesi için nasıl adımlar gerçekleştirmeliyiz onu anlatacağım.</p><p>Öncelikle ilk yapmamız gereken Airflow içerisinde bize bunu sağlayan <strong>PapermillOperator’un </strong>provider’nı kütüphanemize eklemek.</p><pre>pip install apache-airflow-providers-papermill<br>#İlgili kütüphanenin kontrol edilmesi<br>pip freeze | grep papermill<br>Output:<br>apache-airflow-providers-papermill==3.8.0<br>papermill==2.6.0</pre><p>Daha sonrasında tetikleyeceğimiz Jupyter Notebook kodunu oluşturmak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjkVwY0JC0GwkI1E_8XHbg.png" /></figure><p>Yukarıda görmüş olduğunuz gibi basit bir Spark Job’ı oluşturduk. Şimdi bu Jupyter Notebook kodunu dışardan tetiklerken parametre olarak almak istediğimiz değişken <strong>pmonth</strong> değişkeni için aşağıda ekran görüntüsünde paylaştığım gibi <strong>View </strong>sekmesindeki <strong>Cell Toolbar</strong> kısmında bulunan <strong>Tags</strong> kısmına tıklayarak <strong>pmonth’un </strong>olduğu hücreye gelerek <strong>parameters tag’ini ekliyoruz.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjLMmyAWagx3KQhNALV_yg.png" /></figure><p><strong>pmonth</strong> değerini ben test ederken burda belirtmiş olsam da Airflow tarafında tetiklediğimde orada belirlediğim değer benim değerimi ezerek onu dikkate alarak kodu çalıştıracak.</p><p>Şimdi de bu Jupyter Notebook kodunu tetikleyeceğimiz akışı Airflow’da oluşturalım.</p><pre>from datetime import datetime<br>from airflow.models.dag import DAG<br>from airflow.providers.papermill.operators.papermill import PapermillOperator<br>from airflow.operators.empty import EmptyOperator<br><br><br>with DAG(<br>    dag_id=&#39;example_papermill_operator&#39;,<br>    default_args={<br>        &#39;retries&#39;: 0,<br>        &#39;owner&#39;: &#39;emre&#39;,<br>    },<br>    schedule=&#39;@monthly&#39;,<br>    start_date=datetime(2024, 9, 2),<br>    catchup=False<br>) as dag:<br>    <br>    start = EmptyOperator(task_id=&quot;start&quot;)<br><br>    notebook_task = PapermillOperator(<br>        task_id=&quot;run_spark_notebook&quot;,<br>        input_nb=&quot;/home/emre/airflow/include/AlbumList_SparkJupyterNotebook.ipynb&quot;,<br>        output_nb=&quot;/home/emre/airflow/include/out-{{ execution_date }}.ipynb&quot;,<br>        parameters={&quot;pmonth&quot;: &quot;{{ execution_date.strftime(&#39;%Y%m&#39;) }}&quot;},<br>    )<br>    <br>    finish = EmptyOperator(task_id=&quot;finish&quot;)<br>    <br>start &gt;&gt; notebook_task &gt;&gt; finish</pre><p><strong>PapermillOperator’unu </strong>kullanarak <strong>input_nb</strong> kısmında notebook’un bulunduğu dizni output kısmında da bu jupyter çalıştığı ve hücreler çıktılarını görebileceğimiz yeni bir notebook dosyası oluşturmakta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm_CVPGmEoaLjELcOhKDog.png" /></figure><p>Ekran görüntüsünde görmüş olduğumuz gibi notebook içerisindeki kodlar başarılı şekilde çalışmış gözüküyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxjdwknhaeZtRz-FK--uag.png" /></figure><p><strong>out-2024–09–03*.ipynb </strong>dosyasına bakarsak ilgili kodları çıktılarıyla birlikte görüntüleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZt70pJptjS2ptY1hcuRmg.png" /></figure><p>Burada dikkat etmek istediğimiz kısım pmonth değeri gördüğünüz gibi benim bir değer belirtmiş olmama rağmen Airflow içerisinde gönderdiğim değeri dikkate alarak benim set ettiğim değeri ezmiş oldu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QBPKZxD2bkk1lXuJ0tdOQQ.png" /></figure><p>Tabloyu kontrol etmek istediğimizde de başarılı şekilde dolum işleminin gerçekleştiğini görebiliriz.</p><p>Okuduğunuz için teşekkürler. Umarım sizler için faydalı bir yazı olmuştur🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267a72c7d0be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes ile Data Pipeline Projesi Geliştirme(Part-1)]]></title>
            <link>https://emreevcimen.medium.com/kubernetes-ile-data-pipeline-projesi-geli%C5%9Ftirme-part-1-3fc8cc95414e?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fc8cc95414e</guid>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Mon, 27 May 2024 00:12:47 GMT</pubDate>
            <atom:updated>2024-05-27T00:12:47.529Z</atom:updated>
            <content:encoded><![CDATA[<p>🎯Merhabalar bu yazımda sizlere <strong>Kubernetes</strong> kullanarak bir Data Pipeline projesi nasıl oluştururuz onu anlatacağım. İlk önce projemizin genel mimarisine bir bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBEtG5AoOEknl-YkIBC5_g.png" /></figure><p>Yukarıda görmüş olduğumuz gibi <strong>Medallion Architecture’</strong>dan<strong> </strong>yararlanarak bir Veri Modellemesi yapıp en sonunda da <strong>Apache Superset</strong> kullanarak görselleştirmeler yapacağız.</p><p>İlk önce <strong>minikube </strong>aracılığıyla<strong> </strong>3 node’lu bir <strong>Kubernetes Cluster</strong>’ı oluşturalım.</p><pre>#Oluşacak Cluster için donanımsal kaynak ayarlamaları yapıyoruz.<br>minikube config set memory 1024<br>minikube config set cpus 4<br>minikube config view<br><br>#3 Node&#39;lu k8s-bootcamp-cluster adında bir Cluster oluşturuyoruz.<br>minikube start --nodes 3 -p k8s-bootcamp-cluster<br>minikube profile k8s-bootcamp-cluster<br><br>#Worker olarak düşündüğümüz node&#39;lara worker etiketi veriyoruz.<br>kubectl label node k8s-bootcamp-cluster-m02 node-role.kubernetes.io/worker=worker<br>kubectl label node k8s-bootcamp-cluster-m03 node-role.kubernetes.io/worker=worker</pre><pre>kubectl get nodes<br><br>OUTPUT:<br>NAME                       STATUS   ROLES                  AGE     VERSION<br>k8s-bootcamp-cluster       Ready    control-plane,master   2m40s   v1.23.1<br>k8s-bootcamp-cluster-m02   Ready    worker                 2m7s    v1.23.1<br>k8s-bootcamp-cluster-m03   Ready    worker                 93s     v1.23.1</pre><h4>Minio servisini ayağa kaldırma:</h4><pre>kubectl create ns minio-dev</pre><p>Minio servisini ayağa kaldırmak için <strong>minio-dev </strong>adında bir namespace oluşturuyoruz.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: minio<br>  namespace: minio-dev<br>  labels:<br>    app: minio<br>spec:<br>  replicas: 2<br>  template:<br>    metadata:<br>      name: minio<br>      labels:<br>        app: minio<br>    spec:<br>      volumes:<br>      - name: data<br>        nfs:<br>          server: 192.168.49.1          <br>          path: /nfs/share<br>      containers:<br>        - name: minio<br>          image: quay.io/minio/minio:latest<br>          imagePullPolicy: IfNotPresent<br>          livenessProbe:<br>            httpGet:<br>              path: /minio/health/live<br>              port: 9000<br>            initialDelaySeconds: 120<br>            periodSeconds: 20<br>          readinessProbe:<br>            httpGet:<br>              path: /minio/health/ready<br>              port: 9000<br>            initialDelaySeconds: 120<br>            periodSeconds: 20<br>          resources:<br>            requests:<br>              memory: &quot;1000Mi&quot;<br>              cpu: &quot;1000m&quot;<br>            limits:<br>              memory: &quot;1500Mi&quot;<br>              cpu: &quot;1500m&quot;<br>          volumeMounts:<br>            - mountPath: /data<br>              name: data<br>          command:<br>            - /bin/bash<br>            - -c<br>          args:<br>              - minio server /data --console-address :9090<br>      restartPolicy: Always<br>  selector:<br>    matchLabels:<br>      app: minio<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: minio<br>  namespace: minio-dev<br>spec:<br>  selector:<br>    app: minio<br>  ports:<br>    - port: 9090<br>      name: console<br>    - port: 9000<br>      name: s3<br>  type: ClusterIP</pre><p>Yukarıdaki Yaml’da dikkatinizi çekmek istediğim ilk nokta <strong>Volume </strong>kısmında olacak. Benim oluşturduğum Cluster 3 Node’dan oluşmakta bu <strong>volumeMount</strong> kısmında belirttiğim path tüm node’lardan erişilebilen işlem yapılabilen bir path olmalı. Bunun için Kubernetes birden fazla çözüm sunmakta. Ben bu yazımda <strong>nfs</strong> ile bu süreci ilerleteceğim. <strong>NFS</strong> çözümünden yararlanabilmek için lokalime kurulumunu gerçekleştiriyorum.</p><pre>sudo apt update<br>sudo apt upgrade<br>sudo apt install nfs-kernel-server -y<br>sudo systemctl status nfs-kernel-server.service<br><br>sudo mkdir -p /nfs/share/<br>sudo chown emre:emre /nfs/share/<br>sudo chmod 777 /nfs/share/<br>vi /etc/exports<br>---<br>/nfs/share/ 192.168.49.0/24(rw,sync,no_root_squash,no_subtree_check)<br>---<br><br>exportfs -a<br>exportfs -v<br>sudo systemctl restart nfs-kernel-server<br>showmount -e <br></pre><p>Yukarıdaki script ile lokalimize nfs kurulumunu gerçekleştirmiş oluyoruz. Yaml içerisinde nfs kısmında belirttiğimiz Server bilgisini de aşağıdaki kod yardımıyla bulabiliriz.</p><pre>minikube ssh -n k8s-bootcamp-cls<br>ip r | grep default</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*cA_pLt2HWGWaEdKSfMkqMg.png" /></figure><pre>kubectl apply -f minio.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9333B1XNyQr60ibaDyIJUQ.png" /></figure><p>Yaml içerisinde oluşturmuş olduğumuz <strong>deployment</strong> ve <strong>service</strong> başarılı şekilde ayağa kalkmış gözüküyor.</p><p>Lokal’den erişmek için ayrı terminal ekranlarında <strong>port-forward</strong> komutlarını çalıştıralım şimdi.</p><pre>kubectl port-forward svc/minio -n minio-dev 9000<br>kubectl port-forward svc/minio -n minio-dev 9090</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpRVNuTUb4O26KdR1x12Cw.png" /></figure><p><a href="http://localhost:9090/"><strong>http://localhost:9090</strong></a><strong> </strong>adresine giderek Kullanıcı Adı ve Şifre kısmına <strong>minioadmin </strong>bilgisini girerek <strong>Minio Web UI</strong> kısmına erişmiş olacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcSolnc917Y2WXYgedKckQ.png" /></figure><p>Çalıştıracağımız <strong>Spark</strong> ve <strong>Python</strong> kodlarında kullanacağımız Key’ler için <strong>Access Keys </strong>sekmesinden oluşturma işlemini gerçekleştiriyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuHa4vVKXFZHOGQSTGpgLg.png" /></figure><pre>import boto3<br>import logging<br>import configparser<br><br><br>parser = configparser.ConfigParser()<br>parser.read(&quot;conf.ini&quot;)<br><br><br>s3 = boto3.client(&#39;s3&#39;,<br>                  endpoint_url=&#39;http://localhost:9000&#39;,<br>                  aws_access_key_id=parser.get(&quot;keys&quot;,&quot;minio_access_key_id&quot;),           <br>                  aws_secret_access_key=parser.get(&quot;keys&quot;,&quot;minio_secret_access_key&quot;))<br><br><br><br><br>logging.basicConfig(filename=&#39;logging/script.log&#39; ,level=logging.INFO, filemode=&#39;w&#39;, format=&#39;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#39;,datefmt=&#39;%Y-%m-%d %H:%M:%S&#39;)<br><br>minio_bucket = &#39;landing&#39;<br>exists_file_cnts = s3.list_objects(Bucket=minio_bucket)[&quot;Contents&quot;]<br>exists_file_lst = [ element[&quot;Key&quot;] for element in exists_file_cnts ]<br>delete_file_dict = [ {&quot;Key&quot;: f[&quot;Key&quot;]} for f in exists_file_cnts]<br><br><br>if len(exists_file_lst) &gt; 1:<br>    logging.info(f&quot;Exists file count: {len(exists_file_lst)}&quot;)<br>    logging.info(&quot;Exists file count more than one!...&quot;)<br>    s3.delete_objects(Bucket=minio_bucket, Delete={&quot;Objects&quot;: delete_file_dict})<br>    logging.info(&quot;Minio bucket deleted all objects&quot;)<br><br>source_file_lst = [&quot;Calendar.csv&quot;,&quot;Customer.csv&quot;,&quot;Employee.csv&quot;,&quot;Food_Inventory.csv&quot;,&quot;Product.csv&quot;,<br>                    &quot;Sales_by_Store.csv&quot;,&quot;Store.csv&quot;]<br><br>for file in source_file_lst:<br>    logging.info(f&quot;Start: {file} is moving to minio landing path...&quot;)<br>    s3.upload_file(f&quot;files/{file}&quot;, minio_bucket, file)<br>    logging.info(f&quot;Finish: {file} was moved to minio landing path...&quot;)</pre><pre>[keys]<br>minio_access_key_id=xxxxxxxxxxxxxxx<br>minio_secret_access_key=xxxxxxxxxxxxxxx</pre><p>Yukarıdaki kod ile kendi makinemizde bulunan csv dosyalarını Minio üzerinde oluşturduğumuz <strong>landing path</strong>’ine gönderiyoruz.</p><pre>2024-05-20 22:01:48 - root - INFO - Exists file count: 7<br>2024-05-20 22:01:48 - root - INFO - Exists file count more than one!...<br>2024-05-20 22:01:48 - root - INFO - Minio bucket deleted all objects<br>2024-05-20 22:01:48 - root - INFO - Start: Calendar.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Calendar.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Customer.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Customer.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Employee.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Employee.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Food_Inventory.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Food_Inventory.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Product.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Product.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Sales_by_Store.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Sales_by_Store.csv was moved to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Start: Store.csv is moving to minio landing path...<br>2024-05-20 22:01:48 - root - INFO - Finish: Store.csv was moved to minio landing path...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XhWVQ8kJjc2HW9NleG6Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*dWZpV8hZj8i_VrEQYq1wOQ.png" /></figure><p>csv dosyaları başarılı şekilde landing kısmına gelmiş durumda. Python koduna dikkat ederseniz burada <strong>9000 </strong>portunu kullanıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x66Bhwl4wFBmYkZrKydDZw.png" /></figure><p><strong>NFS</strong> kullanarak <strong>mount etme işlemi </strong>gerçekleştirmiştik. Kendi makinemizde oluşturduğumuz path’e bakarsak ilgili dosyaları da burada görebiliyoruz.</p><h4>Kubernetes üzerinde Spark Kodu Çalıştırma:</h4><p>İlk önce kendi makinemizde <strong>VS Code Editor’u </strong>içerisindeki <a href="https://scalameta.org/metals/docs/editors/vscode/"><strong>Metals Extension</strong></a><strong>’ı </strong>kullanarak Spark kodlarımızı geliştireceğimiz bir Scala projesi oluşturuyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gXoivPeG5KK2Y_zfPyJdQ.png" /></figure><pre>import org.apache.spark.sql.SparkSession<br>import org.apache.spark.sql.types.{IntegerType, StringType, DoubleType, StructField, StructType}<br>import org.apache.spark.sql.functions.{col, coalesce, lit, input_file_name, current_timestamp}<br><br>object Food_Inventory_Bronze extends App {<br><br>  val spark = SparkSession <br>        .builder <br>        .appName(&quot;BronzeLayer_FoodInventory_App&quot;)<br>        .getOrCreate()<br><br>  val sc = spark.sparkContext<br><br>  val access_key = System.getenv(&quot;access_key&quot;)<br>  val secret_key = System.getenv(&quot;secret_key&quot;)<br>  <br>  sc.setLogLevel(&quot;WARN&quot;)<br><br>  sc.hadoopConfiguration.set(&quot;fs.s3a.access.key&quot;, access_key)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.secret.key&quot;, secret_key)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.path.style.access&quot;, &quot;true&quot;)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.impl&quot;, &quot;org.apache.hadoop.fs.s3a.S3AFileSystem&quot;)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.endpoint&quot;, &quot;http://minio.minio-dev.svc.cluster.local:9000&quot;)<br><br>   val FoodInventoryDF = spark.read.format(&quot;csv&quot;).option(&quot;header&quot;,&quot;true&quot;).load(&quot;s3a://landing/Food_Inventory.csv&quot;)<br><br>   val FoodInventoryDF2 = FoodInventoryDF.withColumn(&quot;food_inventory_file_name&quot;,input_file_name())<br>                         .withColumn(&quot;insert_timestamp&quot;, current_timestamp())<br><br>      <br><br>   FoodInventoryDF2.coalesce(1).write.mode(&quot;overwrite&quot;).parquet(&quot;s3a://bronze/foodinventory&quot;)<br><br>  <br>}</pre><pre>scalaVersion := &quot;2.12.18&quot;<br><br>name := &quot;hello-world&quot;<br>organization := &quot;ch.epfl.scala&quot;<br>version := &quot;1.0&quot;<br><br>libraryDependencies ++= Seq(<br>    &quot;org.apache.spark&quot; %% &quot;spark-core&quot; % &quot;3.5.1&quot;,<br>    &quot;org.apache.spark&quot; %% &quot;spark-sql&quot; % &quot;3.5.1&quot;,<br>    &quot;io.delta&quot; %% &quot;delta-spark&quot; % &quot;3.1.0&quot;,<br>    &quot;org.apache.hadoop&quot; % &quot;hadoop-aws&quot; % &quot;3.3.1&quot;,<br>    &quot;com.amazonaws&quot; % &quot;aws-java-sdk-bundle&quot; % &quot;1.12.725&quot;,<br>    &quot;org.apache.hadoop&quot; % &quot;hadoop-common&quot; % &quot;3.3.1&quot;<br>)</pre><pre>emre@emre-lenovo:~/Desktop/k8s-bootcamp-project/spark-on-k8s$ sbt package<br><br>Output:<br>WARNING: An illegal reflective access operation has occurred<br>WARNING: Illegal reflective access by org.jline.terminal.impl.exec.ExecTerminalProvider$ReflectionRedirectPipeCreator (file:/home/emre/.sbt/boot/scala-2.12.18/org.scala-sbt/sbt/1.9.9/jline-terminal-3.24.1.jar) to constructor java.lang.ProcessBuilder$RedirectPipeImpl()<br>WARNING: Please consider reporting this to the maintainers of org.jline.terminal.impl.exec.ExecTerminalProvider$ReflectionRedirectPipeCreator<br>WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations<br>WARNING: All illegal access operations will be denied in a future release<br>[info] welcome to sbt 1.9.9 (Ubuntu Java 11.0.22)<br>[info] loading project definition from /home/emre/Desktop/k8s-bootcamp-project/spark-on-k8s/project<br>[info] loading settings for project spark-on-k8s from build.sbt ...<br>[info] set current project to hello-world (in build file:/home/emre/Desktop/k8s-bootcamp-project/spark-on-k8s/)<br>[info] compiling 1 Scala source to /home/emre/Desktop/k8s-bootcamp-project/spark-on-k8s/target/scala-2.12/classes ...<br>[success] Total time: 5 s, completed May 25, 2024, 12:42:37 AM</pre><p><strong>sbt package</strong> komutunu çalıştırarak <strong>target/scala-2.12/ </strong>dizini altında bir jar dosyası oluşuyor. Kubernetes üzerinde Spark kodumuzu çalıştırırken bu jar dosyasını kullanacağız.</p><p><strong>Docker baz imaj oluşturma:</strong></p><pre>$SPARK_HOME/bin/docker-image-tool.sh -r docker.io/emreus09 -t 3.5.1 -u 1000 build<br>docker image push emreus09/spark:3.5.1</pre><pre>FROM emreus09/spark:3.5.1<br>USER root<br>RUN mkdir /app<br>COPY hello-world_2.12-1.0.jar /app</pre><pre>emre@emre-lenovo:~/Desktop/k8s-bootcamp-project$ docker build -t spark-k8s-app:1.0 .<br><br>Output:<br>Sending build context to Docker daemon  50.98MB<br>Step 1/4 : FROM emreus09/spark:3.5.1<br> ---&gt; f4621dc3d3d2<br>Step 2/4 : USER root<br> ---&gt; Using cache<br> ---&gt; 8c873f6c0955<br>Step 3/4 : RUN mkdir /app<br> ---&gt; Using cache<br> ---&gt; a9f4c0332354<br>Step 4/4 : COPY hello-world_2.12-1.0.jar /app<br> ---&gt; e4c628176ccf<br>Successfully built e4c628176ccf<br>Successfully tagged spark-k8s-app:1.0<br><br>emre@emre-lenovo:~/Desktop/k8s-bootcamp-project$ docker tag spark-k8s-app:1.0 emreus09/spark-k8s-app:1.0<br>emre@emre-lenovo:~/Desktop/k8s-bootcamp-project$ docker image push emreus09/spark-k8s-app:1.0</pre><p><strong>Spark Operator indirme işlemi:</strong></p><pre>#Spark Operator için yeni bir namespace tanımlıyoruz.<br>kubectl create ns spark-operator<br><br>#Helm aracını kullanarak spark-operator&#39;un indirilme işlemi<br>helm repo add spark-operator https://kubeflow.github.io/spark-operator<br>helm install my-release spark-operator/spark-operator --namespace spark-operator --create-namespace  --version 1.2.14</pre><p><strong>Servis Hesabı oluşturma işlemi:</strong></p><pre>kubectl create serviceaccount spark -n spark-operator<br>kubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=spark-operator:spark --namespace=spark-operator</pre><p>Spark üzerinden Minio erişimi sağlayacağımız<strong> ACCESS_KEY</strong> ve <strong>SECRET_KEY</strong> için <strong>secret nesnesi</strong> oluşturma:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: s3-credentials<br>  namespace: spark-operator<br>type: Opaque<br>data:<br>  ACCESS_KEY: YkZ5amJicFprbEQ3dHJXQnRBaVk=<br>  SECRET_KEY: QmU3QzNqalFWelV5aWZxR05ta0hDRFp5UUlXUEo4aFdGUU1HQWpZTg==</pre><pre>kubectl apply -f spark-secret.yaml</pre><pre>apiVersion: &quot;sparkoperator.k8s.io/v1beta2&quot;<br>kind: SparkApplication<br>metadata:<br>  name: spark-on-k8s<br>  namespace: spark-operator<br>spec:<br>  type: Scala<br>  mode: cluster<br>  image: &quot;emreus09/spark-k8s-app:1.0&quot;<br>  imagePullPolicy: Always<br>  mainClass: Food_Inventory_Bronze<br>  mainApplicationFile: &quot;local:///app/hello-world_2.12-1.0.jar&quot;<br>  sparkVersion: &quot;3.5.1&quot;<br>  restartPolicy:<br>    type: OnFailure<br>    onFailureRetries: 3<br>    onFailureRetryInterval: 10<br>    onSubmissionFailureRetries: 5<br>    onSubmissionFailureRetryInterval: 20<br>  volumes:<br>  - name: data<br>    nfs:<br>      server: 192.168.49.1<br>      path: /nfs/share<br>  driver:<br>    cores: 1<br>    coreLimit: &quot;1200m&quot;<br>    memory: &quot;512m&quot;<br>    labels:<br>      version: 3.5.1<br>    serviceAccount: spark<br>    envSecretKeyRefs:<br>      ACCESS_KEY:<br>        name: s3-credentials<br>        key: ACCESS_KEY<br>      SECRET_KEY:<br>        name: s3-credentials<br>        key: SECRET_KEY<br>    volumeMounts:<br>    - name: data<br>      mountPath: /tmp<br>  executor:<br>    cores: 1<br>    instances: 2<br>    memory: &quot;1000m&quot;<br>    labels:<br>      version: 3.5.1<br>    volumeMounts:<br>    - name: data<br>      mountPath: /tmp<br>  deps:<br>    jars:<br>    - https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/3.3.1/hadoop-aws-3.3.1.jar<br>    - https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.12.725/aws-java-sdk-bundle-1.12.725.jar<br>    - https://repo1.maven.org/maven2/org/apache/spark/spark-core_2.12/3.5.1/spark-core_2.12-3.5.1.jar<br>    - https://repo1.maven.org/maven2/org/apache/spark/spark-sql_2.12/3.5.1/spark-sql_2.12-3.5.1.jar<br>    - https://repo1.maven.org/maven2/io/delta/delta-spark_2.12/3.1.0/delta-spark_2.12-3.1.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-common/3.3.1/hadoop-common-3.3.1.jar</pre><pre><br>kubectl apply -f spark-app-foodinvetory.yaml<br><br>#Logları takip ederek Spark Operator aşamalarını takip edebiliriz.<br>kubectl logs -f spark-on-k8s-driver -n spark-operator</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiRDcd9X25YEVBXebxzNqg.png" /></figure><p><strong>Minio Web UI</strong> ekranına baktığımızda bronze kısmında ilgili <strong>path</strong> oluşmuş ve <strong>parquet</strong> olarak verilerimizi aktarmış olarak görüyoruz.</p><p><strong>Hive Metastore Servisini Oluşturma:</strong></p><p><strong>Silver</strong> ve <strong>Gold</strong> Layer kısımlarında verilerimizi <strong>Delta Lake </strong>formatında tutacağımızı için burada Hive Metastore’a ihtiyacımız olacak bunun için gelin şimdi metastore servisini ayağa kaldıralım.</p><pre>kubectl create ns hive-metastore</pre><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: mysql-secrets<br>  namespace: hive-metastore<br>type: Opaque<br>data:<br>  ROOT_PASSWORD: aWNhcnVzMDMzNw==<br>---<br>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: nfs-2g-pv<br>  namespace: hive-metastore<br>spec:<br>  storageClassName: nfs<br>  accessModes:<br>  - ReadWriteMany<br>  capacity:<br>    storage: 2Gi<br><br>  nfs:<br>    path: /nfs/share/<br>    server: 192.168.49.1<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: mysql-data-disk<br>  namespace: hive-metastore<br>spec:<br>  accessModes:<br>  - ReadWriteMany<br>  resources:<br>    requests:<br>      storage: 2Gi<br>  storageClassName: nfs<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mysql-deployment<br>  namespace: hive-metastore<br>  labels:<br>    app: mysql<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mysql<br>  template:<br>    metadata:<br>      labels:<br>        app: mysql<br>    spec:<br>      containers:<br>      - name: mysql<br>        image: mysql:5.7<br>        ports:<br>        - containerPort: 3306<br>        volumeMounts:<br>        - mountPath: &quot;/var/lib/mysql&quot;<br>          subPath: &quot;mysql&quot;<br>          name: mysql-data<br>        env:<br>        - name: MYSQL_ROOT_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: mysql-secrets<br>              key: ROOT_PASSWORD<br>      volumes:<br>      - name: mysql-data<br>        persistentVolumeClaim:<br>          claimName: mysql-data-disk<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mysql-service<br>  namespace: hive-metastore<br>spec:<br>  selector:<br>    app: mysql<br>  ports:<br>  - protocol: TCP<br>    port: 3306<br>    targetPort: 3306</pre><pre>kubectl apply -f hive-ms-mysql.yaml</pre><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: hive-initschema<br>  namespace: hive-metastore<br>spec:<br>  template:<br>    spec:<br>      affinity:<br>        podAntiAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            - labelSelector:<br>                matchExpressions:<br>                  - key: app<br>                    operator: In<br>                    values:<br>                      - mysql<br>              topologyKey: kubernetes.io/hostname<br>      containers:<br>        - name: hivemeta<br>          image: mykidong/hivemetastore:v3.0.0<br>          command: [&quot;/opt/hive-metastore/bin/schematool&quot;]<br>          args: [&quot;--verbose&quot; ,&quot;-initSchema&quot; , &quot;-dbType&quot;, &quot;mysql&quot; , &quot;-userName&quot;, &quot;root&quot;,<br>                 &quot;-passWord&quot;, &quot;icarus0337&quot; , &quot;-url&quot;, &quot;jdbc:mysql://mysql-service.hive-metastore.svc.cluster.local:3306/metastore_db?createDatabaseIfNotExist=true&amp;connectTimeout=1000&quot;]<br>      restartPolicy: Never<br>  backoffLimit: 4</pre><pre>&lt;configuration&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.connection.ssl.enabled&lt;/name&gt;<br>       &lt;value&gt;true&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.defaultFS&lt;/name&gt;<br>        &lt;value&gt;s3a://emreevcimen&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.path.style.access&lt;/name&gt;<br>        &lt;value&gt;true&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.access.key&lt;/name&gt;<br>        &lt;value&gt;bFyjbbpZklD7trWBtAiY&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.secret.key&lt;/name&gt;<br>        &lt;value&gt;Be7C3jjQVzUyifqGNmkHCDZyQIWPJ8hWFQMGAjYN&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.impl&lt;/name&gt;<br>        &lt;value&gt;org.apache.hadoop.fs.s3a.S3AFileSystem&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.endpoint&lt;/name&gt;<br>        &lt;value&gt;http://minio.minio-dev.svc.cluster.local:9000&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;fs.s3a.fast.upload&lt;/name&gt;<br>        &lt;value&gt;true&lt;/value&gt;<br>    &lt;/property&gt;<br>&lt;/configuration&gt;</pre><pre>&lt;configuration&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;metastore.task.threads.always&lt;/name&gt;<br>      &lt;value&gt;org.apache.hadoop.hive.metastore.events.EventCleanerTask&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;metastore.expression.proxy&lt;/name&gt;<br>      &lt;value&gt;org.apache.hadoop.hive.metastore.DefaultPartitionExpressionProxy&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;javax.jdo.option.ConnectionDriverName&lt;/name&gt;<br>      &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;javax.jdo.option.ConnectionURL&lt;/name&gt;<br>      &lt;value&gt;jdbc:mysql://mysql-service.hive-metastore.svc.cluster.local:3306/metastore_db?useSSL=false&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;javax.jdo.option.ConnectionUserName&lt;/name&gt;<br>      &lt;value&gt;root&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;javax.jdo.option.ConnectionPassword&lt;/name&gt;<br>      &lt;value&gt;icarus0337&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;metastore.warehouse.dir&lt;/name&gt;<br>      &lt;value&gt;s3a://emreevcimen/warehouse/&lt;/value&gt;<br>   &lt;/property&gt;<br>   &lt;property&gt;<br>      &lt;name&gt;metastore.thrift.port&lt;/name&gt;<br>      &lt;value&gt;9083&lt;/value&gt;<br>   &lt;/property&gt;<br>&lt;/configuration&gt;</pre><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: metastore<br>  namespace: hive-metastore<br>spec:<br>  ports:<br>  - port: 9083<br>  selector:<br>    app: metastore<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: metastore<br>  namespace: hive-metastore<br>spec:<br>  selector:<br>    matchLabels:<br>      app: metastore<br>  strategy:<br>    type: Recreate<br>  template:<br>    metadata:<br>      labels:<br>        app: metastore<br>    spec:<br>      containers:<br>      - name: metastore<br>        image: mykidong/hivemetastore:v3.0.0<br>        env:<br>        - name: AWS_ACCESS_KEY_ID<br>          valueFrom:<br>            secretKeyRef:<br>              name: my-s3-keys<br>              key: access-key<br>        - name: AWS_SECRET_ACCESS_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: my-s3-keys<br>              key: secret-key<br>        ports:<br>        - containerPort: 9083<br>        volumeMounts:<br>        - name: metastore-cfg-vol<br>          mountPath: /opt/hive-metastore/conf/metastore-site.xml<br>          subPath: metastore-site.xml<br>        - name: metastore-cfg-vol<br>          mountPath: /opt/hadoop/etc/hadoop/core-site.xml<br>          subPath: core-site.xml<br>        command: [&quot;/opt/hive-metastore/bin/start-metastore&quot;]<br>        args: [&quot;-p&quot;, &quot;9083&quot;]<br>        resources:<br>          requests:<br>            memory: &quot;2G&quot;<br>            cpu: 2<br>        imagePullPolicy: Always<br>      volumes:<br>        - name: metastore-cfg-vol<br>          configMap:<br>            name: metastore-cfg</pre><pre>kubectl create configmap metastore-cfg --dry-run --from-file=metastore-site.xml --from-file=core-site.xml -o yaml -n hive-metastore | kubectl apply -f -<br>kubectl create secret generic my-s3-keys --from-literal=access-key=&#39;bFyjbbpZklD7trWBtAiY&#39; --from-literal=secret-key=&#39;Be7C3jjQVzUyifqGNmkHCDZyQIWPJ8hWFQMGAjYN&#39; -n hive-metastore<br>kubectl apply -f init-schema.yaml;<br>kubectl apply -f metastore.yaml;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxWlzTsTLmNHAIddiOwQ-Q.png" /></figure><p>Yukarıda görüldüğü gibi metastore servisimiz başarılı şekilde çalışmakta.</p><pre>import io.delta.tables._<br>import org.apache.spark.sql.SparkSession<br>import org.apache.spark.sql.types.{IntegerType, StringType, DoubleType, StructField, StructType}<br>import org.apache.spark.sql.functions.{col, to_date, upper, regexp_replace, regexp_extract}<br><br>object Customer_Silver extends App {<br><br><br>  val spark = SparkSession <br>        .builder <br>        .appName(&quot;SilverLayer_Customer_App&quot;) <br>        .config(&quot;spark.sql.extensions&quot;, &quot;io.delta.sql.DeltaSparkSessionExtension&quot;) <br>        .config(&quot;spark.sql.catalog.spark_catalog&quot;,&quot;org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;)<br>        .config(&quot;spark.sql.warehouse.dir&quot;,&quot;s3a://emreevcimen/warehouse&quot;) <br>        .config(&quot;spark.delta.logStore.class&quot;, &quot;org.apache.spark.sql.delta.storage.S3SingleDriverLogStore&quot;) <br>        .config(&quot;spark.sql.debug.maxToStringFields&quot;, 1000)<br>        .config(&quot;spark.hadoop.hive.metastore.client.connect.retry.delay&quot;,5)<br>        .config(&quot;spark.hadoop.hive.metastore.client.socket.timeout&quot;,1800)<br>        .config(&quot;spark.hadoop.hive.metastore.uris&quot;, &quot;thrift://metastore.hive-metastore.svc.cluster.local:9083&quot;)<br>        .config(&quot;spark.sql.catalogImplementation&quot;, &quot;hive&quot;) <br>        .config(&quot;hive.metastore.schema.verification&quot;, &quot;false&quot;) <br>        .enableHiveSupport() <br>        .getOrCreate()<br>  <br>  val sc = spark.sparkContext<br><br>  val access_key = System.getenv(&quot;ACCESS_KEY&quot;)<br>  val secret_key = System.getenv(&quot;SECRET_KEY&quot;)<br>  <br>  sc.setLogLevel(&quot;WARN&quot;)<br><br>  sc.hadoopConfiguration.set(&quot;fs.s3a.access.key&quot;, access_key)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.secret.key&quot;, secret_key)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.path.style.access&quot;, &quot;true&quot;)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.impl&quot;, &quot;org.apache.hadoop.fs.s3a.S3AFileSystem&quot;)<br>  sc.hadoopConfiguration.set(&quot;fs.s3a.endpoint&quot;, &quot;http://minio.minio-dev.svc.cluster.local:9000&quot;)<br>  <br> <br>  spark.sql(&quot;&quot;&quot;<br>    CREATE OR REPLACE TABLE spark_catalog.lkh_silver.customer (<br>      customer_id INT,<br>      home_store INT,<br>      customer_first_name VARCHAR(100),<br>      customer_company VARCHAR(100),<br>      customer_since DATE,<br>      birthdate VARCHAR(500),<br>      gender VARCHAR(50),<br>      birth_year INT,<br>      insert_date DATE<br>  ) <br>  USING DELTA<br>  LOCATION &#39;s3a://emreevcimen/warehouse/lkh_silver.db/customer&#39;;<br>  &quot;&quot;&quot;)<br>  <br>   val new_customerDF = spark.read.format(&quot;parquet&quot;).option(&quot;header&quot;,&quot;true&quot;).load(&quot;s3a://bronze/customer&quot;)<br><br>   val delta_customerDF = DeltaTable.forPath(&quot;s3a://emreevcimen/warehouse/lkh_silver.db/customer&quot;)<br><br>   val new_customerDF2 = new_customerDF.withColumnRenamed(&quot;customer_first-name&quot;,&quot;customer_first_name&quot;)<br>                                 .withColumn(&quot;customer_company&quot;,upper(regexp_replace(regexp_extract(col(&quot;customer_email&quot;),&quot;[@]\\w+&quot;,0),&quot;@&quot;,&quot;&quot;)))<br>                                 .withColumn(&quot;customer_since&quot;,to_date(col(&quot;customer_since&quot;)))<br>                                 .withColumn(&quot;birthdate&quot;,to_date(col(&quot;birthdate&quot;)))<br>                                 .withColumn(&quot;insert_date&quot;,to_date(col(&quot;insert_timestamp&quot;)))<br>                                 .filter(&quot;customer_id IS NOT NULL&quot;)<br>                                 .drop(col(&quot;insert_timestamp&quot;),col(&quot;customer_file_name&quot;),col(&quot;customer_email&quot;),col(&quot;loyalty_card_number&quot;))<br><br>    <br><br><br>    <br>    delta_customerDF.as(&quot;oldData&quot;)    <br>        .merge(new_customerDF2.as(&quot;newData&quot;),&quot;oldData.customer_id = newData.customer_id&quot;)<br>        .whenMatched<br>        .update(Map(&quot;customer_id&quot; -&gt; col(&quot;newData.customer_id&quot;),<br>                    &quot;home_store&quot; -&gt; col(&quot;newData.home_store&quot;),<br>                    &quot;customer_first_name&quot; -&gt; col(&quot;newData.customer_first_name&quot;),<br>                    &quot;customer_company&quot; -&gt; col(&quot;newData.customer_company&quot;),<br>                    &quot;customer_since&quot; -&gt; col(&quot;newData.customer_since&quot;),<br>                    &quot;birthdate&quot; -&gt; col(&quot;newData.birthdate&quot;),<br>                    &quot;gender&quot; -&gt; col(&quot;newData.gender&quot;),<br>                    &quot;birth_year&quot; -&gt; col(&quot;newData.birth_year&quot;),<br>                    &quot;insert_date&quot; -&gt; col(&quot;newData.insert_date&quot;)<br>                    ))<br>        .whenNotMatched<br>        .insert(Map(&quot;customer_id&quot; -&gt; col(&quot;newData.customer_id&quot;),<br>                    &quot;home_store&quot; -&gt; col(&quot;newData.home_store&quot;),<br>                    &quot;customer_first_name&quot; -&gt; col(&quot;newData.customer_first_name&quot;),<br>                    &quot;customer_company&quot; -&gt; col(&quot;newData.customer_company&quot;),<br>                    &quot;customer_since&quot; -&gt; col(&quot;newData.customer_since&quot;),<br>                    &quot;birthdate&quot; -&gt; col(&quot;newData.birthdate&quot;),<br>                    &quot;gender&quot; -&gt; col(&quot;newData.gender&quot;),<br>                    &quot;birth_year&quot; -&gt; col(&quot;newData.birth_year&quot;),<br>                    &quot;insert_date&quot; -&gt; col(&quot;newData.insert_date&quot;)<br>                    ))<br>        .execute()<br>    <br>}</pre><pre>apiVersion: &quot;sparkoperator.k8s.io/v1beta2&quot;<br>kind: SparkApplication<br>metadata:<br>  name: spark-on-k8s-customer-silver<br>  namespace: spark-operator<br>spec:<br>  type: Scala<br>  mode: cluster<br>  image: &quot;emreus09/spark-k8s-app:1.0&quot;<br>  imagePullPolicy: Always<br>  mainClass: Customer_Silver<br>  mainApplicationFile: &quot;local:///app/hello-world_2.12-1.0.jar&quot;<br>  sparkVersion: &quot;3.5.1&quot;<br>  restartPolicy:<br>    type: OnFailure<br>    onFailureRetries: 3<br>    onFailureRetryInterval: 10<br>    onSubmissionFailureRetries: 5<br>    onSubmissionFailureRetryInterval: 20<br>  volumes:<br>  - name: data<br>    nfs:<br>      server: 192.168.49.1<br>      path: /nfs/share<br>  driver:<br>    cores: 1<br>    coreLimit: &quot;1200m&quot;<br>    memory: &quot;512m&quot;<br>    labels:<br>      version: 3.5.1<br>    serviceAccount: spark<br>    envSecretKeyRefs:<br>      ACCESS_KEY:<br>        name: s3-credentials<br>        key: ACCESS_KEY<br>      SECRET_KEY:<br>        name: s3-credentials<br>        key: SECRET_KEY<br>    volumeMounts:<br>    - name: data<br>      mountPath: /tmp<br>  executor:<br>    cores: 1<br>    instances: 2<br>    memory: &quot;1000m&quot;<br>    labels:<br>      version: 3.5.1<br>    volumeMounts:<br>    - name: data<br>      mountPath: /tmp<br>  deps:<br>    jars:<br>    - https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/3.3.1/hadoop-aws-3.3.1.jar<br>    - https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.12.725/aws-java-sdk-bundle-1.12.725.jar<br>    - https://repo1.maven.org/maven2/org/apache/spark/spark-core_2.12/3.5.1/spark-core_2.12-3.5.1.jar<br>    - https://repo1.maven.org/maven2/org/apache/spark/spark-sql_2.12/3.5.1/spark-sql_2.12-3.5.1.jar<br>    - https://repo1.maven.org/maven2/io/delta/delta-spark_2.12/3.1.0/delta-spark_2.12-3.1.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-common/3.3.1/hadoop-common-3.3.1.jar<br>    - https://repo1.maven.org/maven2/io/delta/delta-storage/3.1.0/delta-storage-3.1.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hive/hive-metastore/3.0.0/hive-metastore-3.0.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hive/hive-exec/3.0.0/hive-exec-3.0.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hive/hive-common/3.0.0/hive-common-3.0.0.jar<br>    - https://repo1.maven.org/maven2/org/apache/hive/hive-serde/3.0.0/hive-serde-3.0.0.jar</pre><pre>kubectl apply -f spark-app-customer-silver.yaml<br>kubectl logs -f spark-on-k8s-calendar-silver-driver -n spark-operato</pre><p>Silver Layer kısmında çalıştıracağımız Spark Kodları için remote Hive Metastore’a erişmesi ve Delta Lake tablosu olarak kaydetmesi için gerekli düzenlemeleri hem kod tarafında hem de yaml dosyalarımızda düzenmelerini yaptık.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0k6soGMzcM5iGYw2RFfRg.png" /></figure><p>Spark kodunun çalışma işlemi bittikten sonra Minio kısmını kontrol ettiğimizde ilgili tablonun başarılı şekilde oluştuğunu görmekteyiz.</p><p>Delta Lake tablolarını okumak için ilgili projemizde Trino’yu kullanacağız.</p><p><strong>Trino Servisini Ayağa kaldırma:</strong></p><pre>helm repo add trino https://trinodb.github.io/charts/ <br>helm install my-trino trino/trino --create-namespace -n trino<br>helm show values trino/trino &gt; values.yaml</pre><p>Trino için helm aracını kullanarak ilgili repo’yu ekliyoruz. Daha sonrasında trino namespace’i oluşturup gerekli nesnelerin oluşmasını sağlıyoruz. Delta Lake erişim bilgilerini eklemek adına <strong>values.yaml </strong>içerisine gerekli tanımları basıyoruz.</p><pre>additionalCatalogs:<br>  delta_lake: |<br>    connector.name=delta_lake<br>    hive.metastore.uri=thrift://metastore.hive-metastore.svc.cluster.local:9083<br>    hive.s3.endpoint=http://minio.minio-dev.svc.cluster.local:9000<br>    hive.s3.aws-access-key=bFyjbbpZklD7trWBtAiY<br>    hive.s3.aws-secret-key=Be7C3jjQVzUyifqGNmkHCDZyQIWPJ8hWFQMGAjYN<br>    hive.s3.path-style-access=true<br>    delta.register-table-procedure.enabled=true<br>    delta.enable-non-concurrent-writes=true</pre><p><strong>additionalCatalogs attribute </strong>altına Delta Lake bağlantısı için gerekli tanımları yukarıdaki gibi yapıyoruz.</p><pre>helm upgrade trino trino/trino --values values.yaml -n trino</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7F3JpCCFCk-lPL3WOUcpng.png" /></figure><pre>kubectl port-forward -n trino svc/my-trino 8082:8080</pre><p><strong>DBeaver aracını kullanarak Trino’ya bağlanma:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pLxla15aSBlx3Gg6UBPMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_VwpEem22FKF_5yDV9YAw.png" /></figure><p>Trino’ya bağlantı sağlayıp <strong>Delta Lake</strong> olarak oluşturduğumuz tablolara başarılı şekilde sorgu atabildik.</p><p>Part-1 yazımızın son konusu olan <strong>Apache Superset</strong> aracılığıyla veri görselleştirme aşamasına geçebiliriz.</p><p><strong>Apache Superset Servisini Ayağa Kaldırma:</strong></p><pre>helm repo add superset http://apache.github.io/superset/<br>helm install my-superset superset/superset --set extraSecretEnv.SUPERSET_SECRET_KEY=keymrvcmnkey --create-namespace -n superset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plGHah349Fafcz8HhR0mlg.png" /></figure><p>Apache Superset servisi sağlıklı bir şekilde çalışıyor. Şimdi trino için gerekli kurulum yapmak için superset podunun içerisine girelim ve gerekli kütüphaneyi yükleyelim.</p><pre>kubectl exec -it my-superset-5b99b4cbff-w5tt7 -n superset -- bash<br>root@my-superset-5b99b4cbff-w5tt7:/app# pip3 install sqlalchemy-trino</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H27uUfaMerC61zszc1bDKw.png" /></figure><p>Superset üzerinden Trino servisimize başarılı bir şekilde bağlantı sağladık. Şimdi SQL Lab ekranına giderek aşağıda yazılı olan SQL’i Dataset olarak kaydedelim.</p><pre>select<br> fi.transaction_date,<br> fi.store_id,<br> str.store_type ,<br> str.store_city,<br> prd.product,<br> prd.product_type,<br> fi.quantity_start_of_day,<br> fi.total_quantity_sold<br>from<br> delta_lake.lkh_gold.foodinventory fi<br>join delta_lake.lkh_silver.store str on<br> str.store_id = fi.store_id<br>join delta_lake.lkh_silver.product prd on<br> prd.product_id = fi.product_id</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dB-qvcwqOWZyAs5IVo6CrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ky98QQPMn3_Dgs-lu--9w.png" /></figure><p>Evet artık istediğimiz gibi raporlar oluşturarak <strong>Karar Destek Sistemlerimizi</strong> besleyebiliriz.</p><p>Bir sonraki yazımda da bu akışı Apache Airflow ile otomasyonunu ve orkestra edilme sürecini aktaracağım. Umarım faydalı bir yazı olmuştur. Herhangi bir sorunuz veya öneriniz varsa benimle iletişime geçebilirsiniz. Teşekkürler 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc8cc95414e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache İceberg]]></title>
            <link>https://emreevcimen.medium.com/apache-i%CC%87ceberg-ee1bcb06935b?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1bcb06935b</guid>
            <category><![CDATA[dremio]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 14:29:09 GMT</pubDate>
            <atom:updated>2024-03-27T14:35:28.048Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar, bu yazımda sizlere <strong>Apache İceberg</strong>’i teorik olarak daha sonrasında da uygulamalı örneklerle anlatmaya çalışacağım.İlk olarak <strong>Apache İceberg</strong> nedir, neden kullanılır ve nasıl çalışır bir ona bakalım.</p><h3><strong>Apache İceberg Nedir?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8IOU3SDJMeudo9_4ittEg.jpeg" /></figure><p><strong>Apache Iceberg,</strong> büyük ölçekli veri depolama,sorgulama sistemlerinde kullanılan açık kaynaklı bir veri tabanı formatı ve işlem motorudur. Iceberg, büyük veri tabanlarının performansını artırmak, veri bütünlüğünü sağlamak ve <strong>veri işleme çalışmalarını daha güvenilir hale getirmek için tasarlanmıştır</strong>.</p><p>Apache İceberg’in <strong>kullanım nedenlerini </strong>aşağıdaki gibi örneklendirebiliriz.</p><p><strong>Partitioning:</strong> Iceberg, verileri fiziksel olarak bölme yeteneğine sahiptir. Bu, sorguların yalnızca ilgili parçaları işlemesini sağlar, böylece sorgu performansı artar.</p><p><strong>Transactionality:</strong> Iceberg, <strong>ACID</strong> özelliklerini destekler. Bu, veri yazma, <strong>güncelleme</strong> ve <strong>silme</strong> işlemlerinin güvenilir bir şekilde gerçekleştirilmesini sağlar.</p><p><strong>Time Travel: </strong>Iceberg, geçmişteki veri sürümlerine erişim sağlar. Bu, veri bütünlüğünü kontrol etmek ve analiz yapmak için önemli bir özelliktir.</p><p><strong>Schema Evolution: </strong>Iceberg, veri şemasının zamanla değişmesine izin verir. Bu, veri modelinde yapılan değişikliklerin kolayca yönetilmesini sağlar.</p><p><strong>Kompakt Veri Formatı: </strong>Iceberg, sıkıştırılmış ve sütun tabanlı bir veri formatı kullanır. Bu, depolama alanını optimize eder ve sorgu performansını artırır.</p><p>Apache İceberg’in genel işleyişini resimde görebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QP0D_ZRv_B0HmnIXt7PMeA.png" /></figure><p><strong>Metadata Katmanı (Metadata Layer):</strong> Bu katman, Iceberg tablolarının meta bilgilerini depolar ve yönetir. Metadata Layer, tabloların şemasını, bölme bilgilerini, sütun istatistiklerini, geçmiş veri sürümlerini ve diğer meta bilgilerini saklar. Bu meta bilgileri, tabloların yapılandırılmasını, veri işleme işlemlerini ve sorguların optimize edilmesini sağlar. Metadata genellikle bir veritabanında (örneğin, SQLite, Apache Derby) veya dağıtılmış bir depoda (örneğin, Apache Hive Metastore, Apache HBase) saklanır.</p><p><strong>Veri Katmanı (Data Layer):</strong> Bu katman, verilerin fiziksel olarak depolandığı ve yönetildiği katmandır. <strong>Iceberg</strong>, genellikle <strong>Parquet</strong> veya <strong>ORC</strong> gibi sıkıştırılmış sütun tabanlı dosya formatlarını kullanır. Dosya katmanı, veri yazma, güncelleme, silme ve okuma işlemlerini yönetir. Ayrıca, dosya katmanı veri tablosunu fiziksel olarak bölerek tabakalandırma(<strong>partitioning</strong>) işlemlerini de gerçekleştirir.</p><p><strong>Iceberg Catalog: </strong>İceberg tablosu ile işlem yapacak kişinin(read,write) ilk kontakt yeridir.Iceberg Catalog, bir Iceberg Tablosu için geçerli meta veri noktasını, yani bir tablonun geçerli meta veri dosyasına yönelik güncel noktayı saklar.</p><p>Teorik kısımlarına genel hatlarıyla değindiğimize göre gelin şimdi Spark ile birlikte kullanımına uygulamalı şekilde bir bakalım.</p><pre>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as F<br><br><br>url = &quot;jdbc:sqlserver://your_hostname:1433;database=AdventureWorks2019;encrypt=true;trustServerCertificate=true&quot;<br>properties = {<br>    &quot;user&quot;: &quot;your_username&quot;,<br>    &quot;password&quot;: &quot;your_password&quot;,<br>    &quot;driver&quot;: &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;<br>}<br><br>table_name = &quot;Production.Product&quot;<br><br><br><br>spark = SparkSession.builder.appName(&quot;apache-iceberg-working&quot;) \<br>                    .config(&quot;spark.jars.packages&quot;,&quot;org.apache.iceberg:iceberg-spark3-runtime:0.13.2&quot;) \<br>                    .config(&quot;spark.sql.extensions&quot;,&quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;) \<br>                    .config(&quot;spark.sql.catalog.hive_prod&quot;,&quot;org.apache.iceberg.spark.SparkCatalog&quot;) \<br>                    .config(&quot;spark.sql.catalog.hive_prod.type&quot;,&quot;hive&quot;) \<br>                    .config(&quot;spark.sql.catalog.hive_prod.uri&quot;,&quot;thrift://localhost:9083&quot;) \<br>                    .getOrCreate()<br><br>s_columns = [&quot;ProductID&quot; ,&quot;Name&quot; ,&quot;ProductNumber&quot; ,&quot;MakeFlag&quot; ,&quot;Color&quot; ,&quot;ProductSubcategoryID&quot; ,&quot;StandardCost&quot; ,&quot;ListPrice&quot;,&quot;SellStartDate&quot;]<br>productDF = spark.read.jdbc(url=url, table=table_name, properties=properties)<br>productDF = productDF.select(*s_columns)<br><br><br>spark.sql(&quot;&quot;&quot;CREATE TABLE  hive_prod.de.d_product (<br>        ProductID INT,<br>        Name STRING,<br>        ProductNumber STRING,<br>        MakeFlag BOOLEAN ,<br>        Color STRING,<br>        ProductSubCategoryID INT,<br>        StandardCost DECIMAL(19,4),<br>        ListPrice DECIMAL(19,4),<br>        SellStartDate TIMESTAMP<br>    )<br>    USING iceberg&quot;&quot;&quot;)<br><br><br>productDF.write.format(&quot;iceberg&quot;).mode(&quot;overwrite&quot;).saveAsTable(&quot;hive_prod.de.d_product&quot;)<br>spark.sql(&quot;SELECT * FROM hive_prod.de.d_product&quot;).show()<br><br></pre><pre>&quot;spark.sql.catalog.hive_prod&quot; = &quot;org.apache.iceberg.spark.SparkCatalog&quot; <br>&quot;spark.sql.catalog.hive_prod.type&quot; = &quot;hive&quot;<br>&quot;spark.sql.catalog.hive_prod.uri&quot; = &quot;thrift://localhost:9083&quot;</pre><p>Teori kısmında Catalog için ne demiştik İceberg kısmında yazma veya okuma işlemi yapmak istiyorsak kuracağımız ilk kontakt burasıydı. Apache Iceberg Catalog için birden fazla sistemi desteklemektedir.(Hadoop,Hive,Minio,S3 vb.) Ben metadata bilgilerini saklamak için Hive Metastore’u tercih ettim. O yüzden yukarıdaki parametreleri set ederek Spark içerisinde oluşucak Catalog’a bunu bildiriyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIfHArVQa2fAIpItSV9_4Q.png" /></figure><p>Kodu çalıştırdığımda görmüş olduğunuz gibi Iceberg tablosunu başarılı şekilde oluşturup tabloya yazdı. Oluşturduğu bu tabloyu hive tablolarının hdfs de bulunduğu dizine bendeki path(/user/hive/warehouse/) kaydediyor. Gelin yapısına bir bakalım.</p><pre>hdfs dfs -ls /user/hive/warehouse/de.db/d_product <br>Found 2 items<br>drwxrwxrwx   - emre supergroup          0 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/data<br>drwxrwxrwx   - emre supergroup          0 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/metadata</pre><pre>hdfs dfs -ls /user/hive/warehouse/de.db/d_product/metadata<br>Found 4 items<br>-rw-r--r--   1 emre supergroup       2720 2024-03-27 12:51 /user/hive/warehouse/de.db/d_product/metadata/00000-fbeaa252-1d1a-4eae-9414-4e0e03b31e8d.metadata.json<br>-rw-r--r--   1 emre supergroup       4745 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/metadata/00001-0991683d-a7e5-400e-9aaf-504f9f23b840.metadata.json<br>-rw-r--r--   1 emre supergroup       6442 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/metadata/560f4281-2bb7-4ce6-8d87-ebaf9c8c950b-m0.avro<br>-rw-r--r--   1 emre supergroup       3779 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/metadata/snap-8740618567573872932-1-560f4281-2bb7-4ce6-8d87-ebaf9c8c950b.avro</pre><pre>hdfs dfs -ls /user/hive/warehouse/de.db/d_product/data<br>Found 1 items<br>-rw-r--r--   1 emre supergroup       9306 2024-03-27 12:56 /user/hive/warehouse/de.db/d_product/data/00000-0-91308c0d-b6b6-4c60-867d-fd6c4f0829cb-00001.parquet</pre><p>Iceberg tablosunun arka tarafta nasıl depolandığına baktığımızda <strong>metadata</strong> ve <strong>data</strong> dosyalarına ayrıldığını görüyoruz. Teori kısmında değindiğimiz gibi verileri metadata ve data olmak üzere farklı katmanlarda saklıyor.</p><p>Şimdi gelin isterseniz bir UPDATE sorgusu çalıştıralım.</p><pre>spark.sql(&quot;UPDATE hive_prod.de.d_product SET Color=&#39;Pink&#39; WHERE ProductID=1&quot;)<br>spark.sql(&quot;SELECT * FROM hive_prod.de.d_product WHERE ProductID=1&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeKLg5XrPSIJzHzGQUFq-g.png" /></figure><p>Kodu ilk çalıştırdığımda ProductID’si bir olan kaydın Color kolonu <strong>null</strong> olarak gelmekteydi. Update sorgusunu çalıştırdığımız başarılı şekilde ilgili kolonu güncellemiş olduk.</p><p>İceberg tablolarının metadata bilgileri sorgulamak istersek eğer tablomuzu yazdıktan sonra * .files, *. entries , * .snapshots ,*. manifests ,*. partitions gibi keyword’ler girerek bu değerlere ulaşabiliriz.</p><pre>spark.sql(&quot;SELECT * FROM hive_prod.de.d_product.snapshots&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFHFlduatV1m-rQDRHB9Og.png" /></figure><p><strong>snapshots</strong> bilgisi bize tabloyla ilgili geçmişe yönelik nasıl işlemler olduğuyla ilgili bilgi vermekte ve <strong>time travel </strong>bir sorgu çalıştırmak istediğimizde bunu yapmamıza olanak sağlayacak bilgileri tutar.Yukarıda gördüğümüz gibi uygulama boyunca yaptığımız iki işlem vardı. İlki tabloyu oluşturup veri yazmak daha sonrasında da bir update sorgusu çalıştırmak. Bu işlemlerle ilgili detay bilgiyi 2 farklı satırda bize sunuyor. Gelin isterseniz time travel bir sorgu çalıştıralım. Yani tablonun update etmeden önceki halini sorgulayalım.</p><pre>spark.read \<br>    .option(&quot;snapshot-id&quot;, 8740618567573872932) \<br>    .format(&quot;iceberg&quot;) \<br>    .load(&quot;hive_prod.de.d_product&quot;) \<br>    .show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2Qt1lZ7fsvrm14nBt1YNA.png" /></figure><p>Sorgu sonucuna baktığımızda ProductID’si 1 olan kaydın Color kolonunun değeri null gözüküyor. Yani biz update etmeden önceki hali.</p><p>Spark haricinde Iceberg tablolarını sorgulayabileceğimiz herhangi bir UI var mı diye soracak olursanız onun içinde Dremio aracını sizlere tavsiye ederim şimdi gelin Dremio aracını kullanarak tablomuzu sorgulayalım.</p><p><strong>Dremio servisini başlatma:</strong></p><pre>emre@emre-lenovo:~/dremio/bin$ ./dremio start<br>emre@emre-lenovo:~/dremio/bin$ ./dremio status<br>dremio is running.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BMSeme9H0Ut3RTrMpaSVg.png" /><figcaption><a href="http://localhost:9047/"><strong>http://localhost:9047/</strong></a></figcaption></figure><p><strong>9047</strong> portuna giderek Dremio Web UI ekranına ulaşabilirsiniz.</p><p>Iceberg tablosunu okumadan önce Hive Metastore bağlantımızı oluşturalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtRvUK9mNZOT_iViyab0Jg.png" /></figure><p>Bağlantımızı oluşturduktan sonra Iceberg tablomuza sorgu atabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z798HYn_KxISqecGSyOvaQ.png" /></figure><p>Görmüş olduğunuz gibi Iceberg tablosunu UI kullanarak da sorgulamış olduk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXBrzbi7N34HeFmJx5CAVA.png" /></figure><p>Yukarıda görüldüğü gibi Update işlemi de yapabiliyoruz.</p><p>Dremio üzerinden metadata bilgilerine ulaşmak istersek de aşağıdaki gibi kullanımlar mevcut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LKMzXi-6l1SQDROqtc8wg.png" /></figure><p>Dremio üzerinden time travel bir sorgu atmak istediğimizde ise aşağıdaki gibi bir kullanımla ilerleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ad9XFbhRgnLEfbBK6ejqfw.png" /></figure><p>Son olarak Presto aracını kullanarak da Iceberg tablolarını sorgulayabiliriz.</p><p><strong>Presto için Iceberg bağlantısı oluşturma ve servisi çalıştırma:</strong></p><pre>emre@emre-lenovo:~/Presto/presto-server-0.283/etc/catalog$ pwd<br>/home/emre/Presto/presto-server-0.283/etc/catalog<br>emre@emre-lenovo:~/Presto/presto-server-0.283/etc/catalog$ cat iceberg.properties <br>connector.name=iceberg<br>hive.metastore.uri=thrift://localhost:9083<br>iceberg.catalog.type=hive<br><br>emre@emre-lenovo:~/Presto/presto-server-0.283/bin$ ./launcher start</pre><p><strong>DBeaver kullanarak Presto sunucusuna bağlanma:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2blENpfwB1IWTbGSTmn5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6N115q-4oggOR9GkAyIcTA.png" /></figure><p>Presto kullanarak da Iceberg tablolarımızı sorgulayabiliriz.</p><p>Şimdi Python’da Iceberg için oluşturulmuş <strong>pyiceberg </strong>kütüphanesi üzerinde birkaç işlem yapalım.</p><p><strong>Kütüphanenin yüklenmesi:</strong></p><pre>(icebergenv) emre@emre-lenovo:~$ pip3 install &quot;pyiceberg[s3fs,hive]&quot;</pre><pre>(icebergenv) emre@emre-lenovo:~$ pyiceberg --uri thrift://localhost:9083 list<br>de      <br>default <br>football<br>nyc     <br>school </pre><p>Her sefereinde metadata bilgileri için uri gibi bilgileri girmek istemezseniz aşağıdaki gibi bir yaml dosyası oluşturabilirsiniz.</p><pre>vi ~/.pyiceberg.yaml<br>---<br>catalog:<br>    default:<br>        uri: thrift://localhost:9083<br>        s3.endpoint: hdfs://localhost:9000</pre><pre>(icebergenv) emre@emre-lenovo:~$ pyiceberg list<br>de      <br>default <br>football<br>nyc     <br>school</pre><pre>from pyiceberg.catalog import load_catalog<br>from pyiceberg.expressions import GreaterThanOrEqual<br><br><br>catalog = load_catalog(&quot;default&quot;)<br>print(catalog.list_namespaces())<br>print(catalog.list_tables(&quot;de&quot;))<br># export CLASSPATH=`$HADOOP_HOME/bin/hdfs classpath --glob`<br><br>product_table = catalog.load_table(&quot;de.d_product&quot;)<br><br>scan = product_table.scan(<br>    row_filter=GreaterThanOrEqual(&quot;ListPrice&quot;, 1),<br>    selected_fields=(&quot;ProductID&quot;, &quot;Color&quot;, &quot;MakeFlag&quot;),<br>    limit=100<br>)<br><br>scan_df = scan.to_pandas()<br><br>print(scan_df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhsEwVKmRWWLO68FaZ3Zrw.png" /></figure><p><strong>PyIceberg</strong> kütüphanesi kullanarak da Iceberg tablolarıyla ilgili çoğu işlemleri yönetebiliyoruz.</p><p>Bu yazımda sizlere Apache İceberg’i genel hatlarıyla açıklayıp daha sonrasında da kullanımlarıyla ilgili örnekler vermeye çalıştım. Umarım sizler için faydalı olmuştur. Herhangi bir sorunuz ve öneriniz olursa benimle iletişime geçebilirsiniz👏👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1bcb06935b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming Data Pipeline Proje Örneği (Kafka,Spark,HBase,Phoenix,Streamlit)]]></title>
            <link>https://medium.com/bentego-teknoloji/streaming-data-pipeline-proje-%C3%B6rne%C4%9Fi-kafka-spark-hbase-phoenix-streamlit-d92b2b46f773?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92b2b46f773</guid>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 13:18:59 GMT</pubDate>
            <atom:updated>2023-09-07T13:09:13.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese Merhabalar, bugünkü yazımda sizlere örnek bir canlı veri akışı projesi aktaracağım.</p><p>İlk önce proje mimarisini görsel olarak bir inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaCWaZoG4oLgVmGOB6WzNw.png" /></figure><p>Akışı yazılı olarak ifade etmek gerekirse yazdığımız <strong>Python</strong> koduyla satış verisi(<strong>Avro</strong> formatında) üretiyoruz ve bu verileri <strong>Kafka</strong>’da oluşturduğumuz topic’e iletiyoruz. Daha sonrasında <strong>Spark Streaming </strong>kullanarak topic’i canlı bir şekilde dinleyip verileri <strong>HBase</strong>’e gönderiyoruz. <strong>HBase</strong> üzerindeki verileri SQL yeteneklerimizi kullanarak sorgulamak istediğimiz için <strong>Phoenix</strong> aracını devreye alıyoruz. Burada shell ekranı yerine <strong>DBeaver</strong> kullanarak daha esnek çalışabiliriz. Son olarak da Python’ın <strong>Streamlit</strong> kütüphanesini kullanarak analiz ettiğimiz verileri dashboard’lar oluşturarak son kullanıcıya sunuyoruz.</p><p>Gerekli servislerin çalışma durumlarını kontrol edelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*XGUjs0uDPRlmNaNuzXLA4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCwMNMbpfl3es-6ImBD71w.png" /></figure><p>İlk ekran görüntüsünde görmüş olduğumuz üzere Hbase servisimiz çalışır durumda gözüküyor.(<strong>HMaster</strong>,<strong>HRegion</strong> ve <strong>Hadoop Bileşenleri</strong>)</p><p>İkinci ekran görüntüsünde de <strong>Kafka</strong> servisimizin, verileri <strong>Avro</strong> formatında gönderdiğimiz için <strong>Schema Registry </strong>servisimiz ve hem <strong>Kafka</strong>’nın hem de <strong>HBase</strong>’in kullandığı<strong> Zookeeper</strong> servisimiz çalışır durumda gözüküyor.</p><p><strong>HBase</strong> üzerinde verileri yazacağımız tablonun oluşturulması için aşağıdaki komutu çalıştırıyoruz.</p><pre>hbase-shell<br>...<br>hbase:002:0&gt; create &#39;order&#39;, &#39;order-data&#39;<br>...<br>Created table order<br>Took 2.3048 seconds                                                             <br>=&gt; Hbase::Table - order</pre><p>Şimdi <strong>Kafka</strong>’ya veri üretecek <strong>Python</strong> kodumuzu inceleyip akışı başlatabiliriz.</p><pre>import pandas as pd<br>from faker import Faker<br>import random as rd<br>import time<br>from confluent_kafka import avro<br>from confluent_kafka.admin import AdminClient, NewTopic<br>from confluent_kafka.avro import AvroProducer,CachedSchemaRegistryClient<br>import re<br>import datetime<br><br>SCHEMA_REGISTRY_URL = &quot;http://localhost:8881&quot;<br>BROKER_URL = &quot;localhost:9092&quot;<br><br>admin_client = AdminClient({&#39;bootstrap.servers&#39;: BROKER_URL})<br>order_topic = [NewTopic(&#39;order-topic&#39;, num_partitions=1, replication_factor=1)]<br><br>fs = admin_client.create_topics(order_topic)<br><br>schema = avro.loads(<br>        &quot;&quot;&quot;{<br>    &quot;type&quot;:&quot;record&quot;,<br>    &quot;name&quot;:&quot;myrecord&quot;,<br>    &quot;fields&quot;: [<br>        {<br>            &quot;name&quot;: &quot;CustomerID&quot;,<br>            &quot;type&quot;: &quot;int&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;CustomerName&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Email&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Address&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;State&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;PhoneNumber&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;InvoiceDate&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;StockCode&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Description&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;UnitPrice&quot;,<br>            &quot;type&quot;: &quot;float&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Quantity&quot;,<br>            &quot;type&quot;: &quot;int&quot;<br>        }<br>    ]<br>}&quot;&quot;&quot;<br>    )<br><br>schema_registry = CachedSchemaRegistryClient({&quot;url&quot;: SCHEMA_REGISTRY_URL})<br><br>data = pd.read_csv(&#39;OnlineRetail.csv&#39;, sep = &#39;;&#39;)<br><br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].str.replace(&#39;A&#39;,&#39;&#39;)<br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].str.replace(&#39;C&#39;,&#39;&#39;)<br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].astype(&quot;int64&quot;)<br>data[&quot;StockCode&quot;] = data[&quot;StockCode&quot;].astype(&quot;string&quot;)<br>data[&quot;Description&quot;] = data[&quot;Description&quot;].astype(&quot;string&quot;)<br>data[&quot;UnitPrice&quot;] = data[&quot;UnitPrice&quot;].str.replace(&#39;,&#39;,&#39;.&#39;).astype(&quot;float&quot;)<br><br>cols = [&#39;StockCode&#39;,&#39;Description&#39;, &#39;UnitPrice&#39;]<br>Stock_Desc_Unit_lst = data[cols].values.tolist()<br><br>fake = Faker()<br><br>def create_data(x):<br>    project_data = {}<br>    for i in range(x):<br>        project_data[i] = {}<br>        project_data[i][&#39;CustomerID&#39;] = i + 1<br>        project_data[i][&#39;Name&#39;] = fake.name()<br><br>    return project_data<br><br>df = pd.DataFrame(create_data(5000)).transpose()<br><br>cols = [&#39;CustomerID&#39;,&#39;Name&#39;]<br>CustomerID_Name = df[cols].values.tolist()<br>Q_df = data[data[&quot;Quantity&quot;]&gt;0]<br>Quantity = Q_df[&quot;Quantity&quot;].values.tolist()<br><br>now = datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>def produce_kafka_dict(topic_name,json_as_dict):<br>    producer=AvroProducer({&quot;bootstrap.servers&quot;: BROKER_URL}, schema_registry=schema_registry)<br><br>    producer.produce( topic=topic_name,<br>                value=json_as_dict,<br>                value_schema=schema)<br>    producer.flush()<br><br>while True:<br>#for i in range(50):<br>    order={}<br>    n = rd.randint(1,10)<br>    time.sleep(rd.randint(1,15))<br>    CID_Name = rd.choice(CustomerID_Name)<br>    order[&quot;CustomerID&quot;]= CID_Name[0]<br>    order[&quot;CustomerName&quot;] = CID_Name[1]<br>    order[&quot;Email&quot;] = CID_Name[1].lower().replace(&#39; &#39;,&#39;.&#39;) + &quot;@gmail.com&quot;<br>    order[&quot;Address&quot;] = fake.address().replace(&#39;\n&#39;,&#39; &#39;)<br>    order[&quot;State&quot;] = re.findall(&quot;[A-Z]{2}&quot;, order[&quot;Address&quot;])[0]<br>    order[&quot;PhoneNumber&quot;] = fake.phone_number()[0:10]<br>    order[&quot;InvoiceDate&quot;] = datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    for a in range(n):<br>        Stock_Desc_Unit = rd.choice(Stock_Desc_Unit_lst)<br>        order[&quot;StockCode&quot;] = Stock_Desc_Unit[0]<br>        order[&quot;Description&quot;] = Stock_Desc_Unit[1]<br>        order[&quot;UnitPrice&quot;] = Stock_Desc_Unit[2]<br>        order[&quot;Quantity&quot;]  = rd.choice(Quantity)<br>        produce_kafka_dict(&#39;order-topic&#39;,order)<br>        print(order)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6hBYC6YVeo39G03cGSr5g.png" /></figure><p>Evet kodumuzu çalıştırdığımızda ve <strong>Kafka </strong>topic’ini dinlediğimizde verilerin başarılı şekilde aktığını görebiliyoruz.</p><p>Şimdi ise <strong>Kafka</strong>’dan verileri okuyup <strong>HBase</strong>’e yazacak olan <strong>Spark</strong> kodumuzu inceleyelim.</p><pre>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as func<br>from pyspark.sql.avro.functions import from_avro<br>from confluent_kafka.schema_registry import SchemaRegistryClient<br><br><br>kafka_url = &quot;localhost:9092&quot;<br>schema_registry_url = &quot;http://localhost:8881&quot;<br>kafka_producer_topic = &quot;order-topic&quot;<br>schema_registry_subject = f&quot;{kafka_producer_topic}-value&quot;<br><br><br>spark = SparkSession \<br>        .builder \<br>        .master(&quot;yarn&quot;) \<br>        .appName(&quot;ordertopic_consumer&quot;) \<br>        .config(&quot;spark.jars.packages&quot;, &quot;org.apache.hbase:hbase-shaded-mapreduce:2.4.15,org.apache.spark:spark-avro_2.12:3.0.1&quot;) \<br>        .config(&quot;spark.jars&quot;, &quot;/home/emre/Desktop/DE-Project-Hbase-Phoenix/hbase-spark-1.0.1-SNAPSHOT_spark331_hbase2415.jar,/home/emre/Desktop/DE-Project-Hbase-Phoenix/hbase-spark-protocol-shaded-1.0.1-SNAPSHOT_spark331_hbase2415.jar&quot;) \<br>        .getOrCreate()<br><br>spark.sparkContext.setLogLevel(&quot;ERROR&quot;)<br><br>def get_schema_from_schema_registry(schema_registry_url, schema_registry_subject):<br>    sr = SchemaRegistryClient({&#39;url&#39;: schema_registry_url})<br>    latest_version = sr.get_latest_version(schema_registry_subject)<br><br>    return sr, latest_version<br><br>_, latest_version_ordertopic = get_schema_from_schema_registry(schema_registry_url, schema_registry_subject)<br>fromAvroOptions = {&quot;mode&quot;:&quot;PERMISSIVE&quot;}<br><br><br>def write_to_hbase(batch_df, epoch_id):<br>   <br>   hbase_schema = &quot;&quot;&quot;CustomerID INT :key, CustomerName STRING order-data:CustomerName, <br>               Email STRING order-data:Email, Address STRING order-data:Address, State STRING order-data:State, <br>               PhoneNumber STRING order-data:PhoneNumber, InvoiceDate TIMESTAMP order-data:InvoiceDate,<br>               StockCode STRING order-data:StockCode, Description STRING order-data:Description,<br>               UnitPrice FLOAT order-data:UnitPrice, Quantity INT order-data:Quantity <br>&quot;&quot;&quot;<br>   <br>   batch_df.write.format(&quot;org.apache.hadoop.hbase.spark&quot;) \<br>     .option(&quot;hbase.columns.mapping&quot;,hbase_schema) \<br>     .option(&quot;hbase.namespace&quot;, &quot;default&quot;) \<br>     .option(&quot;hbase.table&quot;, &quot;order&quot;) \<br>     .option(&quot;hbase.spark.use.hbasecontext&quot;, False).save()<br><br><br><br>checkpointDir = &quot;file:///tmp/streaming/kafka-order&quot;<br><br>ordertopic_df = spark \<br>    .readStream\<br>    .format(&quot;kafka&quot;)\<br>    .option(&quot;kafka.bootstrap.servers&quot;, kafka_url)\<br>    .option(&quot;subscribe&quot;, kafka_producer_topic)\<br>    .option(&quot;startingOffsets&quot;, &quot;earliest&quot;)\<br>    .load()<br><br>ordertopic_df = ordertopic_df.withColumn(&quot;fixedValue&quot;, func.expr(&quot;substring(value, 6, length(value)-5)&quot;))<br><br>decoded_output = ordertopic_df.select(<br>    from_avro(<br>        func.col(&quot;fixedvalue&quot;), latest_version_ordertopic.schema.schema_str, fromAvroOptions<br>    )<br>    .alias(&quot;ordertopic&quot;))<br><br>order_value_df = decoded_output \<br>                       .select(&quot;ordertopic.*&quot;)<br>    <br>order_value_df = order_value_df \<br>    .withColumn(&quot;InvoiceDate&quot;, func.to_timestamp(func.col(&quot;InvoiceDate&quot;)))\<br>    .withColumn(&quot;CustomerID&quot;,func.col(&quot;CustomerID&quot;).cast(&quot;integer&quot;)) \<br><br>order_value_df.printSchema()<br>    <br>query = order_value_df.writeStream \<br>    .foreachBatch(write_to_hbase) \<br>    .start()<br>    <br>query.awaitTermination()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQdUU7-oJusHW99GlBah1w.png" /></figure><p><strong>Spark</strong> kodunu çalıştırdığımızda <strong>Kafka</strong>’daki verilerin başarılı şekilde <strong>HBase</strong>’e yazıldığını görmekteyiz. <strong>count</strong> komutunu kullanarak da veri akışının takibini yapabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*X4OY0nExqAX78B6bRSWQbA.png" /></figure><p>Yukarıdaki ekran görüntülerinde de görmüş olacağınız üzere <strong>HBase</strong>’in kendine has bir sorgu dili mevcut.Biz eğer burada depolanan verileri <strong>SQL</strong> yetenekleri kullanarak sorgulamak istersek bunun için açık kaynak ürünü olan<strong> Apache Phoenix’</strong>i kullanabiliriz. Dilerseniz <strong>DBeaver</strong> üzerinden bağlantı sağlayarak<strong> HBase </strong>üzerindeki verilerimizi sorgulayalım.</p><p><strong>DBeaver</strong> ile <strong>Apache Phoenix </strong>sunucusuna bağlanmak istediğinizde <strong>DBeaver</strong>’ın default olarak indirdiği driver’ı değilde sizde kurulu olan versiyonundaki client’ı eklemeniz gerekecek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoAnXG0ZqAlXNTx4-LpK8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*ts4_966Jsm_69Lqzd4jPFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0cFhlskWIhcSZG4K_tCPg.png" /></figure><p>Bende <strong>Apache Phoenix’ın</strong> kurulu olduğu dizine gittiğimde oradaki <strong>phoenix-client-hbase-2.5.jar’ı </strong>driver olarak kendim belirtiyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQAH9ivilFYgSk9DylrfWw.png" /></figure><p>Bağlantıyı test ettiğimizde başarılı olduğunu görmekteyiz.</p><pre>CREATE VIEW &quot;order&quot;<br>(<br>&quot;ID&quot; UNSIGNED_INT PRIMARY KEY,<br>&quot;order-data&quot;.&quot;CustomerName&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;Email&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;Address&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;State&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;PhoneNumber&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;InvoiceDate&quot; UNSIGNED_DATE,<br>&quot;order-data&quot;.&quot;StockCode&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;Description&quot; VARCHAR,<br>&quot;order-data&quot;.&quot;UnitPrice&quot; UNSIGNED_FLOAT,<br>&quot;order-data&quot;.&quot;Quantity&quot; UNSIGNED_INT<br>)<br><br>-- DROP VIEW &quot;order&quot;<br><br>SELECT &quot;CustomerName&quot;,&quot;Email&quot;,&quot;State&quot;,&quot;InvoiceDate&quot;,UPPER(&quot;StockCode&quot;) &quot;StockCode&quot;,ROUND(&quot;UnitPrice&quot;,2) AS &quot;UnitPrice&quot;,&quot;Quantity&quot; <br>FROM &quot;order&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNr45cK_KFOgiJpMvxjXGw.png" /></figure><p><strong>Phoenix</strong> üzerinde oluşturduğumuz <strong>View</strong> sayesinde <strong>HBase</strong> üzerindeki verileri <strong>SQL</strong> yeteneklerimizi kullanarak analiz edebiliriz.</p><p>Her şey yolunda gittiğine göre son aşamamız olan analiz edilen verinin <strong>Streamlit</strong> aracılığıyla son kullanıcıya gösterilmesi kaldı.</p><p>Gelin Streamlit için yazdığımız kodu ve nasıl çalıştırmamız gerektiğine bir bakalım.</p><pre>import jaydebeapi as jdbc<br>import os<br>import pandas as pd<br>from datetime import datetime<br>import streamlit as st<br><br>st.set_page_config(layout=&#39;wide&#39;)<br>st.header(&quot;Sales Report&quot;)<br><br>cwd = os.getcwd()<br>jar = cwd + &#39;/streamlit/phoenix-client-hbase-2.5.jar&#39;<br>drivername = &#39;org.apache.phoenix.jdbc.PhoenixDriver&#39;<br>url = &#39;jdbc:phoenix:localhost:2181/&#39;<br>curr_date = datetime.today().strftime(&#39;%Y-%m-%d&#39;)<br><br>conn = jdbc.connect(url= url, jars=jar ,jclassname=drivername, <br> driver_args={&quot;phoenix.schema.isNamespaceMappingEnabled&quot;: &quot;true&quot;})<br><br>cursor = conn.cursor()<br><br>query = f&#39;&#39;&#39;<br> SELECT *<br> FROM &quot;order&quot; WHERE SUBSTR(TO_CHAR(&quot;InvoiceDate&quot;),1,10) = &#39;{curr_date}&#39;<br><br>&#39;&#39;&#39;<br><br>query_2 = f&#39;&#39;&#39;<br> SELECT &quot;State&quot;, ROUND(SUM(&quot;UnitPrice&quot; * &quot;Quantity&quot;),2) AS &quot;Income&quot;<br> FROM &quot;order&quot; WHERE SUBSTR(TO_CHAR(&quot;InvoiceDate&quot;),1,10) = &#39;{curr_date}&#39;<br> GROUP BY &quot;State&quot;<br> ORDER BY 2 DESC<br> LIMIT 10<br>&#39;&#39;&#39;<br><br>query_3 = f&#39;&#39;&#39;<br> SELECT SUBSTR(TO_CHAR(&quot;InvoiceDate&quot;),12,2) AS &quot;HOUR&quot;, ROUND(SUM(&quot;UnitPrice&quot; * &quot;Quantity&quot;),2) AS &quot;Income&quot;<br> FROM &quot;order&quot; WHERE SUBSTR(TO_CHAR(&quot;InvoiceDate&quot;),1,10) = &#39;{curr_date}&#39;<br> GROUP BY SUBSTR(TO_CHAR(&quot;InvoiceDate&quot;),12,2)<br> ORDER BY 1 DESC<br><br>&#39;&#39;&#39;<br><br>df_raw_data = pd.read_sql(query, conn)<br><br>df_top_income_state = pd.read_sql(query_2, conn)<br><br>df_top_income_hour = pd.read_sql(query_3, conn)<br><br>with st.expander(&#39;View Raw Data&#39;):<br> st.dataframe(df_raw_data, hide_index=True)<br><br>with st.expander(&#39;Top 10 State by Income&#39;):<br> st.dataframe(df_top_income_state, hide_index=True)<br><br>st.bar_chart(df_top_income_state, x=&quot;State&quot;, y=&quot;Income&quot;)<br><br>with st.expander(&#39;Top 10 State by Hour&#39;):<br> st.dataframe(df_top_income_hour, hide_index=True)<br><br>st.line_chart(df_top_income_hour, x=&quot;HOUR&quot;, y=&quot;Income&quot;)</pre><pre>streamlit run streamlit/strlmt-code.py <br>------<br> You can now view your Streamlit app in your browser.<br> Local URL: http://localhost:8501<br> Network URL: http://xxx.xxx.xx.xxx:8501</pre><p>Streamlit uygulamasını başlattığınızda yukarıdaki gibi size erişebileceğiniz URL’ler paylaşılmakta. Herhangi bir web browser üzerinden giriş yaparak kontrol sağlayabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2rOV44HeHRnXzKXBPIjzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjF0hjQYJQEbopImJPILOA.png" /></figure><p>Böylece <strong>Apache Phoenix</strong> üzerinde analiz ettiğimiz verileri son kullanıcıya göstermiş olduk.</p><p>Umarım sizler için faydalı bir yazı olmuştur. Herhangi bir sorunuz veya görüşünüz varsa benimle iletişime geçebilirsiniz. Görüşmek üzere👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92b2b46f773" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentego-teknoloji/streaming-data-pipeline-proje-%C3%B6rne%C4%9Fi-kafka-spark-hbase-phoenix-streamlit-d92b2b46f773">Streaming Data Pipeline Proje Örneği (Kafka,Spark,HBase,Phoenix,Streamlit)</a> was originally published in <a href="https://medium.com/bentego-teknoloji">Bentego Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI ile MongoDB üzerindeki Verileri Sunma]]></title>
            <link>https://emreevcimen.medium.com/fastapi-ile-mongodb-%C3%BCzerindeki-verileri-sunma-aeb28262f7e8?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeb28262f7e8</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 20:18:15 GMT</pubDate>
            <atom:updated>2023-07-17T09:45:56.491Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar bu yazımda sizlere MongoDB de bulunan verilerimizi FastAPI yardımı ile sunma işlemini aktaracağım. İlk olarak yazı boyunca ele alacağımız sürecin mimarisine bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*_TwwP6hZmz3yQ2LUUO-raw.png" /></figure><p>Yukarıda görmüş olduğunuz gibi aslında PostgreSQL’de bulunan verilerimizi Python dilini kullanarak MongoDB’ye aktarıyoruz daha sonrasında FastAPI ile MongoDB’de bulunan verilerimizi sunuyoruz. Postman yardımı ile de her şey istediğimiz gibi mi gerçekleşiyor onu kontrol edeceğiz.</p><p>İlk aşama olarak getdata_from_psql uzantılı kodumuza bakarak PostgreSQL’den verileri nasıl alıyoruz onu inceleyelim.</p><pre>import logging<br>from sqlalchemy import create_engine, text<br>from sqlalchemy.exc import OperationalError<br>import configparser<br><br>parser = configparser.ConfigParser()<br>parser.read(&quot;conf.ini&quot;)<br><br><br>def connect_yemeksepetidb():<br>    try:<br>        database_url = f&quot;postgresql://{parser.get(&#39;postgresql&#39;,&#39;username&#39;)}:{parser.get(&#39;postgresql&#39;,&#39;password&#39;)}@{parser.get(&#39;postgresql&#39;,&#39;hostname&#39;)}/yemeksepetidb&quot;<br>        engine = create_engine(database_url)<br>        conn = engine.connect()<br>        return conn<br>    except OperationalError as err:<br>        logging.error(&quot;Cannot connect to DB %s&quot;, err)<br><br>def execute_query():<br>    conn = connect_yemeksepetidb()<br>    table_name = &quot;restaurant_comments&quot;<br>    comments = []<br>    try:<br>        query = conn.execute(text(f&quot;select * from {table_name}&quot;))<br>        for data in query.fetchall():<br>            comment = {<br>                &quot;comment_id&quot;: data[0],<br>                &quot;comment&quot;: data[1],<br>                &quot;restaurant_name&quot;: data[2] <br>            }<br>            comments.append(comment)<br>        return comments<br>            <br>    except OperationalError as err:<br>        logging.error(&quot;Query failed &amp;s&quot;, err)<br></pre><pre># conf.ini<br>[postgresql]<br>hostname=xxxxxxxx<br>password=xxxxxxxx<br>username=xxxxxxxx<br>port=xxxxxxx<br>[mongodb]<br>hostname=xxxxxx<br>port=xxxxxx</pre><p>PostgreSQL’de belirlediğimiz tablodan verilerin her birini dictionary yapı da alarak hepsini liste içeriside tutuyoruz ve execute_query fonksiyonunun çıktısı olarak bu listeyi döndürüyoruz.</p><p>Daha sonrasında ise write_data_to_mdb kodunun içerisinde de bu liste içerisindeki verileri MongoDB’ye basıyoruz. Aşağıda ilgili kodu paylaşıyorum.</p><pre>from pymongo import MongoClient<br>from pymongo.errors import ConnectionFailure<br>from get_data_from_psql import execute_query<br>import logging<br>import configparser<br><br>parser = configparser.ConfigParser()<br>parser.read(&quot;conf.ini&quot;)<br><br>def mongodb_conn():<br>    try:<br>        logging.info(&quot;Attempting to connect...&quot;)<br>        client = MongoClient(f&#39;mongodb://{parser.get(&quot;mongodb&quot;,&quot;hostname&quot;)}:{parser.get(&quot;mongodb&quot;,&quot;port&quot;)}&#39;)<br>        db = client[&#39;yemeksepetidb&#39;]<br>        return db<br>    except ConnectionFailure as e:<br>        logging.error(&quot;ConnectionFailure seen: &quot; + str(e))<br><br><br>def write_to_mongodb():<br>    comments = execute_query()<br>    db = mongodb_conn()<br>    collection = db[&quot;restaurant_comments&quot;]<br>    for item in comments:<br>        collection.insert_one(item)<br>        logging.info(&quot;Item write to mongodb&quot;)<br><br>write_to_mongodb()</pre><p>MongoDB Compass aracını kullanarak verilerimiz belirttiğimiz collection içerisine gelmiş mi kontrol edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdaWqsdsI8bO4G9db-5FzA.png" /></figure><p>Kontrol sağladığımız da başarılı şekilde verilerin geldiğini görebiliriz.</p><p>Son aşama olarak FastAPI kütüphanesini kullanarak MongoDB üzerindeki verilerimizi sunalım.</p><pre>from pymongo import MongoClient<br>from fastapi import FastAPI<br>import configparser<br><br>parser = configparser.ConfigParser()<br>parser.read(&quot;conf.ini&quot;)<br><br>mongodb_uri = f&quot;mongodb://{parser.get(&#39;mongodb&#39;,&#39;hostname&#39;)}:{parser.get(&#39;mongodb&#39;,&#39;port&#39;)}/&quot;<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: f&quot;Welcome Comment API&quot;}<br><br>@app.get(&quot;/restaurants&quot;)<br>async def get_distinct_restaurant():<br>    with MongoClient(mongodb_uri) as client:<br>        restaurant_collection = client[&quot;yemeksepetidb&quot;][&quot;restaurant_comments&quot;]<br>        distinct_restaurant_list = restaurant_collection.distinct(&quot;restaurant_name&quot;)<br>        return distinct_restaurant_list<br><br><br>@app.get(&quot;/comments&quot;)<br>async def get_all_comments():<br>    with MongoClient(mongodb_uri) as client:<br>        comment_collection = client[&quot;yemeksepetidb&quot;][&quot;restaurant_comments&quot;]<br>        comment_response = comment_collection.find({},{&quot;_id&quot;:0})<br>        cmnt_list = []<br>        for comment in comment_response:<br>            cmnt_list.append(comment)<br>        return cmnt_list<br><br>@app.get(&quot;/comment/{comment_id}&quot;)<br>async def get_comment_by_id(comment_id:int):<br>    with MongoClient(mongodb_uri) as client:<br>        comment_collection = client[&quot;yemeksepetidb&quot;][&quot;restaurant_comments&quot;]<br>        comment_response = comment_collection.find({&quot;comment_id&quot;:comment_id},{&quot;_id&quot;:0})<br>        for comment in comment_response:<br>            return comment</pre><p>FastAPI servisini başlatmak için aşağıdaki kodu çalıştırabilirsiniz.</p><pre>uvicorn making_a_rest_api:app --reload</pre><p>Şimdi Postman aracını kullanarak test işlemlerimizi gerçekleştirelim.</p><blockquote><a href="http://localhost:8000/"><strong>http://localhost:8000</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_U--womXgUNJ9JMXAJ4QA.png" /></figure><blockquote><a href="http://localhost:8000/comments"><strong>http://localhost:8000/comments</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cql6fi_8E7ZvWreGkHqExA.png" /></figure><blockquote><a href="http://localhost:8000/comment/1"><strong>http://localhost:8000/comment/1</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ht0901R5Aa_D-rj2F7FJgw.png" /></figure><blockquote><a href="http://localhost:8000/restaurants"><strong>http://localhost:8000/restaurants</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqzfovHihkMHkrzZ76HUMg.png" /></figure><p>Test işlemlerimizi de başarılı şekilde gerçekleştirdik. Her şey istediğimiz gibi gözüküyor. 👏👌</p><p>Umarım sizler için faydalı bir yazı olmuştur. Bir sonraki yazıda görüşmek üzere 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeb28262f7e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Connect ile HDFS’e Veri Gönderme İşlemi]]></title>
            <link>https://medium.com/bentego-teknoloji/kafka-connect-ile-hdfse-veri-g%C3%B6nderme-i%CC%87%C5%9Flemi-c12b3c7d4789?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12b3c7d4789</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[hdfs]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 19:07:26 GMT</pubDate>
            <atom:updated>2023-07-18T11:07:50.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*Lg2m8BY3PCLTCkLpoSzxVQ.png" /></figure><p>Merhabalar bu yazımda sizlere <strong>Kafka</strong>’da bulunan verilerimizi nasıl<strong> Kafka Connector</strong> yardımı ile <strong>HDFS</strong>’e taşıyabileceğimizi göstereceğim. İlk önce gerekli <strong>Connector</strong>’umuzu indirelim ve servislerimizi başlatalım.</p><pre># HDFS3 Sink Connector indirme işlemi<br>confluent-hub install confluentinc/kafka-connect-hdfs3:1.1.25<br><br># Gerekli servisleri başlatma<br>confluent local services zookeeper start<br>confluent local services kafka start<br>confluent local services schema-registry start<br>confluent local services connect start<br><br># Servislerin durumunu takip etmek için <br>confluent local services status<br><br># Control Center yerine kullanacağım AKHQ servisini başlatmak için<br>java -Dmicronaut.config.files=akhq.yml -jar akhq.jar</pre><pre># akhq.yml içeriği <br>akhq:<br>  connections:<br>    local:<br>      properties:<br>        bootstrap.servers: &quot;localhost:9092&quot;<br>      schema-registry:<br>        url: &quot;http://localhost:8881&quot;<br>      connect:<br>        - name: &quot;connect&quot;<br>          url: &quot;http://localhost:8083&quot;<br>micronaut:<br>  server:<br>    port: 8880</pre><blockquote><strong>AKHQ Web UI</strong> erişimi için: http://localhost:8880/ui/</blockquote><p>Gerekli servislerimizi başlattık ve çalışma durumlarını kontrol ettikten sonra şimdi ise <strong>Kafka</strong>’da berlittiğimiz topic’e veri aktaracak olan <strong>Python</strong> kodumuza bakalım.</p><pre>import pandas as pd<br>from faker import Faker<br>import random as rd<br>import time<br>from confluent_kafka import avro<br>from confluent_kafka.admin import AdminClient, NewTopic<br>from confluent_kafka.avro import AvroProducer,CachedSchemaRegistryClient<br>import re<br>import datetime<br><br>SCHEMA_REGISTRY_URL = &quot;http://localhost:8881&quot;<br>BROKER_URL = &quot;localhost:9092&quot;<br><br>admin_client = AdminClient({&#39;bootstrap.servers&#39;: BROKER_URL})<br>order_topic = [NewTopic(&#39;order-topic&#39;, num_partitions=1, replication_factor=1)]<br><br>fs = admin_client.create_topics(order_topic)<br><br>schema = avro.loads(<br>        &quot;&quot;&quot;{<br>    &quot;type&quot;:&quot;record&quot;,<br>    &quot;name&quot;:&quot;myrecord&quot;,<br>    &quot;fields&quot;: [<br>        {<br>            &quot;name&quot;: &quot;CustomerID&quot;,<br>            &quot;type&quot;: &quot;int&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;CustomerName&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Email&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Address&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;State&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;PhoneNumber&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;InvoiceDate&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;StockCode&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Description&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;UnitPrice&quot;,<br>            &quot;type&quot;: &quot;float&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Quantity&quot;,<br>            &quot;type&quot;: &quot;int&quot;<br>        }<br>    ]<br>}&quot;&quot;&quot;<br>    )<br><br>schema_registry = CachedSchemaRegistryClient({&quot;url&quot;: SCHEMA_REGISTRY_URL})<br><br>data = pd.read_csv(&#39;OnlineRetail.csv&#39;, sep = &#39;;&#39;)<br><br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].str.replace(&#39;A&#39;,&#39;&#39;)<br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].str.replace(&#39;C&#39;,&#39;&#39;)<br>data[&quot;InvoiceNo&quot;] = data[&quot;InvoiceNo&quot;].astype(&quot;int64&quot;)<br>data[&quot;StockCode&quot;] = data[&quot;StockCode&quot;].astype(&quot;string&quot;)<br>data[&quot;Description&quot;] = data[&quot;Description&quot;].astype(&quot;string&quot;)<br>data[&quot;UnitPrice&quot;] = data[&quot;UnitPrice&quot;].str.replace(&#39;,&#39;,&#39;.&#39;).astype(&quot;float&quot;)<br><br>cols = [&#39;StockCode&#39;,&#39;Description&#39;, &#39;UnitPrice&#39;]<br>Stock_Desc_Unit_lst = data[cols].values.tolist()<br><br>fake = Faker()<br><br>def create_data(x):<br>    project_data = {}<br>    for i in range(x):<br>        project_data[i] = {}<br>        project_data[i][&#39;CustomerID&#39;] = i + 1<br>        project_data[i][&#39;Name&#39;] = fake.name()<br><br>    return project_data<br><br>df = pd.DataFrame(create_data(5000)).transpose()<br><br>cols = [&#39;CustomerID&#39;,&#39;Name&#39;]<br>CustomerID_Name = df[cols].values.tolist()<br>Q_df = data[data[&quot;Quantity&quot;]&gt;0]<br>Quantity = Q_df[&quot;Quantity&quot;].values.tolist()<br><br>now = datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>def produce_kafka_dict(topic_name,json_as_dict):<br>    producer=AvroProducer({&quot;bootstrap.servers&quot;: BROKER_URL}, schema_registry=schema_registry)<br><br>    producer.produce( topic=topic_name,<br>                value=json_as_dict,<br>                value_schema=schema)<br>    producer.flush()<br><br>while True:<br>    order={}<br>    n = rd.randint(1,10)<br>    time.sleep(rd.randint(1,15))<br>    CID_Name = rd.choice(CustomerID_Name)<br>    order[&quot;CustomerID&quot;]= CID_Name[0]<br>    order[&quot;CustomerName&quot;] = CID_Name[1]<br>    order[&quot;Email&quot;] = CID_Name[1].lower().replace(&#39; &#39;,&#39;.&#39;) + &quot;@gmail.com&quot;<br>    order[&quot;Address&quot;] = fake.address().replace(&#39;\n&#39;,&#39; &#39;)<br>    order[&quot;State&quot;] = re.findall(&quot;[A-Z]{2}&quot;, order[&quot;Address&quot;])[0]<br>    order[&quot;PhoneNumber&quot;] = fake.phone_number()[0:10]<br>    order[&quot;InvoiceDate&quot;] = datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    for a in range(n):<br>        Stock_Desc_Unit = rd.choice(Stock_Desc_Unit_lst)<br>        order[&quot;StockCode&quot;] = Stock_Desc_Unit[0]<br>        order[&quot;Description&quot;] = Stock_Desc_Unit[1]<br>        order[&quot;UnitPrice&quot;] = Stock_Desc_Unit[2]<br>        order[&quot;Quantity&quot;]  = rd.choice(Quantity)<br>        produce_kafka_dict(&#39;order-topic&#39;,order)<br>        print(order)</pre><p>Yukarıdaki kod’u özetlemek gerekirse yapacağı iş random bir şekilde sipariş verisi yaratarak bunu <strong>avro </strong>formatında <strong>Kafka</strong>’da istediğimiz <strong>topic</strong>’e iletmek. Örnek çıktı aşağıdaki gibidir:</p><pre>{&#39;CustomerID&#39;: 824, &#39;CustomerName&#39;: &#39;Robert Bullock&#39;, &#39;Email&#39;: &#39;robert.bullock@gmail.com&#39;, &#39;Address&#39;: &#39;9618 Chambers Centers Apt. 343 Kevinmouth, WA 39994&#39;, &#39;State&#39;: &#39;WA&#39;, &#39;PhoneNumber&#39;: &#39;399.352.69&#39;, &#39;InvoiceDate&#39;: &#39;2023-06-04 21:44:54&#39;, &#39;StockCode&#39;: &#39;23371&#39;, &#39;Description&#39;: &#39;SET 36 COLOUR PENCILS SPACEBOY&#39;, &#39;UnitPrice&#39;: 2.46, &#39;Quantity&#39;: 1}</pre><p><strong>Kafka</strong>’ya iletilen verileri <strong>Kafka CLI</strong> yardımı ile de görüntülemek istersek aşağıdaki script’i kullanabiliriz.</p><pre>kafka-avro-console-consumer \<br>--bootstrap-server localhost:9092 \<br>--topic order-topic \<br>--property schema.registry.url=http://localhost:8881</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fwvtof0D17-SnurS6SZRdg.png" /></figure><p><strong>Python</strong> kodunu durdurmadığınız sürece sürekli sipariş verisi üretilip istediğimiz <strong>topic</strong>’e iletilecek. Şimdi gelin bu verileri<strong> parquet</strong> formatında <strong>HDFS</strong>’e yazmamızı sağlıyacak <strong>connector konfigürasyonunu</strong> oluşturup bunu çalıştıralım.</p><pre>{<br>    &quot;name&quot;: &quot;hdfs3-sink-connector&quot;,<br>    &quot;config&quot;: {<br>        &quot;connector.class&quot;: &quot;io.confluent.connect.hdfs3.Hdfs3SinkConnector&quot;,<br>        &quot;tasks.max&quot;: &quot;1&quot;,<br>        &quot;topics&quot;: &quot;order-topic&quot;,<br>        &quot;hdfs.url&quot;: &quot;hdfs://localhost:9000&quot;,<br>        &quot;flush.size&quot;: &quot;3&quot;,<br>        &quot;key.converter&quot;: &quot;org.apache.kafka.connect.storage.StringConverter&quot;,<br>        &quot;value.converter&quot;: &quot;io.confluent.connect.avro.AvroConverter&quot;,<br>        &quot;value.converter.schema.registry.url&quot;:&quot;http://localhost:8881&quot;,<br>        &quot;confluent.topic.bootstrap.servers&quot;: &quot;localhost:9092&quot;,<br>        &quot;confluent.topic.replication.factor&quot;: &quot;1&quot;,<br>        &quot;format.class&quot;:&quot;io.confluent.connect.hdfs3.parquet.ParquetFormat&quot;,<br>        &quot;partitioner.class&quot;:&quot;io.confluent.connect.storage.partitioner.FieldPartitioner&quot;,<br>        &quot;partition.field.name&quot;:&quot;State&quot;<br>    }<br>}</pre><p>Konfigürasyonumuz yukarıdaki gibidir. İlgili <strong>connector</strong>’u çalıştırmak için ben <strong>Postman</strong> aracını kullandım siz <strong>CLI</strong> yardımıyla da bunu yapabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otq08-0MjvbTbBco5DyP9g.png" /></figure><p><strong>AKHQ Web UI </strong>ekranına giderek başarılı şekilde çalışıp çalışmama durumunu takip edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd5sI7FMZKU7qo4FOn0grg.png" /></figure><p>Sağlıklı bir şekilde çalıştığını gördük. Şimdi son olarak<strong> HDFS</strong> tarafındaki kontrolümüzü yaparak senaryomuzu tamamlamış olacağız.</p><pre>hdfs dfs -ls /topics/order-topic/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akU4MH06UcgrFKE81f8gyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0M-xjBH-kbgTrMBm_Jpgw.png" /></figure><p><strong>HDFS </strong>tarafına baktığımızda istediğimiz gibi <strong>State</strong> kolonunu dikkate alarak verileri ayırmış ve <strong>parquet </strong>formatında kaydetmiş.</p><p>Umarım faydalı bir yazı olmuştur. Sorularınız ve önerileriniz için benimle iletişime geçebilirsiniz. Teşekkürler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12b3c7d4789" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentego-teknoloji/kafka-connect-ile-hdfse-veri-g%C3%B6nderme-i%CC%87%C5%9Flemi-c12b3c7d4789">Kafka Connect ile HDFS’e Veri Gönderme İşlemi</a> was originally published in <a href="https://medium.com/bentego-teknoloji">Bentego Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure üzerinde Data Pipeline Oluşturma]]></title>
            <link>https://medium.com/bentego-teknoloji/azure-%C3%BCzerinde-data-pipeline-olu%C5%9Fturma-1f644f21455b?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f644f21455b</guid>
            <category><![CDATA[azure-data-lake]]></category>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[azure-data-engineer]]></category>
            <category><![CDATA[azure-sql-database]]></category>
            <category><![CDATA[azure-synapse-analytics]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Tue, 30 May 2023 05:57:16 GMT</pubDate>
            <atom:updated>2023-05-30T08:24:25.647Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar bu yazımda sizlere Bulut Servis Sağlayıcılarından olan <strong>Azure</strong> üzerinde bir <strong>Data Pipeline</strong> oluşturma sürecini anlatacağım. Gelin isterseniz ilk önce projemizin mimarisine bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5P8E-uh4BIKhoFiYVzL6lA.png" /></figure><p>Mimarimiz yukarıda görmüş olduğunuz gibidir. Veri akışı anlatımına geçmeden önce <strong>Azure</strong> üzerinde kullandığımız servisleri kısaca bir tanıyalım.</p><p><strong>Azure Resource Group → Microsoft Azure</strong> bulut platformunda kaynaklarınızı yönetmek için kullanılan bir yapıdır. <strong>Azure</strong>’da oluşturduğunuz kaynakları, sanal makineleri, depolama hesaplarını, ağ yapılandırmalarını, uygulamaları ve diğer hizmetleri mantıksal bir grup içinde toplamanızı sağlar.</p><p><strong>Azure Data Factory → Microsoft Azure</strong> bulut platformunda veri entegrasyonu ve veri işleme işlerini otomatikleştirmek için kullanılan bir hizmettir. <strong>Azure Data Factory</strong>, farklı veri kaynakları arasında<strong> veri hareketini</strong>, <strong>dönüşümünü</strong> ve <strong>işlenmesini</strong> sağlayarak<strong> veri entegrasyonunu</strong> kolaylaştırır.</p><p><strong>Azure Synapse Analytics → Microsoft Azure</strong> bulut platformunda, <strong>verilerinizi analiz etmek, işlemek ve raporlamak</strong> için kullanabileceğiniz güçlü bir veri analitiği çözümüdür.<strong>Azure Synapse Analytics</strong>, veri ambarı, veri entegrasyonu, veri sorgulama ve<strong> büyük veri analitiği</strong> gibi işlemleri<strong> tek bir platformda</strong> birleştirir.</p><p><strong>Azure Data Lake → </strong>Büyük veri depolama ve analizi için kullanılan bir hizmettir. <strong>Azure</strong> bulut platformunda,<strong> yapılandırılmış</strong> ve<strong> yapılandırılmamış</strong> büyük veri kütlelerini <strong>güvenli ve ölçeklenebilir</strong> bir şekilde <strong>depolamak</strong> için kullanılır.</p><p><strong>Azure SQL Database → Microsoft Azure</strong> bulut platformunda barındırılan ilişkisel veritabanı hizmetidir. Geleneksel<strong> SQL Server</strong> veritabanının<strong> bulut tabanlı bir sürümü</strong> olarak düşünülebilir.</p><p>Mimariye baktığımızda ilk kısımda <strong>On-Premise</strong> tarafta gerçekleşen işlemlerimiz mevcut. Gelin isterseniz ilk olarak lokalimizde çalışan python koduna ve çıktısına bir bakalım.</p><pre>import spotipy<br>from spotipy.oauth2 import SpotifyClientCredentials<br>import pandas as pd<br>from datetime import date<br>import configparser<br><br>parser = configparser.ConfigParser()<br>parser.read(&quot;conf.ini&quot;)<br><br><br><br>client_credentials_manager = SpotifyClientCredentials(<br>    client_id = parser.get(&quot;credentials&quot;,&quot;CLIENT_ID&quot;),<br>    client_secret = parser.get(&quot;credentials&quot;, &quot;CLIENT_SECRET&quot;)<br>)<br><br>sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)<br><br>playlist_link = &#39;https://open.spotify.com/playlist/37i9dQZF1EIWxkuBxGv3mp&#39;<br><br>playlist_URI = playlist_link.split(&quot;/&quot;)[-1]<br>data = sp.playlist_tracks(playlist_URI)<br>date_str = str(date.today())<br><br>album_list = []<br><br>for row in data[&quot;items&quot;]:<br>    album_id = row[&quot;track&quot;][&quot;album&quot;][&quot;id&quot;]<br>    album_name = row[&quot;track&quot;][&quot;album&quot;][&quot;name&quot;]<br>    album_release_date = row[&quot;track&quot;][&quot;album&quot;][&quot;release_date&quot;]<br>    album_total_tracks = row[&quot;track&quot;][&quot;album&quot;][&quot;total_tracks&quot;]<br>    album_url = row[&quot;track&quot;][&quot;album&quot;][&quot;external_urls&quot;][&quot;spotify&quot;]<br>    album_element = {<br>        &quot;album_id&quot;: album_id,<br>        &quot;name&quot;: album_name,<br>        &quot;album_release_date&quot;: album_release_date,<br>        &quot;album_total_tracks&quot;: album_total_tracks,<br>        &quot;album_url&quot;: album_url<br>                     }<br>    album_list.append(album_element)<br><br>artist_list = []<br><br>for row in data[&quot;items&quot;]:<br>    for key, value in row.items():<br>        if key == &quot;track&quot;:<br>            for artist in value[&quot;artists&quot;]:<br>                artist_dict = {<br>                    &quot;artist_id&quot;: artist[&quot;id&quot;],<br>                    &quot;artist_name&quot;: artist[&quot;name&quot;],<br>                    &quot;external_url&quot;: artist[&quot;href&quot;]<br>                }<br>                artist_list.append(artist_dict)<br><br>song_list = []<br><br>for row in data[&quot;items&quot;]:<br>    song_id = row[&quot;track&quot;][&quot;id&quot;]<br>    song_name = row[&quot;track&quot;][&quot;name&quot;]<br>    song_duration = row[&quot;track&quot;][&quot;duration_ms&quot;]<br>    song_url = row[&quot;track&quot;][&quot;external_urls&quot;][&quot;spotify&quot;]<br>    song_popularity = row[&quot;track&quot;][&quot;popularity&quot;]<br>    song_added = row[&quot;added_at&quot;]<br>    album_id = row[&quot;track&quot;][&quot;album&quot;][&quot;id&quot;]<br>    artist_id = row[&quot;track&quot;][&quot;album&quot;][&quot;artists&quot;][0][&quot;id&quot;]<br>    song_element = {<br>        &quot;song_id&quot;: song_id,<br>        &quot;song_name&quot;: song_name,<br>        &quot;duration_ms&quot;: song_duration,<br>        &quot;url&quot;: song_url,<br>        &quot;popularity&quot;: song_popularity,<br>        &quot;song_added&quot;: song_added,<br>        &quot;album_id&quot;: album_id,<br>        &quot;artist_id&quot;: artist_id<br>    }<br>    song_list.append(song_element)<br><br>album_df = pd.DataFrame.from_dict(album_list)<br>album_df = album_df.drop_duplicates(subset = [&quot;album_id&quot;])<br><br>artist_df = pd.DataFrame.from_dict(artist_list)<br>artist_df = artist_df.drop_duplicates(subset = [&quot;artist_id&quot;])<br><br>song_df = pd.DataFrame.from_dict(song_list)<br>album_df[&quot;release_date&quot;] = pd.to_datetime(album_df[&quot;album_release_date&quot;])<br>song_df[&quot;song_added&quot;] = pd.to_datetime(song_df[&quot;song_added&quot;])<br><br>song_df.to_parquet(f&quot;data\\{date_str}_song_ds.parquet&quot;,engine=&quot;fastparquet&quot;)<br>album_df.to_parquet(f&quot;data\\{date_str}_album_ds.parquet&quot;,engine=&quot;fastparquet&quot;)<br>artist_df.to_parquet(f&quot;data\\{date_str}_artist_ds.parquet&quot;,engine=&quot;fastparquet&quot;)</pre><pre>conf.ini<br>[credentials]<br>CLIENT_ID = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX<br>CLIENT_SECRET = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*H_UxtPvGdTGTN14Vi3nOwg.png" /></figure><p>Görmüş olduğunuz <strong>Python</strong> kodu <strong>Spotify API</strong>’na istekte bulunarak dönen sonuçtan 3 farklı veri seti elde ederek bunları <strong>parquet </strong>formatında belirtilen dizine kaydediyor.</p><p>Evet lokalimizdeki işlemleri böylelikle bitiyoruz. Şimdi <strong>Azure </strong>üzerindeki servislerimizi oluşturarak işlemlerimize devam edelim.</p><p><strong>Resource Group</strong> Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8He4AbwUII1F1yMXF7pOJw.png" /></figure><p><strong>Azure Data Lake</strong> Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*xB-lVd6HTUSfK_8vJpPr8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*YIp9voASTPcanzvyCHveiw.png" /></figure><p><strong>Azure Data Factory </strong>Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*4OMx4YLapUrdoR8Zot4kSA.png" /></figure><p><strong>Azure Synapse Analytics </strong>Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*TCHOUTfB_S9ccj3WeHZNnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*3SWNho0Q9KxykNTcNUd2Wg.png" /></figure><p><strong>Azure SQL Database </strong>Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*xKbbvi_J2TzGvMKXsHVoVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*BB7pXpH1EUKyagVnIojvZQ.png" /></figure><p>Gerekli servisleri oluşturduğumuza göre <strong>Azure Data Factory Studio </strong>ekranına giderek <strong>Manage</strong> sekmesinden <strong>Integration Runtimes(IR)</strong> kısmına gelerek lokalimizle bağlantı sağlayacak yeni bir tanesini oluşturacağız.</p><p><strong>Self-Hosted IR</strong> Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uv99elh3b2lCsh9xPF6fVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*78aNh3npqhOWwSEzk-zVrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*h2vReC5D0O2zfhCwe-LvIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*GjxhLHTxtfVGsNmPAXPDow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*teBErOXKVtLzPkG9Nw353g.png" /></figure><p><strong>Option 2</strong>&#39;deki link’e tıklayarak indirme işlemini gerçekleştiriyoruz. İşlem bittikten sonra çıkacak ekrana <strong>Key1</strong>&#39;i kopyalayarak ilgili alana yapıştırıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*XLQr_qa9OVe8-XycIYT2wA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*oza8oqksX6vy6K71oKlAvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QK2qd2fjpedOf62jlvAvRA.png" /></figure><p>Başarılı bir şekilde lokalimiz ile bağlantı sağlayacak ve ilgili işlemleri orada gerçekleştirecek olan <strong>IR</strong>’ı oluşturmuş olduk.</p><p><strong>Data Factory</strong> üzerinde oluşturacağımız Pipeline da lokalimizde ki parquet dosyalarını kullanabilmek için<strong> Linked Service</strong> oluşturacağız onu da aşağıdaki adımları takip ederek oluşturabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*0SnHnnpTyeAFHdIFiUcisQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*xpOUhN1P9pwohR8UTlA2Lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*KGYK6kgqsvo-vsZeQ42UiA.png" /></figure><p>Oluşturacağımız Data Pipeline içerisinde bu <strong>LS(Linked Service)’i </strong>kullanarak lokal’deki her bir parquet formatı eğer bugünün tarihi ile başlıyorsa onu alarak <strong>Azure Data Lake</strong>’deki belirttiğimiz dizine kopyalayacak.</p><p><strong>DP_Extract_OnpremToADL2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKJN0-gB4O6Lbv_SCFayuQ.png" /></figure><p>Yukarıda görmüş olduğunuz <strong>Data Pipelin</strong>e’ı açıklamak gerekirse yaptığı iş <strong>Get Metadata</strong>’yı kullanarak lokal’deki her <strong>parquet </strong>dosyasının dosya ismini <strong>ForEach Loop</strong>’unda döndürek eğer bugünün tarihiyle başlıyorsa kopyalama işlemini gerçekleştirecek eğer değilse hiçbir işlem yapmayacak.Bu kontrolü yapan Activity <strong>‘If Condition’ </strong>ve koşulu yapan kod ise aşağıdaki gibidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*AgXLljZQHSk0TggJTxu9Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aVinaN8N_mTU0VYdMQBog.png" /></figure><p>Data Pipeline’ı çalıştırdığımızda başarılı bir şekilde çalıştığını görmekteyiz. <strong>Azure Data Lake</strong> üzerindeki belirttiğimiz dizini kontrol ederek veriler başarılı şekilde gelmiş mi şimdi ona bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nET4rlIQE4JvEtJoWECnbA.png" /></figure><p>Lokalimizdeki veri setlerinin başarılı şekilde kopyalandığı görmekteyiz.</p><p>Bir sonraki aşamamız <strong>Azure Synapse Analytics</strong> üzerinde <strong>Spark Pool</strong> oluşturarak veri temizleme ve dönüştürme işlemi uygulayacağız.</p><p><strong>Spark Pool</strong> Oluşturma İşlemi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuJstL2qptYGIteyrJ9ceg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU2DF6wi5nMfX-kStVtlgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oq_ZXEN6RWab9gtKp779iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nEb36z936EiJoG8MMX76g.png" /></figure><pre>from notebookutils import mssparkutils<br>from pyspark.sql.functions import *<br>from pyspark.sql.types import *<br><br>accountname=&quot;bentegostg&quot;<br>sourcecontainer=&quot;raw&quot;<br>LinkedService=&quot;bentego-synapse-ws-WorkspaceDefaultStorage&quot;<br>sourceFile_location=&quot;ingest&quot;<br>destinationcontainer=&quot;refined&quot;<br><br>spark.conf.set(&quot;spark.storage.synapse.linkedServiceName&quot;,LinkedService)<br>spark.conf.set(&quot;fs.azure.account.oauth.provider.typ&quot;,&quot;com.microsoft.azure.synapse.tokenlibrary.LinkedServiceBasedTokenProvider&quot;)<br>spark.conf.set(&quot;spark.sql.parquet.writeLegacyFormat&quot;,&quot;true&quot;)<br><br>SongCustomSchema = StructType([<br>        StructField(&quot;song_id&quot;, StringType(), True),<br>        StructField(&quot;song_name&quot;, StringType(), True),<br>        StructField(&quot;duration_ms&quot;, LongType(), True),<br>        StructField(&quot;url&quot;, StringType(), True),<br>        StructField(&quot;popularity&quot;, LongType(), True),<br>        StructField(&quot;song_added&quot;, StringType(), True),<br>        StructField(&quot;album_id&quot;, StringType(), True),<br>        StructField(&quot;artist_id&quot;, StringType(), True)<br>        ]<br>        )<br><br>song_df = spark \<br>        .read \<br>        .schema(SongCustomSchema) \<br>        .parquet(f&quot;abfss://{sourcecontainer}@{accountname}.dfs.core.windows.net/{sourceFile_location}/2023-05-29_song_ds.parquet&quot;)<br><br><br>song_df = song_df \<br>          .withColumn(&quot;duration_ms&quot;,col(&quot;duration_ms&quot;).cast(IntegerType())) \<br>          .withColumn(&quot;popularity&quot;,col(&quot;popularity&quot;).cast(IntegerType())) \<br>          .drop(col(&quot;song_added&quot;))    <br><br><br>AlbumCustomSchema = StructType([<br>        StructField(&quot;album_id&quot;, StringType(), True),<br>        StructField(&quot;name&quot;, StringType(), True),<br>        StructField(&quot;album_release_date&quot;, StringType(), True),<br>        StructField(&quot;album_total_tracks&quot;, LongType(), True),<br>        StructField(&quot;album_url&quot;, StringType(), True),<br>        StructField(&quot;release_date&quot;, StringType(), True)<br>        ]<br>        )<br><br>album_df = spark \<br>        .read \<br>        .schema(AlbumCustomSchema) \<br>        .parquet(f&quot;abfss://{sourcecontainer}@{accountname}.dfs.core.windows.net/{sourceFile_location}/2023-05-29_album_ds.parquet&quot;)<br><br><br>album_df = album_df \<br>            .withColumn(&quot;album_total_tracks&quot;,col(&quot;album_total_tracks&quot;).cast(IntegerType())) \<br>            .withColumn(&quot;album_release_date&quot;,to_date(col(&quot;album_release_date&quot;),&quot;yyyy-MM-dd&quot;)) \<br>            .drop(&quot;release_date&quot;)<br><br><br>ArtistCustomSchema = StructType([<br>        StructField(&quot;artist_id&quot;, StringType(), True),<br>        StructField(&quot;artist_name&quot;, StringType(), True),<br>        StructField(&quot;external_url&quot;, StringType(), True),<br>        ]<br>        )<br><br><br>artist_df = spark \<br>        .read \<br>        .schema(ArtistCustomSchema) \<br>        .parquet(f&quot;abfss://{sourcecontainer}@{accountname}.dfs.core.windows.net/{sourceFile_location}/2023-05-29_artist_ds.parquet&quot;)<br><br><br>album_df.write \<br>        .mode(&quot;overwrite&quot;) \<br>        .format(&quot;parquet&quot;) \<br>        .option(&quot;header&quot;,&quot;true&quot;) \<br>        .option(&quot;inferSchema&quot;,&quot;true&quot;) \<br>        .save(f&quot;abfss://{destinationcontainer}@{accountname}.dfs.core.windows.net/album/&quot;)<br><br><br>artist_df.write \<br>        .mode(&quot;overwrite&quot;) \<br>        .format(&quot;parquet&quot;) \<br>        .option(&quot;header&quot;,&quot;true&quot;) \<br>        .option(&quot;inferSchema&quot;,&quot;true&quot;) \<br>        .save(f&quot;abfss://{destinationcontainer}@{accountname}.dfs.core.windows.net/artist/&quot;)</pre><p><strong>Spark Pool</strong>’u oluşturduktan sonra <strong>Developer</strong> sekmesinden <strong>Notebook</strong> oluşturarak yukarıdaki görmüş olduğunuz kodları yazıyoruz. Normal <strong>PySpark </strong>kodlarımızı yazarak verinin düzgün ve temizlenmiş halini yine Azure Data Lake üzerindeki belirtiğimiz dizinlere yolluyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39N8ysmt7feQwyJ5V0fxDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbXtnUXGfKEb53uYp6J6GA.png" /></figure><p>Kontrol ettiğimizde verilerin başarılı şekilde dizinlere yazıldığını görmekteyiz.</p><p>Yukarıda oluşturduğumuz Notebook’u <strong>Data Factory </strong>üzerinde oluşturduğumuz Data Pipeline içerisinden çağırmak için <strong>Azure Data Factory’</strong>i servisine <strong>Synapse Administrator</strong> yetkisi vermemiz gerekli.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49enApMU9bNgnLjt50o99A.png" /></figure><p>Şimdi <strong>Azure Data Factory</strong> kısmına gidirek<strong> Synapse</strong> kısmında oluşturduğumuz Notebook’u bağlanabilmesi için yeni bir <strong>Linked Service</strong> oluşturalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VriGQ6qGw3nLwjd6qKT2BA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*-F2Q6NTzoozfpgEf-kBChA.png" /></figure><p>Başarılı şekilde bağlantımızı oluşturduk. Data Pipeline oluştururak Notebook’u birde oradan çağıralım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5ln2q2IS_sXV-7GK5348w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5AdNLLvh_E52rgF4fkjMQ.png" /></figure><p>Data Pipeline’ı çalıştırdığımızda başarılı bir şekilde çalıştığını görmekteyiz.</p><p>Çalışan <strong>Pyspark Job</strong>’ımız temizlenmiş ve dönüştürülmüş veriyi başka bir dizine kaydetmiş oldu. Bu veri setlerini şimdi de <strong>Azure SQL Database</strong> kısmında oluşturduğumuz SpotifyDB’sinin altında tablolar oluşturarak oraya aktaracağız. <strong>Data Factory</strong> servisinin <strong>Azure SQL Database</strong> servisine erişebilmesi için aşağıdaki ayarı yapmalısınız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqixhxVVChB9h3woiEyRQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*NGH5vRM1_lyGX24T1kn-jw.png" /></figure><p>Başarılı şekilde bağlantıyı sağlamış olduk. Şimdi Azure SQL Database aktarım işlemini gerçekleştirecek olan Data Pipeline’ı oluşturabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IasbAB6XMCUpAbxl43bIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*OflbjbQH_30dCiRL4qck_w.png" /></figure><p>Oluşturduğumuz Data Pipeline yukarıdaki gibidir ve çalıştırdığımızda da hata almadan işlemi gerçekleştirdiğini görmekteyiz. Gelin bir de ilgili DB’miz altında tablolar oluşmuş mu ona bir bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QL0f3_NXqTNeeMvng6nOQ.png" /></figure><p>Evet istediğimiz tablolar başarılı bir şekilde oluşmuş ve içerisindeki veriler istediğimiz şekilde ve tipte gelmiş gözüküyor.</p><p>Umarım sizler için faydalı bir yazı olmuştur. Herhangi bir sorunuz veya öneriniz var ise benimle iletişime geçebilirsiniz. Teşekkürler, görüşmek üzere 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f644f21455b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentego-teknoloji/azure-%C3%BCzerinde-data-pipeline-olu%C5%9Fturma-1f644f21455b">Azure üzerinde Data Pipeline Oluşturma</a> was originally published in <a href="https://medium.com/bentego-teknoloji">Bentego Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DE- Örnek Proje 2]]></title>
            <link>https://emreevcimen.medium.com/de-%C3%B6rnek-proje-2-7f561efdf0ac?source=rss-7b35c26c88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f561efdf0ac</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[metabase]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Emre Evcimen]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 12:13:51 GMT</pubDate>
            <atom:updated>2023-04-05T12:29:44.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar daha öncesinde <a href="https://medium.com/p/6e02a948ba3a">DE- Örnek Proje 1</a> başlıklı yazımda sizlere veri mühendisliği alanında yapılabilecek örnek bir projeyi anlatmıştım. Bu yazımda da başka bir örnek projeyi ele alacağım. Proje’nin genel tanımını yapmadan önce görsel mimariyi aşağıda paylaşıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*9RAgrgUgWk14yeyGP_u7Lw.png" /></figure><p><strong>Proje Tanımı: </strong>Spark ile lokalimizde bulunan kompleks<strong>(Örn: bir kolonda sözlük yapısında birden fazla verinin bulunması vb.)</strong> yapıdaki parquet formatındaki veriy<strong>i Spark</strong> ile birden fazla veri setine ayırarak bu veri setlerini <strong>PostgreSQ</strong>L’e yazmak. Daha sonrasında <strong>DBT </strong>aracını kullanarak <strong>stg(staging)</strong> ve<strong> rpt(report)</strong> katmanları oluşturarak veriyi görselleştirilecek hale getirmek(<strong>Veri Modelleme</strong>) ve bunu <strong>Airflow</strong> aracı ile otomasyonunu sağlamak. Son olarak da <strong>Metabase </strong>üzerinde örnek görselleştirmeler hazırlayacağız.</p><p>İlk olarak gelin kısaca veri setlerine bir bakalım.</p><blockquote><strong>Not: </strong>parq komutunu kullanmak için <strong>pip install parquet-cli</strong> komutunu çalıştırmalısınız.</blockquote><p><strong>tmdb_5000_credits.parquet:</strong></p><pre>parq tmdb_5000_credits.parquet <br>Output:<br> # Metadata <br> &lt;pyarrow._parquet.FileMetaData object at 0x7fa9bd123db0&gt;<br>  created_by: parquet-cpp-arrow version 10.0.0<br>  num_columns: 4<br>  num_rows: 4803<br>  num_row_groups: 1<br>  format_version: 2.6<br>  serialized_size: 2763</pre><p><strong>tmdb_5000_credits.parquet:</strong></p><pre> parq tmdb_5000_movies.parquet <br> Output:<br> # Metadata <br> &lt;pyarrow._parquet.FileMetaData object at 0x7f33dff08720&gt;<br>  created_by: parquet-cpp-arrow version 10.0.0<br>  num_columns: 20<br>  num_rows: 4803<br>  num_row_groups: 1<br>  format_version: 2.6<br>  serialized_size: 11311</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMKls40bQWUhx7j8Waf8eg.png" /></figure><p><strong>tmdb_5000_credits.parquet</strong> dosyasındaki baştan ilk 3 satıra baktığımızda dikkatimizi çekmesi gereken kolonlar <strong>cast</strong> ve <strong>crew</strong>. Görmüş olduğuz gibi liste içerisinde birden fazla sözlük veri tipinde değer içeriyorlar. Aslında bu iki kolon işlenerek farklı veri setleri haline getirilmesi gerekiyor. Aksi halde görselleştirme ve sorgulama konusunda son kullanıcı için verimsiz bir halde bulunmuş olacaklar. Aynı şekilde <strong>tmdb_5000_movies.parquet</strong> dosyasındaki kolonlara bakacak olursak yukarıdaki duruma benzer bir çok kolon mevcut olduğunu görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giVsrTw0-dICNthzRya1IQ.png" /></figure><p>Burada <strong>Apache Spark </strong>kullanarak ilgili kısımları farklı veri setlerine ayırarak<strong> PostgreSQL’</strong>de depolayacağız. <strong>Spark</strong> tarafında bu işlemi gerçekleştirmek için yazdığım kodu aşağıda paylaşıyorum.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, explode_outer, from_json, to_date<br>from pyspark.sql.types import ArrayType, StructField, StructType, IntegerType, StringType, FloatType, DoubleType <br><br>spark = SparkSession \<br>             .builder \<br>             .master(&quot;yarn&quot;) \<br>             .appName(&quot;tmdb-app&quot;) \<br>             .config(&quot;spark.jars.packages&quot;, &quot;org.postgresql:postgresql:42.2.18&quot;) \<br>             .getOrCreate()<br><br>url = &quot;jdbc:postgresql://localhost:5432/tmdb&quot;<br><br>properties = {<br>    &quot;user&quot;: &quot;postgres&quot;,<br>    &quot;password&quot;: &quot;*****&quot;<br>}<br><br>write_database_df = []<br><br>table_names = [&quot;raw_cast&quot;,&quot;raw_crew&quot;,&quot;raw_movies&quot;,&quot;raw_genres&quot;,&quot;raw_keywords&quot;,&quot;raw_production_companies&quot;,<br>                &quot;raw_production_countries&quot;,&quot;raw_spoken_languages&quot;]<br><br>df_credits = spark \<br>                .read \<br>                .parquet(&quot;file:///home/emre/Desktop/medium_dp/spark/tmdb_5000_credits.parquet&quot;)<br><br><br><br>cast_column_schema = (<br>    ArrayType(<br>        StructType([<br>            StructField(&quot;cast_id&quot;, IntegerType()),<br>            StructField(&quot;character&quot;, StringType()),<br>            StructField(&quot;credit_id&quot;, StringType()),<br>            StructField(&quot;gender&quot;, IntegerType()),<br>            StructField(&quot;id&quot;, IntegerType()),<br>            StructField(&quot;name&quot;, StringType()),<br>            StructField(&quot;order&quot;, IntegerType())<br>                  ])<br>            )<br>         )<br><br>crew_column_schema = (ArrayType(<br>        StructType([<br>            StructField(&quot;credit_id&quot;, StringType()),<br>            StructField(&quot;department&quot;, StringType()),<br>            StructField(&quot;gender&quot;, IntegerType()),<br>            StructField(&quot;id&quot;, IntegerType()),<br>            StructField(&quot;job&quot;, StringType()),<br>            StructField(&quot;name&quot;, StringType())<br>                  ])<br>            )<br>         )<br><br><br>df_credits_nested= df_credits \<br>                     .withColumn(&quot;cast&quot;, from_json(col(&quot;cast&quot;), cast_column_schema)) \<br>                     .withColumn(&quot;crew&quot;, from_json(col(&quot;crew&quot;), crew_column_schema))<br><br><br>cast_df = df_credits_nested \<br>            .select(&quot;movie_id&quot;, &quot;title&quot;, explode_outer(&quot;cast&quot;)) \<br>            .select(&quot;movie_id&quot;,&quot;title&quot;, &quot;col.*&quot;)<br><br>cast_df = cast_df \<br>    .withColumn(&quot;movie_id&quot;,col(&quot;movie_id&quot;).cast(IntegerType())) <br><br>write_database_df.append(cast_df)<br><br><br><br><br>crew_df = df_credits_nested \<br>             .select(&quot;movie_id&quot;, &quot;title&quot;, explode_outer(&quot;crew&quot;)) \<br>             .select(&quot;movie_id&quot;, &quot;title&quot;, &quot;col.*&quot;)<br><br>crew_df = crew_df.withColumn(&quot;movie_id&quot;, col(&quot;movie_id&quot;).cast(IntegerType()))<br><br>write_database_df.append(crew_df)<br><br><br><br>df_movies = spark \<br>               .read \<br>               .parquet(&quot;file:///home/emre/Desktop/medium_dp/spark/tmdb_5000_movies.parquet&quot;)<br><br><br>df_movies_lst = df_movies \<br>               .select(&quot;id&quot;,&quot;title&quot;, &quot;budget&quot;, &quot;homepage&quot;, &quot;original_language&quot;, &quot;original_title&quot;,  \<br>                       &quot;overview&quot;, &quot;popularity&quot;, &quot;release_date&quot;, &quot;revenue&quot;, &quot;runtime&quot;, &quot;status&quot;, \<br>                       &quot;tagline&quot;, &quot;vote_average&quot;, &quot;vote_count&quot;) \<br>                .withColumnRenamed(&quot;id&quot;, &quot;movie_id&quot;)<br><br><br>movies_df = df_movies_lst.withColumn(&quot;movie_id&quot;, col(&quot;movie_id&quot;).cast(IntegerType())) \<br>                         .withColumn(&quot;budget&quot;, col(&quot;budget&quot;).cast(DoubleType())) \<br>                         .withColumn(&quot;popularity&quot;, col(&quot;popularity&quot;).cast(FloatType())) \<br>                         .withColumn(&quot;release_date&quot;, to_date(&quot;release_date&quot;, &quot;yyyy-MM-dd&quot;)) \<br>                         .withColumn(&quot;revenue&quot;, col(&quot;revenue&quot;).cast(DoubleType())) \<br>                         .withColumn(&quot;runtime&quot;, col(&quot;runtime&quot;).cast(IntegerType())) \<br>                         .withColumn(&quot;vote_average&quot;, col(&quot;vote_average&quot;).cast(FloatType())) \<br>                         .withColumn(&quot;vote_count&quot;,  col(&quot;vote_count&quot;).cast(IntegerType()))<br><br>write_database_df.append(movies_df)<br><br><br><br>column_schema = (ArrayType(<br>        StructType([<br>            StructField(&quot;id&quot;, IntegerType()),<br>            StructField(&quot;name&quot;, StringType()),<br>                  ])<br>            ) )<br><br>specific_column = [&quot;genres&quot;,&quot;keywords&quot;,&quot;production_companies&quot;]<br><br><br>for cols in specific_column:<br>    specific_clmn_df = df_movies \<br>                  .withColumnRenamed(&quot;id&quot;,&quot;movie_id&quot;)  \<br>                  .withColumn(&quot;movie_id&quot;, col(&quot;movie_id&quot;).cast(IntegerType())) \<br>                  .withColumn(cols, from_json(col(cols), column_schema)) \<br>                  .select(&quot;movie_id&quot;, explode_outer(cols)) \<br>                  .select(&quot;movie_id&quot;,&quot;col.*&quot;)<br>    globals()[cols + &quot;_df&quot;] = specific_clmn_df<br>    write_database_df.append(globals()[cols + &quot;_df&quot;])<br><br><br>for cols in [&quot;production_countries&quot;, &quot;spoken_languages&quot;]:<br>    ps_df_movies_raw = df_movies.select(&quot;id&quot;,cols).withColumnRenamed(&quot;id&quot;, &quot;movie_id&quot;) <br>    if cols == &quot;production_countries&quot; :<br>        iso_col = &quot;iso_3166_1&quot;<br>    else :<br>        iso_col = &quot;iso_639_1&quot;<br>    schema = (<br>    ArrayType(<br>        StructType([<br>            StructField(iso_col, StringType()),<br>            StructField(&quot;name&quot;, StringType()),<br>                  ])<br>            )<br>         )<br>    ps_df_movies_raw = ps_df_movies_raw.withColumn(cols, from_json(cols, schema))<br>    ps_df = ps_df_movies_raw.select(&quot;movie_id&quot;, explode_outer(cols)).select(&quot;movie_id&quot;,f&quot;col.{iso_col}&quot;,&quot;col.name&quot;).withColumn(&quot;movie_id&quot;, col(&quot;movie_id&quot;).cast(IntegerType()))<br>    globals()[cols + &quot;_df&quot;]= ps_df<br>    write_database_df.append(globals()[cols + &quot;_df&quot;])<br><br>for num , tbls in enumerate(write_database_df):<br>      tbls.write.jdbc(   url=url, <br>                         table=f&quot;{table_names[num]}&quot;, <br>                         mode=&quot;overwrite&quot;, <br>                         properties=properties<br>      )</pre><p>Yazmış olduğum <strong>Spark</strong> kodu yukarıda bahsettiğim veri setlerini okuyarak belirttiğimiz kolonlara işlem uygulayıp birden fazla veri seti oluşturup ortayan çıkan <strong>Spark DataFrame</strong>’leri sırasıyla<strong> PostgreSQL</strong>’e yazıyor. <strong>Spark</strong> kodunu detaylı olarak açıklamayacağım ancak sizin kod kısmında kafanıza takılan veya bir öneriniz olması halinde benimle iletişime geçebilirsiniz. En son <strong>PostgreSQL</strong>’e yazılacak tabloların isimlerini ve yapılarını aşağıda paylaşıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhIqE7eWZdqyT2tbYFhoIA.png" /></figure><p>Görmüş olduğunuz gibi elimizde <strong>2 adet veri set</strong>i varken Spark kodumuzu başarılı şekilde çalıştırdıktan sonra <strong>8 adet tablo </strong>ortaya çıkarmış olduk.</p><p>Şimdi <strong>DBT</strong> tarafına geçip orada nasıl işlemler gerçekleştirmişim ona bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*apuk2mrWcmaq_BLXucPpuQ.png" /></figure><p>Basit bir <strong>DBT</strong> Proje yapısı yukarıdaki gibidir. Bu proje özelinde daha çok işlem gerçekleştirdiğim kısımlarıda kırmızı kutucuk içerisinde belirttim. Models dosyasını içerisinde <strong>Spark</strong> ile <strong>PostgreSQL</strong>’e ilettiğimiz tabloları okuyup yine <strong>PostgreSQL</strong> içerisinde <strong>dbt_stg </strong>ve<strong> dbt_rpt </strong>şemaları altında görselleştirme ve modellemeye daha uygun hallere getirmek için veri dönüştürme işlemleri gerçekleştirip verileri ilgili şema altına öyle depoluyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*KIS4k4iEJKSNht2BqCs87Q.png" /></figure><p>Yukarıda gördüğünüz gibi iki katman içinde farklı dosya path’leri oluşturdum. Gelin iki katmandan da örnek <strong>sql</strong> ve <strong>yml</strong> dosyalarına bir bakalım.</p><p><strong>dbt_project.yml:</strong></p><pre><br># Name your project! Project names should contain only lowercase characters<br># and underscores. A good package name should reflect your organization&#39;s<br># name or the intended use of these models<br>name: &#39;tmdb_dbt&#39;<br>version: &#39;1.0.0&#39;<br>config-version: 2<br><br># This setting configures which &quot;profile&quot; dbt uses for this project.<br>profile: &#39;tmdb_dbt&#39;<br><br># These configurations specify where dbt should look for different types of files.<br># The `model-paths` config, for example, states that models in this project can be<br># found in the &quot;models/&quot; directory. You probably won&#39;t need to change these!<br>model-paths: [&quot;models&quot;]<br>analysis-paths: [&quot;analyses&quot;]<br>test-paths: [&quot;tests&quot;]<br>seed-paths: [&quot;seeds&quot;]<br>macro-paths: [&quot;macros&quot;]<br>snapshot-paths: [&quot;snapshots&quot;]<br><br>target-path: &quot;target&quot;  # directory which will store compiled SQL files<br>clean-targets:         # directories to be removed by `dbt clean`<br>  - &quot;target&quot;<br>  - &quot;dbt_packages&quot;<br><br><br># Configuring models<br># Full documentation: https://docs.getdbt.com/docs/configuring-models<br><br># In this example config, we tell dbt to build all models in the example/<br># directory as views. These settings can be overridden in the individual model<br># files using the `{{ config(...) }}` macro.<br>models:<br>  tmdb_dbt:<br>    # Config indicated by + and applies to all files under models/example/<br>    stg:<br>      +materialized: table<br>      +schema: stg<br>    reports:<br>      +materialized: table<br>      +schema: rpt</pre><p><strong>stg_movies.sql:</strong></p><pre>{{<br>  config(<br>    materialized = &#39;table&#39;,<br>    )<br>}}<br>select  movie_id,title,budget , original_language ,original_title, overview ,popularity ,release_date, <br>        revenue ,runtime, status, tagline ,vote_average ,vote_count  <br>from {{ source(&#39;tmdb&#39;, &#39;raw_movies&#39;) }}</pre><p><strong>stg_genres.sql:</strong></p><pre>{{<br>  config(<br>    materialized = &#39;table&#39;,<br>    )<br>}}<br>select movie_id ,coalesce(id,-9999) as id , name <br>from {{ source(&#39;tmdb&#39;, &#39;raw_genres&#39;) }}</pre><p><strong>stg_cast.sql:</strong></p><pre>{{<br>  config(<br>    materialized = &#39;table&#39;,<br>    )<br>}}<br>select movie_id, title, cast_id, &quot;character&quot; , <br>       coalesce(credit_id,&#39;0000000000&#39;) as credit_id ,<br>       gender, id, &quot;name&quot; <br>from {{source(&#39;tmdb&#39;,&#39;raw_cast&#39;)}}</pre><p>Yukarıda gördüğünüz gibi <strong>stg</strong> katmanına verileri göndermeden önce null değerlere sahip olan kolonları belirttiğim değerlerle doldurup ilgili katmana öyle iletiyorum. En başta gördüğünüz <strong>config</strong> içerisinde <strong>materialized</strong> değerini <strong>table</strong> olarak belirtmemizin sebebi <strong>PostgreSQL</strong> içerisinde bu işlemi tablo olarak kaydetmesini istiyoruz. <strong>Source </strong>kısmında belirttiğimiz değerlerede aslında <strong>sources.yml </strong>içerisinde bulunan bilgiler ışığında ulaşılıyor. <strong>sources.yml</strong> dosyasını da aşağıda paylaşıyorum.</p><p><strong>sources.yml</strong></p><pre>version: 2<br><br>sources:<br>  - name: tmdb<br>    database: tmdb<br>    schema: public<br>    tables:<br>      - name: raw_cast<br>      - name: raw_crew<br>      - name: raw_movies<br>      - name: raw_genres<br>      - name: raw_keywords<br>      - name: raw_production_companies<br>      - name: raw_production_countries<br>      - name: raw_spoken_languages</pre><p><strong>rpt_top3rvnByProductionCompany.sql:</strong></p><pre>{{<br>  config(<br>    materialized = &#39;table&#39;,<br>    )<br>}}<br><br>with rpt_top3rvnByProductionCompany as (<br>select sm.title ,sm.revenue,<br>       spc.name as production_company,ssl.&quot;name&quot; as spoken_language_name, <br>       row_number() over(partition by spc.name order by sm.revenue desc) as rank_<br>from {{ ref(&#39;stg_movies&#39;) }} sm <br>join {{ ref(&#39;stg_production_companies&#39;) }} spc <br>on sm.movie_id =spc.movie_id <br>join {{ ref(&#39;stg_spoken_languages&#39;) }} ssl  on sm.movie_id = ssl.movie_id <br>)<br>select * from rpt_top3rvnByProductionCompany <br>where rank_&lt;=3</pre><p>Rapor katmanında da <strong>stg</strong> aşamasında oluşturduğumuz tabloları referans göstererek son kullanıcı tarafından yaygın şekilde görüntülenen raporları bu katmanda tablo olarak oluşturuyoruz.</p><p><strong>DBT</strong> tarafını da bitererek artık mevcut verimizi görselleştirecek ve anlamlı değerlere ulaşılacak formata getiriyoruz. Ancak bu sürecin belirli aralıklarla sürekli çalışması gerektiğini düşünürsek bunu otomatize etmemiz gerekiyor. İşte burada da <strong>Airflow</strong> aracını kullanacağız. Bu süreci gerçekleştirmesi için oluşturduğum dag dosyasına aşağıda görebilirsiniz.</p><blockquote><strong>Not:</strong> Airflow üzerinde DBT Projenizi tetiklemek istiyorsanız <strong>pip install airflow-dbt </strong>komutunu çalıştırarak ilgili kütüphaneyi ilgili sanal ortamınıza import etmeniz gerekir.</blockquote><pre>from airflow import DAG<br>from datetime import datetime, timedelta<br>from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator<br>from airflow_dbt.operators.dbt_operator import (<br>     DbtRunOperator,<br>     DbtDocsGenerateOperator<br>)<br><br>default_args = {<br>    &quot;owner&quot;: &quot;emre&quot;,<br>    &quot;start_date&quot; : datetime(2023,4,4),<br>    &quot;schedule_interval&quot;: &quot;@daily&quot;,<br>    &quot;retries&quot;: 2,<br>    &quot;retry_delay&quot;: timedelta(minutes=1),<br>    &quot;tags&quot;: [&quot;data-engineer&quot;]<br>}<br><br>with DAG( dag_id = &quot;de-dbt-pipeline&quot;, <br>          catchup=False,<br>          default_args=default_args<br>        ) as dag:<br>    <br>     task_1 = SparkSubmitOperator(<br>                task_id = &quot;extract_data_with_spark&quot;,<br>                conn_id=&quot;my_spark3_conn&quot;,<br>                application=&quot;/home/emre/Desktop/medium_dp/spark/extract_data_spark.py&quot;<br>        )<br>     <br>     task_2 = DbtRunOperator(<br>          task_id = &quot;run_dbt_task&quot;,<br>          profiles_dir= &quot;/home/emre/.dbt/&quot;,<br>          dir = &quot;/home/emre/Desktop/medium_dp/tmdb_dbt/&quot;<br>                )<br>     <br>     task_3 = DbtDocsGenerateOperator(<br>          task_id = &quot;docs_dbt_task&quot;,<br>          profiles_dir= &quot;/home/emre/.dbt/&quot;,<br>          dir = &quot;/home/emre/Desktop/medium_dp/tmdb_dbt/&quot;<br>     )<br><br>task_1 &gt;&gt; task_2 &gt;&gt; task_3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*1eLvl9Sc7MKc9nZ6HpPQ6w.png" /></figure><p>Evet yukarıda görmüş olduğunuz gibi ilgili DAG’ımız başarılı şekilde çalıştı. Gelin isterseniz tablolar oluşmuş mu bir bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Awx2yEL_6IWu5O9ipKiJ_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*TK9G57OeJp7y1JO-2EAzLA.png" /></figure><p>Süper istediğimiz şemalar ve tablolar oluşturulmuş durumda. 👏🤗 Airflow tarafındaki DAG’a bakacak olursak son task’ta <strong>dbt docs</strong> komutunu çalıştıracak Operatörü(<strong>DbtDocsGenerateOperator</strong>) kullanmıştık. Bunun amacı evet biz <strong>.yml</strong> ve<strong> .sql </strong>uzantılı dosyaların içine bir şeyler karalıyoruz ama bunu biraz daha insanın anlayabileceği ve evet ya ben bunu yapmak istemiştim her şey yolunda gözüküyor diyebileceği bir Web UI ekranı sağlıyor. Bunu görüntülemek için aşağıdaki komutu çalıştırıyoruz ve o bize otomatik olarak bir Web UI ekranı çıkartıyor.</p><pre>(dbt-venv) emre@emre-lenovo:~/Desktop/medium_dp/tmdb_dbt$ dbt docs serve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RVS7vFQ4kh4m4zjyMso2g.png" /></figure><p>İlgili komutu çalıştırdıktan sonra Web UI bizi karşılıyor. Burada kırmızı okla belirttiğim yere tıklarsanız görsel olarak nasıl bir modelleme yaptığınız daha net olarak göreceksiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_1XM0-cC5u0yROw0C2AKw.png" /></figure><p>Harika işte ortaya çıkan modelimizin görselleşmiş hali burada ilgili tabloya tıklayarak hangi tablolardan beslendiğini ve modelin nasıl bir durumda olduğunu daha net olarak görüyoruz.</p><p>Tüm süreci tamamladığımıza göre artık <strong>Metabase </strong>kısmına geçerek örnek olması için birkaç görselleştirme yapalım.</p><pre>java -jar metabase.jar</pre><p>Yukarıdaki komutu çalıştırarak Metabase servisini başlatıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rp807MRI4606OPWACLfwzQ.png" /></figure><p>tmdb üzerindeki tablolara erişmesi için Veritabanı bağlantısını yukarıdaki bilgileri girerek oluşturuyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNVkplBGujKgs-NFX0OncA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBqZj7BHeWlJ4K4oprPHXQ.png" /></figure><p>Daha sonra ilgili tabloları kullanarak yukarıdaki gibi örnek görselleştirmeleri yaratabiliriz. İlk görselleştirmemizde <strong>aksiyon kategorisinde en uzun süreli olan 5 Filmi</strong> görüntülüyoruz. İkinci görselleştirmede ise <strong>Film Üretici Firması olan 1492 Pictures firmasının en çok gelir elde ettiği ilk 3 filmi Pie </strong>formatında gösteriyoruz.</p><p>Umarım faydalı bir yazı olmuştur. Geri dönüşleriniz olursa rahatlıkla iletebilirsiniz. Teşekkürler. Görüşmek üzere…👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f561efdf0ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>