<?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 Rajkumar k on Medium]]></title>
        <description><![CDATA[Stories by Rajkumar k on Medium]]></description>
        <link>https://medium.com/@krajkumar14?source=rss-6ae57b3a73f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pnESv1Jun1iAPR38</url>
            <title>Stories by Rajkumar k on Medium</title>
            <link>https://medium.com/@krajkumar14?source=rss-6ae57b3a73f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:08:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krajkumar14/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[A data engineering project on Google Cloud Platform utilizing Dataproc, BigQuery, Google Cloud…]]></title>
            <link>https://medium.com/@krajkumar14/a-data-engineering-project-on-google-cloud-platform-utilizing-dataproc-bigquery-google-cloud-295404e6cd8f?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/295404e6cd8f</guid>
            <category><![CDATA[google-cloud-storage]]></category>
            <category><![CDATA[dataproc]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 18:06:43 GMT</pubDate>
            <atom:updated>2025-09-15T18:06:43.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>A data engineering project on Google Cloud Platform utilizing Dataproc, BigQuery, Google Cloud Storage and Cloud Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*N6FF-WpV7fxVBd41flnBnw.png" /></figure><p><strong>Scenario:</strong></p><p>We have a use case where <strong>data needs to be processed on an ad hoc basis using Apache Spark</strong>. After each processing run, the data is <strong>loaded into BigQuery</strong> for storage and analytical purposes.</p><p>Following every load, the <strong>latest dataset is pulled from BigQuery</strong> and <strong>exported to a designated Cloud Storage bucket (GCS)</strong>. This exported data is then made available to <strong>end users for further analysis</strong>.</p><p><strong>Steps:</strong></p><p>Setup GCP Account<br>Activate Gcloud &amp; Create Service account<br>Create Bucket <br>Create Bigquery Dataset<br>Sample file preparation<br>Dataproc cluster creation<br>Run Spark Job &amp; Verify the data in BigQuery<br>Create &amp; Deploy Cloud Function<br>Verify the flow. — Run the Spark job and verify the bucket</p><ol><li><strong>Create Service Account &amp; Initiate gcloud:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*85ogy6szbI02C4Hz.png" /></figure><p>Creating a service account is optional.</p><p>Create a service account → Generate keys → Assign permissions.</p><pre>gcloud iam service-accounts create sa-account-sjm \<br>--display-name=&quot;sa-account-sjm&quot;<br><br>gcloud iam service-accounts list<br><br>gcloud iam service-accounts keys create ~/key.json \<br>--iam-account=sa-account-sjm@gcplearingsjm.iam.gserviceaccount.com<br><br>gcloud projects add-iam-policy-binding gcplearingsjm \<br>--member=&quot;serviceAccount:sa_account_sjm@gcplearingsjm.iam.gserviceaccount.com&quot; \<br>--role=&quot;roles/owner&quot;</pre><p>Authenticate using a service account.</p><pre>gcloud auth activate-service-account sa-account-sjm@gcplearingsjm.iam.gserviceaccount.com \<br> - key-file=/home/rkgcplearning/key.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*8TOURIaGzZyAangz.png" /></figure><p>2. <strong>Create Bucket:</strong></p><pre>gcloud storage buckets create gs://netflix_source_data --location=us-central1<br> <br>gcloud storage buckets create gs://high_rated_movies --location=us-central1 </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*tHbIvW4jv1bTeNqXXUPu0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*tCJrTa03DGmsxTlkfXkuCw.png" /></figure><p>3. <strong>Create BigQuery Dataset:</strong></p><p>The dataset is created using the Python API.</p><pre>pip install google-cloud-bigquery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*5ag4NST4zt8s8sm4.png" /></figure><pre>from google.cloud import bigquery<br>client = bigquery.Client()<br><br>project_id = &quot;gcplearingsjm&quot;<br>dataset_id = &quot;analytics_datamart&quot;<br>datasetid = f&quot;{project_id}.{dataset_id}&quot;<br><br>dataset = bigquery.Dataset(datasetid)<br>dataset = client.create_dataset(dataset, exists_ok=True)<br>print(f&quot;Created dataset {dataset.dataset_id}&quot;)</pre><p>5. <strong>Sample file preparation:</strong></p><p>Let&#39;s use public data for this use case.</p><pre>pip install kagglehub<br><br>import kagglehub<br><br># Download latest version<br>path = kagglehub.dataset_download(&quot;evanschreiner/netflix-movie-ratings&quot;)<br><br>print(&quot;Path to dataset files:&quot;, path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*oTOTNzPoPCFhm90sqzBtYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*nl29cZ4B9C48txKraMAXxg.png" /></figure><p>Push the file to the bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*c1WMy9CMyCpqcMOgwqltIg.png" /></figure><p>6. <strong>Dataproc cluster creation:</strong></p><p>The file size is approximately 2GB. A machine type n4-standard-2 with 2 workers should be sufficient to complete the tasks.</p><pre>gcloud dataproc clusters create devcluster - region=us-central1 \<br>- zone=us-central1-a \<br>- master-machine-type=n4-standard-2 \<br>- worker-machine-type=n4-standard-2 \<br>- num-workers=2 \<br>- master-boot-disk-size=32GB \<br>- worker-boot-disk-size=32GB \<br>- image-version=2.1-debian11 \<br>- project=gcplearingsjm  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*wcs1mKDjUdBy6_wOR12AqA.png" /></figure><p>The cluster is ready. Let’s create a simple PySpark script to join the two datasets — <em>Movies</em> and <em>Ratings</em> — and retrieve the Top 5 highest-rated movies.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import lit,current_date,col,current_timestamp<br><br>spark = SparkSession.builder.appName(&quot;SparkToGCS&quot;).getOrCreate()<br><br># Read source file<br>df_movies = spark.read.csv(&quot;gs://netflix_source_data/movies.csv&quot;, header=True, inferSchema=True)<br>df_rating = spark.read.csv(&quot;gs://netflix_source_data/Netflix_User_Ratings.csv&quot;, header=True, inferSchema=True)<br><br># Top 5 Movies rated more 5 ratings<br><br>df_joined = df_movies.join(df_rating, df_movies[&quot;MovieId&quot;] == df_rating[&quot;MovieId&quot;], &quot;inner&quot;)<br>df_selected = df_joined.select(df_movies[&quot;MovieTitle&quot;], df_rating[&quot;Rating&quot;])<br>df_filtered = df_selected.filter(df_selected[&quot;Rating&quot;] == 5)<br>df_filtered.filter(df_filtered[&quot;MovieTitle&quot;] == &quot;Mob Justice&quot;)<br>df_grouped = df_filtered.groupBy(&quot;MovieTitle&quot;).count().withColumnRenamed(&quot;count&quot;, &quot;rating&quot;)<br>df_with_load_dt = df_grouped.withColumn(&quot;load_date&quot;, current_timestamp())<br>df_top_5 = df_with_load_dt.sort(df_with_load_dt.rating.desc()).limit(5)<br>df_top_5.show()<br><br>df_top_5.printSchema()<br><br><br>df_top_5.write.format(&quot;bigquery&quot;) \<br>  .option(&quot;table&quot;, &quot;gcplearingsjm.analytics_datamart.highest_rated_movies&quot;) \<br>  .option(&quot;temporaryGcsBucket&quot;, &quot;netflix_source_data&quot;) \<br>  .mode(&quot;append&quot;) \<br>  .save()</pre><p>7. <strong>Run the Spark Job &amp; Verify the Data in BigQuery:</strong></p><p>Cluster and Spark code is ready. Let&#39;s run and test.</p><pre>gcloud dataproc jobs submit pyspark /home/rkgcplearning/pyspark_file_to_bq.py   \<br>       --cluster=devcluster   \<br>       --region=us-central1</pre><p>Post-completion, the data load is being verified.</p><pre>bq query --use_legacy_sql=false &#39;select * from gcplearingsjm.analytics_datamart.highest_rated_movies&#39;</pre><p>8. <strong>Create &amp; Deploy Cloud Function:</strong></p><p>Up to Step 7, the Spark code successfully processed the data and loaded it into BigQuery.<br> Now, we need to proceed with pulling the latest dataset and uploading it to the specified bucket.</p><p>The Cloud Function will take care of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*ilBl-pToxhtPdHnVNo4bLw.png" /></figure><p>a. <strong>Requirements.txt: This </strong>file is used to <strong>install additional Python packages</strong> into your Composer environment.</p><p>b. <strong>Main.py</strong>: Cloud Functions used to trigger DAGs.</p><p>main.py</p><pre>import functions_framework<br>from google.cloud import bigquery<br><br><br>&#39;&#39;&#39;<br>Dependencies to be installed<br><br>db-dtypes<br>fsspec<br>gcsfs<br>bigquery<br><br>&#39;&#39;&#39;<br><br><br>@functions_framework.cloud_event<br>def bqtogcs(cloudevent):<br><br><br>   payload = cloudevent.data.get(&quot;protoPayload&quot;)<br>   if payload:<br><br>       <br>       # Build Big Query client <br>       bucket_name = &#39;high_rated_movies&#39;<br>       project = &quot;gcplearingsjm&quot;<br>       dataset_id = &quot;analytics_datamart&quot;<br>       table_id = &quot;highest_rated_movies&quot;<br>       <br>       # Write data into GCS<br>       client = bigquery.Client(project=project)<br>       destination_uri = &quot;gs://{}/{}&quot;.format(bucket_name, &quot;bq_to_gcs_extract&quot;  + &quot;.csv&quot;)<br>       #qry = &quot;select * from &quot; + project + &quot;.&quot; + dataset_id + &quot;.&quot; + table_id<br>       qry = &quot;SELECT * FROM gcplearingsjm.analytics_datamart.highest_rated_movies where load_date=(select max(load_date) from gcplearingsjm.analytics_datamart.highest_rated_movies)&quot;<br>       df_qry_result = client.query(qry).to_dataframe()<br>       df_qry_result.to_csv(destination_uri)<br><br>       print(<br>                &quot;Exported {}:{}.{} to {}&quot;.format(project, dataset_id, table_id, destination_uri)<br>            )</pre><pre>functions-framework==3.*<br>db-dtypes<br>fsspec<br>gcsfs<br>bigquery</pre><p>Both files are ready. Let&#39;s deploy.</p><pre>gcloud functions deploy bqtogcs   --gen2   \<br>             --runtime=python310 \<br>             --region=us-central1 \<br>             --entry-point=bqtogcs \<br>             --trigger-event-filters=&quot;type=google.cloud.audit.log.v1.written&quot;  \<br>             --trigger-event-filters=&quot;serviceName=bigquery.googleapis.com&quot;   \<br>             --trigger-event-filters=&quot;methodName=google.cloud.bigquery.v2.JobService.InsertJob&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*3h0acUjQEVcPA9z51eQNhg.png" /></figure><p>9. <strong>Verify the flow — Run the Spark job and verify the bucket:</strong></p><p>Run the Spark code and verify whether the latest data has been successfully pushed to the specified bucket.<br> This confirms that the Cloud Function triggered by the BigQuery insert event is working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*20vdRQ708TzE_rMG3AJQTA.png" /></figure><p>Verifying the Bucket.</p><pre>gsutil cat gs://high_rated_movies/bq_to_gcs_extract.csv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Qtu1FgNKdHBgQf1spiR8Zw.png" /></figure><p>10. <strong>Mandatory Info:</strong></p><p>If no longer required, please stop the Dataproc cluster and disable the Cloud Function to avoid unnecessary billing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=295404e6cd8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP: Loading Data from Google Cloud Storage to BigQuery using Cloud Composer]]></title>
            <link>https://medium.com/@krajkumar14/gcp-loading-data-from-google-cloud-storage-to-bigquery-using-cloud-composer-08c0f45b5c32?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/08c0f45b5c32</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[google-cloud-composer]]></category>
            <category><![CDATA[google-cloud-storage]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:22:30 GMT</pubDate>
            <atom:updated>2025-09-15T17:32:45.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*sMAI-V1XvCAOwEOazLxYfw.png" /></figure><p><strong>Steps:</strong></p><p>Initiate Cloud Shell &amp; Create Service Account<br>Create dataset and table<br>Create bucket<br>Move file from local to bucket<br>Setup Cloud Composer (Airflow)<br>Flow Chart<br>Move Python Script to DAG folder<br>Operators used<br>Run and Verify</p><ol><li><strong>Create Service Account &amp; Initiate gcloud:</strong></li></ol><p>Log into the GCP account and initiate cloud shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*HXKmOaow3Dyfv_3SYGM1uA.png" /></figure><p>Creating a service account is optional.</p><p>Create a service account → Generate keys → Assign permissions.</p><pre>gcloud iam service-accounts create sa-account-sjm \<br>--display-name=&quot;sa-account-sjm&quot;<br><br>gcloud iam service-accounts list<br><br>gcloud iam service-accounts keys create ~/key.json \<br>--iam-account=sa-account-sjm@gcplearingsjm.iam.gserviceaccount.com<br><br>gcloud projects add-iam-policy-binding gcplearingsjm \<br>--member=&quot;serviceAccount:sa_account_sjm@gcplearingsjm.iam.gserviceaccount.com&quot; \<br>--role=&quot;roles/owner&quot;</pre><p>Authenticate using a service account.</p><pre>gcloud auth activate-service-account sa-account-sjm@gcplearingsjm.iam.gserviceaccount.com \<br>--key-file=/home/rkgcplearning/key.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*kN5rYRhbmAfYfw7OuvUQng.png" /></figure><p>2. <strong>Create Dataset and Table:</strong></p><p>The dataset is created using the Python API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*SgyhVJY5_f5ZfCvwz3mAEg.png" /></figure><pre>from google.cloud import bigquery<br>client = bigquery.Client()<br><br>project_id = &quot;gcplearingsjm&quot;<br>dataset_id = &quot;analytics_datamart&quot;<br>datasetid = f&quot;{project_id}.{dataset_id}&quot;<br><br>dataset = bigquery.Dataset(datasetid)<br>dataset = client.create_dataset(dataset, exists_ok=True)<br>print(f&quot;Created dataset {dataset.dataset_id}&quot;)</pre><p>Creating tables…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_X7ZoAp_Mis-31DY65Extw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*n4o1HzieHmd0Mk3nPG_ASg.png" /></figure><pre>bq mk --table   gcplearingsjm.analytics_datamart.fund_details   fund_no:string,date:string,nav:string<br><br><br>bq mk --table   gcplearingsjm.analytics_datamart.fact_fund_details    fund_no:string,date:string,nav:string,load_date:date</pre><p>3. <strong>Create Bucket:</strong></p><pre>gcloud storage buckets create gs://raw_data_engg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*1-mAOb-g8IduSQHvzngvGw.png" /></figure><p>4. <strong>Move file from local to bucket:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LEF5AaQBSgLaIVXpBlVVdA.png" /></figure><pre>gsutil cp sample.csv  gs://raw_data_engg<br><br>gsutil ls  gs://raw_data_engg</pre><p>5. <strong>Setup Cloud Composer (Airflow):</strong></p><pre>gcloud services enable composer.googleapis.com<br><br>gcloud composer environments create prod-env \<br>    --location us-central1 \<br>    --image-version composer-3-airflow-2.10.5-build.13 \<br>    --service-account &quot;sa-account-sjm@gcplearingsjm.iam.gserviceaccount.com&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*BTtnGXwo9UpCBsqLIDQ9hA.png" /></figure><p>6. <strong>Move Python Script to DAG Folder:</strong></p><p>Check the DAG folder and move the Python script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*PKUC6Fl8SAdYd_vRYEbZzA.png" /></figure><pre>gcloud composer environments describe prod-env \<br>  --location us-central1 \<br>  --format=&quot;value(config.dagGcsPrefix)&quot;<br><br>gsutil cp GCS_to_BQ.py gs://us-central1-prod-env-f724e9a8-bucket/dags<br></pre><p>Python Script (GCS_to_BQ.py) is,</p><pre>from airflow import DAG<br>from airflow.utils.dates import days_ago<br>from datetime import datetime, timedelta<br>from airflow.operators.python import BranchPythonOperator<br>from airflow.operators.empty import EmptyOperator<br>from airflow.providers.google.cloud.hooks.bigquery import BigQueryHook<br>from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator<br>from airflow.providers.google.cloud.sensors.gcs import GCSObjectExistenceSensor<br>from airflow.providers.google.cloud.transfers.gcs_to_bigquery import GCSToBigQueryOperator<br>from airflow.providers.google.cloud.operators.gcs import GCSDeleteObjectsOperator<br><br><br>yesterday = datetime.combine(datetime.today() - timedelta(1), datetime.min.time())<br><br># Default arguments<br>default_args = {<br>    &#39;start_date&#39;: yesterday,<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5)<br>}<br><br># Constants<br>GCP_CONN_ID = &#39;google_cloud_default&#39;<br>#google_cloud_conn_id=&#39;google_cloud_default&#39;<br>EXPECTED_COUNT = 0<br><br>def check_row_count(**kwargs):<br>    hook = BigQueryHook(gcp_conn_id=GCP_CONN_ID)<br>    sql = &quot;&quot;&quot;<br>    SELECT COUNT(*) as count<br>    FROM gcplearingsjm.analytics_datamart.fact_fund_details<br>    WHERE  CAST(load_date AS STRING) = CAST(CURRENT_DATE() AS STRING)<br>    &quot;&quot;&quot;<br>    df = hook.get_pandas_df(sql)<br>    actual_count = df.iloc[0][&#39;count&#39;]<br><br>    print(f&quot;[INFO] Actual row count: {actual_count}&quot;)<br><br>    if actual_count == EXPECTED_COUNT:<br>        return &#39;insert_into_table&#39;<br>    else:<br>        return &#39;skip_insert&#39;<br><br># Define DAG<br>with DAG(<br>    dag_id=&#39;GCS_to_BQ&#39;,<br>    schedule_interval=timedelta(days=1),<br>    default_args=default_args,<br>    tags=[&#39;example&#39;],<br>) as dag:<br><br>    start = EmptyOperator(task_id=&#39;start&#39;)<br><br>    # Wait for GCS file<br>    gcs_object_exists = GCSObjectExistenceSensor(<br>        task_id=&#39;gcs_object_exists&#39;,<br>        bucket=&#39;raw_data_engg&#39;,<br>        object=&#39;sample.csv&#39;,<br>        poke_interval=10,<br>        timeout=300,<br>        #gcp_conn_id=GCP_CONN_ID<br>    )<br><br>    # Load CSV to staging BigQuery table<br>    gcs_to_bq_load = GCSToBigQueryOperator(<br>        task_id=&#39;gcs_to_bq_load&#39;,<br>        bucket=&#39;raw_data_engg&#39;,<br>        source_objects=[&#39;sample.csv&#39;],<br>        destination_project_dataset_table=&#39;gcplearingsjm.analytics_datamart.fund_details&#39;,<br>        schema_fields=[<br>            {&#39;name&#39;: &#39;fund_no&#39;, &#39;type&#39;: &#39;STRING&#39;, &#39;mode&#39;: &#39;NULLABLE&#39;},<br>            {&#39;name&#39;: &#39;date&#39;, &#39;type&#39;: &#39;STRING&#39;, &#39;mode&#39;: &#39;NULLABLE&#39;},<br>            {&#39;name&#39;: &#39;nav&#39;, &#39;type&#39;: &#39;STRING&#39;, &#39;mode&#39;: &#39;NULLABLE&#39;}<br>        ],<br>        skip_leading_rows=1,<br>        create_disposition=&#39;CREATE_IF_NEEDED&#39;,<br>        write_disposition=&#39;WRITE_TRUNCATE&#39;,<br>        gcp_conn_id=GCP_CONN_ID<br>    )<br><br>    # Check if fact table has today&#39;s data<br>    branch_task = BranchPythonOperator(<br>        task_id=&#39;check_row_count&#39;,<br>        python_callable=check_row_count,<br>    )<br><br>    # Load from staging to fact table with load_date<br>    insert_task = BigQueryInsertJobOperator(<br>        task_id=&#39;insert_into_table&#39;,<br>        configuration={<br>            &quot;query&quot;: {<br>                &quot;query&quot;: &quot;&quot;&quot;<br>                    SELECT fund_no, date, nav, CURRENT_DATE() as load_date<br>                    FROM `gcplearingsjm.analytics_datamart.fund_details`<br>                &quot;&quot;&quot;,<br>                &quot;useLegacySql&quot;: False,<br>                &quot;destinationTable&quot;: {<br>                    &quot;projectId&quot;: &quot;gcplearingsjm&quot;,<br>                    &quot;datasetId&quot;: &quot;analytics_datamart&quot;,<br>                    &quot;tableId&quot;: &quot;fact_fund_details&quot;<br>                },<br>                &quot;writeDisposition&quot;: &quot;WRITE_APPEND&quot;,<br>                &quot;createDisposition&quot;: &quot;CREATE_IF_NEEDED&quot;<br>            }<br>        },<br>        gcp_conn_id=GCP_CONN_ID<br>    )<br><br>    skip_task = EmptyOperator(task_id=&#39;skip_insert&#39;)<br><br>    #Post load delete the file<br>    delete_gcs_files = GCSDeleteObjectsOperator(<br>        task_id=&#39;delete_gcs_files&#39;,<br>        bucket_name=&#39;raw_data_engg&#39;,<br>        objects=[&#39;sample.csv&#39;],<br>        #gcp_conn_id=GCP_CONN_ID<br>    )<br><br>    end = EmptyOperator(task_id=&#39;end&#39;)<br><br>    # DAG structure<br>    start &gt;&gt; gcs_object_exists &gt;&gt; gcs_to_bq_load &gt;&gt; branch_task<br>    branch_task &gt;&gt; insert_task &gt;&gt; delete_gcs_files &gt;&gt; end<br>    branch_task &gt;&gt; skip_task &gt;&gt; end</pre><p>7. <strong>Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*YCLHTyEus0KQ2fe_K0QhOw.png" /></figure><p>8. <strong>Operators used:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*uNaVODPW2UIXwaXCLTeTJw.png" /></figure><p>8. <strong>Run and Verify:</strong></p><pre>gcloud composer environments run prod-env \<br>  --location us-central1 \<br>  dags trigger \<br>  -- GCS_to_BQ</pre><p>Let&#39;s check the DAG and verify the load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*FSI5qyK6cOOpRon8yx-fQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*5guM0RqHufoP8vGPkMVyEA.png" /></figure><p>Second run—since the data for the current date is already loaded, the next run will skip the insert operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*yQlVw0OnJqsISlQbMlRqUA.png" /></figure><p>Instead of deleting the source file, we can also move it to the target folder.</p><pre>move_gcs_file = GCSToGCSOperator(<br> task_id=&quot;move_file_between_buckets&quot;,<br> source_bucket=&#39;raw_data_engg&#39;,<br>    source_object=[&#39;sample.csv&#39;],<br> destination_bucket=&quot;tgt_data_engg&quot;,<br> destination_object=&quot;sample.csv&quot;, <br> move_object=True, <br>)</pre><p>Another option is to check the row count.</p><pre>check_rows = BigQueryValueCheckOperator(<br>    task_id=&quot;check_row_count&quot;,<br>    sql = &quot;&quot;&quot;<br>    SELECT COUNT(*) as count<br>    FROM gcplearingsjm.analytics_datamart.fact_fund_details<br>    WHERE  CAST(load_date AS STRING) = CAST(CURRENT_DATE() AS STRING)<br>    &quot;&quot;&quot;,<br>    pass_value=0,  <br>    use_legacy_sql=False,<br>)</pre><p>If the condition is satisfied → the task succeeds.</p><p>If the condition is not satisfied → the task fails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08c0f45b5c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bigquery: Rank vs Array_agg]]></title>
            <link>https://medium.com/@krajkumar14/bigquery-rank-vs-array-agg-9e00cf9bd6d1?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e00cf9bd6d1</guid>
            <category><![CDATA[array-functions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[rank]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 19:05:47 GMT</pubDate>
            <atom:updated>2025-03-14T19:05:47.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*X6s5cSs2GaIZn6MJpr59JA.png" /></figure><p><strong>Description:</strong></p><p>We have a table with subject-wise marks for each student. We need to determine the highest score for each subject.</p><p>Yes, this is a simple scenario. We can achieve this using a window function (rank).</p><p>But we are going to achieve this using ARRAY_AGG function.</p><p><strong>Note:</strong> One of the<strong> </strong>Bigquery optimization techniques is using BQ native functions over regular OLAP functions.</p><p><strong>Keywords:</strong></p><p>Rank — Assign a rank to each row within a partition of result set.</p><p>Array_Agg — Summarizes the rows of group into a single value.</p><p>Index / Ordinal /Offset — Access the array elements</p><p>Ordinal — one based indexes</p><p>Offset — Zero based indexes</p><p><strong>Data:</strong></p><p>Below is our sample data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*FNXfTRuoni4ZDlsGpslrNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*Jcx-kVtf1WP9tu0Ez5ck6A.png" /></figure><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*pyn_2xHLss05V9o5vARpaQ.png" /></figure><pre>create table `abstract-pod-447012-t7.prod_analytics.student_marks`<br>(<br>name string,<br>subject string,<br>mark int64<br>);<br><br>insert into abstract-pod-447012-t7.prod_analytics.student_marks values (&#39;Jhon&#39;,&#39;Maths&#39;,50),<br>(&#39;Tom&#39;,&#39;Maths&#39;,60),<br>(&#39;Web&#39;,&#39;Maths&#39;,60),<br><br>(&#39;Jhon&#39;,&#39;Science&#39;,45),<br>(&#39;Tom&#39;,&#39;Science&#39;,70),<br>(&#39;Web&#39;,&#39;Science&#39;,50),<br><br>(&#39;Jhon&#39;,&#39;English&#39;,80),<br>(&#39;Tom&#39;,&#39;English&#39;,70),<br>(&#39;Web&#39;,&#39;English&#39;,90);<br><br>select * from abstract-pod-447012-t7.prod_analytics.student_marks;</pre><p><strong>Using Rank:</strong></p><pre>with top_marks as<br>(<br>select *,rank() over (partition by subject order by mark desc) as top_mark from abstract-pod-447012-t7.prod_analytics.student_marks<br>) select * from top_marks where top_mark=1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*6x8s_MgTlwKyPzGGASERQg.png" /></figure><p>Using qualify to avoid subquery, CTE.</p><pre>select * from abstract-pod-447012-t7.prod_analytics.student_marks<br>qualify rank() over (partition by subject order by mark desc)=1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*duo4vSDD7H3Cs8vETiFyDA.png" /></figure><p><strong>Using Array_agg:</strong></p><p>Let’s run step by step.</p><pre>select *,array_agg(mark) over (partition by subject order by mark desc) as marks_agg from abstract-pod-447012-t7.prod_analytics.student_marks;</pre><p>In this step, the mark column is aggregated, and the mark is ordered in descending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*fPqLkoi9nwSdARAFNdWVhw.png" /></figure><p>From the array, select the first element using index or ordinal, or offset.</p><pre>select *,array_agg(mark) over (partition by subject order by mark desc) [0] as marks_agg from abstract-pod-447012-t7.prod_analytics.student_marks;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*5nMyn0ZklXZoBz-TEqE3MA.png" /></figure><pre>with top_mark as <br>(<br>select *,array_agg(mark) over (partition by subject order by mark desc) [0] as marks_agg from abstract-pod-447012-t7.prod_analytics.student_marks<br>) select * except(marks_agg) from top_mark where mark=marks_agg;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*BcUSIaII_bS4Y-cmTILq_w.png" /></figure><p>Using qualify to avoid subquery, CTE.</p><pre>select *  from abstract-pod-447012-t7.prod_analytics.student_marks<br>qualify array_agg(mark) over (partition by subject order by mark desc) [0]=mark;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*cLsGXAfBv6v8SlQYnHfbMQ.png" /></figure><p><strong>Statistics:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*XcGHBFtwnq8WxPoX50pbOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*45q6TUYVC7BoMR-d11eeBQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e00cf9bd6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bigquery : Data ingestion from Virtual Machine using BQ command line and API]]></title>
            <link>https://medium.com/@krajkumar14/bigquery-data-ingestion-from-virtual-machine-using-bq-command-line-and-api-d5432135a088?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5432135a088</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[compute-engine]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 18:31:34 GMT</pubDate>
            <atom:updated>2025-03-11T18:31:34.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bigquery : Data ingestion from Virtual Machine using BQ command line and API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZLJjr_RDj7nA98jXC1JFQ.png" /></figure><p><strong>Description:</strong></p><p>There are multiple ways like command line, API, Web console etc to ingest data to Bigquery.</p><p>Command line is one of the main methods of ingestion in Data engineering projects.</p><p>In real world scenarios, the files will be pushed or pull via multiple ways like API, SFTP etc.</p><p>We will prepare a sample file — “Pull Stock/mutual fund data using Yahoo Finance Module” for our use case here.</p><p>Listed are the file Types that will be processed: CSV, Json, AVRO, Parquet.</p><p><strong>Steps:</strong></p><p>· Setup Virtual machine in GCP</p><p>· Sample file preparation (CSV, Json, AVRO, Parquet)</p><p>o Install Python in VM</p><p>o Install required packages</p><p>· Load files into BQ tables using command line</p><p>· Verify the data</p><p><strong>Setup Virtual machine in GCP:</strong></p><p>Reference below article.</p><p><a href="https://medium.com/@krajkumar14/accessing-bigquery-from-virtual-machine-a125fab2a27d">Accessing Bigquery from Virtual Machine</a></p><p><strong>Sample file preparation:</strong></p><p>As the first step, install python in VM.</p><p>Start the virtual machine and open SSH browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*oC0DwaLXMx2Il5WPF7B0MQ.png" /></figure><p>Run the below commands:</p><pre>Sudo apr-get install wget<br>mkdir -p ~/miniconda3<br>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh<br>bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3<br>rm ~/miniconda3/miniconda.sh<br>source ~/miniconda3/bin/activate<br>conda init - all</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*ObUfJ0yG68BIwQdVcpoDGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*SwqMqEHcWuHuNy3OdjjL5w.png" /></figure><p>Verifying python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*_LyVAJdRoJtdOX1jEi4bNQ.png" /></figure><p>Install required packages using conda install or pip install.</p><p>Pandas, Mftool, pyarrow, fastavro.</p><p>Now all set to prepare sample files.</p><p>Below is the python script which pulls data and generate different file formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*0c7Iy7tlxRKU8wnb79vqsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*kU7c6JEKQBf6jmQBkCBcew.png" /></figure><p>Execute the script and view the generated files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*hbEW7fXFrJ2nOy9sb0Pusg.png" /></figure><pre>import pandas as pd<br>from mftool import Mftool<br>from fastavro import writer, parse_schema, reader<br>import datetime<br>mf = Mftool()<br><br>df = pd.DataFrame()<br> <br>print(df)<br><br><br>df = mf.get_scheme_historical_nav(&#39;135784&#39;,as_Dataframe=True).reset_index()<br>df[&#39;fund_no&#39;] = &#39;135784&#39;<br>#df = df[list((&#39;fund_no&#39;,&#39;date&#39;,&#39;nav&#39;,&#39;dayChange&#39;))]<br><br>df = df[list((&#39;fund_no&#39;,&#39;date&#39;,&#39;nav&#39;))]<br><br>#Download as CSV<br><br>df.to_csv(&quot;/home/samrith_r/sample.csv&quot;,index=False)<br><br>#Download as Json<br><br>df.to_json(&quot;/home/samrith_r/sample.json&quot;,orient=&quot;records&quot;,lines=True)<br><br>#Download as Parquet<br><br>df.to_parquet(&quot;/home/samrith_r/sample.parquet&quot;, engine=&quot;pyarrow&quot;, index=False)<br><br>#Download as Avro<br>#specifying the avro schema<br>schema = {<br>    &#39;doc&#39;: &#39;mutualfunddata&#39;,<br>    &#39;name&#39;: &#39;mutualfunddata&#39;,<br>    &#39;namespace&#39;: &#39;mutualfunddata&#39;,<br>    &#39;type&#39;: &#39;record&#39;,<br>    &#39;fields&#39;: [<br>        {&#39;name&#39;: &#39;fund_no&#39;, &#39;type&#39;: &#39;string&#39;},<br>       {&#39;name&#39;: &#39;date&#39;, &#39;type&#39;: &#39;string&#39;},<br>       {&#39;name&#39;: &#39;nav&#39;, &#39;type&#39;: &#39;string&#39;}<br>    ]<br>}<br>parsed_schema = parse_schema(schema)<br>records = df.to_dict(&#39;records&#39;)<br>with open(&#39;/home/samrith_r/sample.avro&#39;, &#39;wb&#39;) as out:<br>    writer(out, parsed_schema, records)</pre><p><strong>Load files into BQ tables using command line:</strong></p><p>Below are the steps:</p><p>· Create table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*1wUTHDc652DqbH0K4yN9Sw.png" /></figure><pre>bq query - nouse_legacy_sql &#39;create or replace table abstract-pod-447012-t7.prod_analytics.sample_csv (fund_no string,date string,nav string)&#39;;<br>bq query - nouse_legacy_sql &#39;create or replace table abstract-pod-447012-t7.prod_analytics.sample_json (fund_no string,date string,nav string)&#39;;<br>bq query - nouse_legacy_sql &#39;create or replace table abstract-pod-447012-t7.prod_analytics.sample_parquet (fund_no string,date string,nav string)&#39;;<br>bq query - nouse_legacy_sql &#39;create or replace table abstract-pod-447012-t7.prod_analytics.sample_avro (fund_no string,date string,nav string)&#39;;</pre><p>· Load files and verify</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*PcRShWODioeUdSkUsk_xhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*GaZToPJ49vWrvqkY-U4wGA.png" /></figure><pre>bq load - source_format=CSV - skip_leading_rows=1 prod_analytics.sample_csv /home/samrith_r/sample.csv;<br>bq load - source_format=NEWLINE_DELIMITED_JSON prod_analytics.sample_json /home/samrith_r/sample.json;<br>bq load - source_format=PARQUET prod_analytics.sample_parquet /home/samrith_r/sample.json.parquet;<br>bq load - source_format=AVRO prod_analytics.sample_avro /home/samrith_r/sample.avro;<br><br>bq query - nouse_legacy_sql &#39;select count(*) from abstract-pod-447012-t7.prod_analytics.sample_csv&#39;;<br>bq query - nouse_legacy_sql &#39;select count(*) from abstract-pod-447012-t7.prod_analytics.sample_json&#39;;<br>bq query - nouse_legacy_sql &#39;select count(*) from abstract-pod-447012-t7.prod_analytics.sample_parquet&#39;;<br>bq query - nouse_legacy_sql &#39;select count(*) from abstract-pod-447012-t7.prod_analytics.sample_avro&#39;;</pre><p>To summarize, Stock/Mutual fund data has been pulled and a sample file has been prepared in different formats. The file is loaded into Bigquery table using Command line.</p><h4>Additional information.</h4><ol><li>Similarly, way we can also load from bucket (GCS).</li></ol><pre>Ex: bq load - source_format=CSV - skip_leading_rows=1 prod_analytics.sample_csv gs://prodanalytics/sample.csv</pre><p>2. Like command line we can also ingest data using API. Here python API will be loading file into BQ.</p><p>· Install Bigquery Package.</p><pre>pip install Bigquery</pre><p>· Move file to GCS bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*KQOTGgQEDBS-CEP4Yt9g0Q.png" /></figure><pre>gcloud storage cp /home/samrith_r/sample.csv gs://prodanalytics/sample.csv</pre><p>· Verify the moved file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*Q5NoOBGm90tPtyrynrh57w.png" /></figure><pre>gsutil ls -l gs://prodanalytics/</pre><p>· Below is the script to load files in BQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*sGd9toe3Bz7qgAKFLOc10g.png" /></figure><p>· Execute the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*skVFU5_FVuY3pn9f7Wo6Qw.png" /></figure><p>Code Snippet:</p><pre>from google.cloud import bigquery<br>client = bigquery.Client()<br>table_id=&#39;abstract-pod-447012-t7.prod_analytics.sample_csv&#39;<br>job_config = bigquery.LoadJobConfig(<br>skip_leading_rows=1,<br>source_format=bigquery.SourceFormat.CSV,<br>)<br>uri = &quot;gs://prodanalytics/sample.csv&quot;<br>load_job = client.load_table_from_uri(<br>uri, table_id, job_config=job_config<br>)<br>load_job.result()<br>destination_table = client.get_table(table_id)<br>print(&quot;Loaded {} rows.&quot;.format(destination_table.num_rows))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5432135a088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Bigquery from Virtual Machine]]></title>
            <link>https://medium.com/@krajkumar14/accessing-bigquery-from-virtual-machine-a125fab2a27d?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a125fab2a27d</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[compute-engine]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 14:16:11 GMT</pubDate>
            <atom:updated>2025-02-28T14:16:11.198Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this article, we will be able to understand how we can access Bigquery from a virtual machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6wWaBP1urK75IWBzfvyjLg.png" /></figure><p><strong>Steps:</strong></p><p>1. Service account creation</p><p>2. Key Generation</p><p>3. Virtual Machine creation (Compute Engine) &amp; Checking Bigquery access</p><p><strong>Step1:</strong></p><p>Log into GCP Console</p><p>Menu → IAM &amp; Admin → Service Account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*0tZDtud4fuRa2fPGuYJxrA.png" /></figure><p>Next pop-up window provides Service account name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*HrWP0VbUWtEzH1UrfxXuLQ.png" /></figure><p>Provide required access to the account. It can be either product wise or full access.</p><p>Here I have given <strong>Basic → Owner</strong></p><p>Post this press create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*ptYGngkuGYByo3qzWIDRcw.png" /></figure><p>Service account created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*1oyuM3PBkQBDzTlP3ZyM4g.png" /></figure><p><strong>Step2:</strong></p><p><strong>Actions -&gt; Manage Keys</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*lNoax8IY75Hea1khfRZYaA.png" /></figure><p>In the new pop window select <strong>Generate New Key</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*bdf_xiq2MLnas6GWp5c85g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*MAJtijJ1FAf0BpguliE9cA.png" /></figure><p>The new key file (JSON) will be generated and saved into local system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*UrXu9VLTBtK-XcdoH314YA.png" /></figure><p><strong>Step3:</strong></p><p>VM instance creation.</p><p>Menu → Compute Engine → VM Instances</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*bPrKPlKCpSyLqpxEcU2e-w.png" /></figure><p>Press create instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*C-4oBpHgMrcv9wO_ExOqZw.png" /></figure><p>Here majorly we are focusing on <strong>Machine Configuration, Networking &amp; Security</strong>.</p><p>Again, Machine type is user preference. Here I have selected E2 — Low cost, day to day computing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*zS-LJGE97EAuwwtGeVSDbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*o1HR4S-mHU3IGJcEWHpcCw.png" /></figure><p>Networking <strong>Allow HTTP traffic, Allow HTTPS traffic.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*sbx6yJm0gSvDl-7vPahU0A.png" /></figure><p>Finally, <strong>security</strong> tab, select newly created service account.</p><p>Then access scope, we can provide specific API based access. Here I have given <strong>full access</strong>.</p><p>Then press create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*P3FFRnSSclqSCV1wtVbEUA.png" /></figure><p>For specific API level access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*Dl_s4Hf0qN-eNrhocixUEA.png" /></figure><p>Finally, the VM instance is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*fwyWHsh8qDai3Qez7kvsrA.png" /></figure><p>Final few steps to access Bigquery.</p><p>SSH → Open in Brower window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*VlKtS_TQEIQKzqWd0Ad0QQ.png" /></figure><p>Next add the newly generated Key file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*3fT6Mhi_UtpgHZVDuNYwuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*8nZuH0yA2madh8WGXN9EDQ.png" /></figure><p>Once the key file is added, we need to authenticate it.</p><p>Run below command.</p><p>gcloud auth activate-service-account <strong>service_account_name</strong></p><p>— key-file=key.json — project=<strong>project_name</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*sb-vqZDiLEPVZe8WNsjN9A.png" /></figure><p>Final step,</p><p>Checking access using Bigquery using Command Line interface (CLI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*BGw-wJ2Njci3mlIaCf-81g.png" /></figure><p>So, we are now able to access Bigquery from a virtual machine successfully.</p><p><strong>Note:</strong></p><p>Post all activity delete (if not required) or stop the instance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a125fab2a27d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bigquery — Row to column using Pivot function with Dynamic SQL]]></title>
            <link>https://medium.com/@krajkumar14/bigquery-row-to-column-using-pivot-function-with-dynamic-sql-897d465be530?source=rss-6ae57b3a73f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/897d465be530</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Rajkumar k]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 14:16:03 GMT</pubDate>
            <atom:updated>2025-02-25T14:17:33.067Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Bigquery — Row to column using Pivot function with Dynamic SQL</strong></h3><p>The use case is transposing rows to columns.</p><p><strong>Input:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*WAgJadYFH7ZA9Mb-QFT3SA.png" /></figure><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*wE7pDhvwphMmgbLzkeBCyA.png" /></figure><p><strong>Approach 1:</strong></p><p>This is the usual approach, and it’s the ANSI standard. The same code can be executed in Oracle, MySQL, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WwdcYZGKva9iXQtoyU5Vsg.png" /></figure><p><strong>Approach 2:</strong></p><p>In this method we will be using the <strong>Pivot</strong> function to transpose the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FLN6KNid03H6tVKXeIxohA.png" /></figure><p><strong>Approach 3:</strong></p><p>In this method we will be using Pivot with Dynamic SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*p1DqV5iZqL8rMUqn_oPq4g.png" /></figure><p>In the above 2 approaches, if a new category is added, we need to modify the code.</p><p>In this case it will be taken care of automatically.</p><p>Let’s test it.</p><p>Adding another category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Jp2EF8E0_gAXccDD2laSIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*aH2XQtyRz61B2y5KQ5J0Tg.png" /></figure><p><strong>Code Snippet:</strong></p><p>create or replace table `abstract-pod-447012-t7.prod_analytics.employee_salary`<br>(<br>emp_id string,<br>Category string,<br>amount int64<br>);</p><p>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘12A’,’Salary’,50000);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘12A’,’Bonus’,10000);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘12A’,’Hike’,10);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘14C’,’Salary’,55000);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘14C’,’Bonus’,12000);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘14C’,’Hike’,12);</p><p>select <br>emp_id,<br>max(case when Category=’Salary’ then amount else 0 end) Salary,<br>max(case when Category=’Bonus’ then amount else 0 end) Bonus,<br>max(case when Category=’Hike’ then amount else 0 end) Hike,<br>from abstract-pod-447012-t7.prod_analytics.employee_salary<br>group by emp_id;</p><p>select *<br>from abstract-pod-447012-t7.prod_analytics.employee_salary<br>PIVOT<br>(<br>max(amount)</p><p>FOR category in (‘Salary’,’Bonus’,’Hike’)<br>);</p><p>DECLARE ctgy string default (select concat(“‘“,string_agg( distinct category,”’,’”),”’”) from abstract-pod-447012-t7.prod_analytics.employee_salary);</p><p>declare qry string;</p><p>set qry=”””</p><p>select *<br>from abstract-pod-447012-t7.prod_analytics.employee_salary<br>PIVOT<br>(<br>max(amount)</p><p>FOR category in (‘Salary’,’Bonus’,’Hike’)<br>)”””;</p><p>execute immediate (qry);</p><p>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘12A’,’Stock’,1000);<br>insert into abstract-pod-447012-t7.prod_analytics.employee_salary values (‘14C’,’Stock’,2000);</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897d465be530" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>