<?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 Ashutosh Singh on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Singh on Medium]]></description>
        <link>https://medium.com/@ashutoshsingh?source=rss-cf4e078e8172------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xF4zj5mgkBQZvyu0i3_d2g.jpeg</url>
            <title>Stories by Ashutosh Singh on Medium</title>
            <link>https://medium.com/@ashutoshsingh?source=rss-cf4e078e8172------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:13:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshsingh/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[Join Bigquery table with spark stream to get mapping data in realtime]]></title>
            <link>https://towardsdev.com/join-bigquery-table-with-spark-stream-to-get-mapping-data-in-realtime-b1a1e1b00763?source=rss-cf4e078e8172------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a1e1b00763</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 11:20:47 GMT</pubDate>
            <atom:updated>2024-02-05T16:17:54.239Z</atom:updated>
            <content:encoded><![CDATA[<p>Agenda of this blog to join bigquery table with spark stream dataframe to get transformed data in realtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Zdgxq7IggZutgC1NiX_dA.png" /></figure><p>To solve this use-case, taking example of product order and product price. Product order data is comming through spark stream, however product price is master table which is created in bigquery. We have to read product order stream and join with product price table in realtime and compute total bill of each order. After computation, store output back to another bigquery table named product_order_bill.</p><p><strong>Create spark dataframe for bigquery table</strong></p><p>Here will create a spark dataframe for table named product_price. This is master table created in bigquery and keeps price of each product.</p><pre>product_price_df = spark.read.format(&quot;bigquery&quot;)\<br>    .option(&quot;table&quot;,&quot;product_price&quot;)\<br>    .load()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Z-eTcG0LdJok23kb4_ht7A.png" /><figcaption>product_price</figcaption></figure><p><strong>Json Payload -</strong></p><p>This is json payload of kafka topic named product-order, which will be consumed from kafka through spark stream.</p><pre>{<br>  &quot;orderId&quot;: &quot;ORD0001&quot;,<br>  &quot;productId&quot;: &quot;P001&quot;,<br>  &quot;quantity&quot;: 3<br>}</pre><p><strong>Create stream -</strong></p><p>Create spark stream dataframe to read kafka topic named product-order.</p><pre><br>server = &#39;kafka-host:9092&#39;<br>usr = &#39;kafka-user-id&#39;<br>pwd = &#39;ASDEWQ5675vdssfgtfnbbnmb&#39;<br>group_id = &#39;kafka-product-order-group-1&#39;<br>topic = &#39;product-order&#39;<br><br>df = spark.readStream\<br>    .format(&quot;kafka&quot;)\<br>    .option(&quot;kafka.bootstrap.servers&quot;, server)\<br>    .option(&quot;kafka.sasl.jaas.config&quot;, config)\<br>    .option(&quot;kafka.security.protocol&quot;, &quot;SASL_SSL&quot;)\<br>    .option(&quot;kafka.sasl.mechanism&quot;, &quot;PLAIN&quot;)\<br>    .option(&quot;failOnDataLoss&quot;, &quot;false&quot;)\<br>    .option(&quot;subscribe&quot;,topic)\<br>    .option(&quot;startingOffsets&quot;, &quot;latest&quot;)\<br>    .load()</pre><p><strong>Transformation</strong></p><p>Here record json comes under <em>value</em>. We need to parse it and convert into json format. For better usability, we are pulling all attributes of json payload at root level of dataframe.</p><pre>schema = t.StructType([ <br>     t.StructField(&quot;orderId&quot;,t.StringType(),True), <br>     t.StructField(&quot;productId&quot;,t.StringType(),True), <br>     t.StructField(&quot;quantity&quot;,t.IntegerType(),True)<br>])<br><br>df = df.withColumn(&#39;key_str&#39;, df[&#39;key&#39;].cast(&#39;string&#39;).alias(&#39;key_str&#39;))\<br>      .drop(&#39;key&#39;)\<br>      .withColumn(&#39;value_str&#39;, df[&#39;value&#39;].cast(&#39;string&#39;).alias(&#39;key_str&#39;))\<br>      .drop(&#39;value&#39;)<br><br>df = df.withColumn(&#39;value_json&#39;, f.from_json(df[&#39;value_str&#39;], schema))<br><br>df = df.withColumn(&#39;order_id&#39;, df[&#39;value_json&#39;][&#39;orderId&#39;])<br>df = df.withColumn(&#39;product_id&#39;, df[&#39;value_json&#39;][&#39;productId&#39;])<br>df = df.withColumn(&#39;quantity&#39;, df[&#39;value_json&#39;][&#39;quantity&#39;])</pre><p><strong>Mapping with product price and write to bigquery</strong></p><p>Create write stream and use foreachBatch to call a function. Here we are streaming data for given processing time(5 minutes). By calling foreachBatch, a spark dataframe is created for each 5 minutes and calls a function to do any operation on that dataframe.</p><p>We have create function here named <em>product_order_price_mapping. </em>Under this function we are creating two temporary view named <em>stream_df_tmp</em> and <em>product_price_df_tmp </em>for spark stream dataframe and bigquery dataframe. Next create a sql and compute required output and create another dataframe. This is final dataframe, so write it back to bigquery.</p><p>Note:- There could be two ways to create temporary view</p><ol><li>createOrReplaceGlobalTempView</li><li>createOrReplaceTempView</li></ol><p>We have used createOrReplaceGlobalTempView for creating view as it creates view for entire spark application. However createOrReplaceTempView also creates view, but for specific session and two different view might be associated with two different session. So sometimes you might get error like “<em>Table of view does not exist</em>”</p><pre>output_query = df.writeStream \<br>        .outputMode(&#39;append&#39;) \<br>        .foreachBatch(product_order_price_mapping) \<br>        .option(&quot;checkpointLocation&quot;, &quot;checkpoint_path&quot;) \<br>        .trigger(processingTime=&quot;5 minutes&quot;)\<br>        .start()<br><br>output_query.awaitTermination()</pre><pre>def product_order_price_mapping(df, epoch_id):<br>  df.createOrReplaceGlobalTempView(&#39;stream_df_tmp&#39;)<br>  product_price_df.createOrReplaceGlobalTempView(&#39;product_price_df_tmp&#39;)<br><br>  sql = &#39;&#39;&#39;<br>    select ss.order_id, <br>           ss.product_id, <br>           ss.quantity, <br>           (ss.quantity * bq.unit_price) as total_bill<br>    from stream_df_tmp as ss<br>    left join product_price_df_tmp bq<br>    on ss.product_id = bq.order_id<br>  &#39;&#39;&#39;<br><br>  map_df = spark.sql(sql)<br>  <br>  map_df.write \<br>      .format(&quot;bigquery&quot;) \<br>      .option(&quot;table&quot;, &quot;product_order_bill&quot;) \<br>      .option(&quot;temporaryGcsBucket&quot;, &quot;stream-bucket&quot;) \<br>      .mode(&#39;append&#39;) \<br>      .save()<br></pre><p><strong>product_order_bill</strong> <strong>table</strong></p><p>product_order_bill is output table, created in bigquery, which gets populated in realtime through spark stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*mbqqjUqoczqkq0k_PRNaTw.png" /><figcaption>product_order_bill</figcaption></figure><p>Enough documentation for today‘s blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a1e1b00763" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/join-bigquery-table-with-spark-stream-to-get-mapping-data-in-realtime-b1a1e1b00763">Join Bigquery table with spark stream to get mapping data in realtime</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka to Bigquery through PySpark Stream]]></title>
            <link>https://towardsdev.com/kafka-to-bigquery-through-pyspark-stream-c825b9bbe4e5?source=rss-cf4e078e8172------2</link>
            <guid isPermaLink="false">https://medium.com/p/c825b9bbe4e5</guid>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 15:10:28 GMT</pubDate>
            <atom:updated>2024-02-03T13:35:50.207Z</atom:updated>
            <content:encoded><![CDATA[<p>I am not going to explain here what is kafka, spark streaming or bigquery as you can get enough documentation on internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBjKOEdXUAobYDex7kvQUQ.png" /></figure><p>Our agenda here is to read streaming data from Kafka and write it into Bigquery table. We are going to use spark stream for data processing.</p><p><strong>Jars required to connect to kafka</strong></p><p>Download jars mentioned bellow from internet and put it on some GCS bucket. Create array of jar name with absolute path.</p><p>Note : If you are going to create dataproc workflow, then attach all these jars under create job -&gt; dependent jar section.</p><pre>packages = [<br>    &quot;gs://gcs-bucket/spark-bigquery-latest_2.12.jar&quot;,<br>    &quot;gs://gcs-bucket/commons-pool2-2.11.1.jar&quot;,<br>    &quot;gs://gcs-bucket/kafka-clients-2.8.1.jar&quot;,<br>    &quot;gs://gcs-bucket/slf4j-api-1.7.32.jar&quot;,<br>    &quot;gs://gcs-bucket/spark-sql-kafka-0-10_2.12-3.3.2.jar&quot;,<br>    &quot;gs://gcs-bucket/spark-streaming-kafka-0-10-assembly_2.12-3.3.2.jar&quot;,<br>    &quot;gs://gcs-bucket/spark-token-provider-kafka-0-10_2.12-3.3.2.jar&quot;<br>]</pre><p><strong>Create spark session</strong></p><p>Create spark session and include all these jars under config section</p><pre>spark = SparkSession.builder\<br>          .appName(&#39;kafka-spark-bigquery-app-1&#39;)\<br>          .master(&#39;local[*]&#39;)\<br>          .config(&quot;spark.jars.packages&quot;,&quot;,&quot;.join(packages))\<br>          .getOrCreate()</pre><p><strong>Creare read stream dataframe</strong></p><p>Create streaming dataframe to read data from multiple kafka topics. All topics can be passed as comma separated string. If there is large set of topics with fixed pattern, then regular expression can be passed like kafka-topic-*.</p><pre>server = &#39;kafka-host:9092&#39;<br>usr = &#39;user-id&#39;<br>pwd = &#39;password&#39;<br>group_id = &#39;kafka-spark-bigquery-group-1&#39;<br>topic = &quot;kafka-topic-1, kafka-topic-2&quot;<br><br>df = spark.readStream\<br>    .format(&quot;kafka&quot;)\<br>    .option(&quot;kafka.bootstrap.servers&quot;, server)\<br>    .option(&quot;kafka.sasl.jaas.config&quot;, config)\<br>    .option(&quot;kafka.security.protocol&quot;, &quot;SASL_SSL&quot;)\<br>    .option(&quot;kafka.sasl.mechanism&quot;, &quot;PLAIN&quot;)\<br>    .option(&quot;failOnDataLoss&quot;, &quot;false&quot;)\<br>    .option(&quot;subscribe&quot;,topic)\<br>    .option(&quot;startingOffsets&quot;, &quot;latest&quot;)\<br>    .load()</pre><p><strong>Parse kafka json and transform</strong></p><p>Spark stream reads kafka message into encoded key and value. Value field contains actual kafka message. You need to create a struct type equivalent to kafka payload.</p><p>Transformation steps -</p><ol><li>Create struct type equivalent to kafka payload</li><li>parse encoded key and convert to string</li><li>Parse encoded value and convert to string</li><li>Parse value string to value json</li><li>You can transform dataframe further according to your need…</li></ol><pre>schema = t.StructType([ <br>     t.StructField(&quot;field1&quot;,t.StringType(),True), <br>     t.StructField(&quot;field2&quot;,t.StringType(),True), <br>     t.StructField(&quot;field3&quot;,t.StringType(),True)<br>])<br><br>df = df.withColumn(&#39;key_str&#39;, df[&#39;key&#39;].cast(&#39;string&#39;).alias(&#39;key_str&#39;))\<br>      .drop(&#39;key&#39;)\<br>      .withColumn(&#39;value_str&#39;, df[&#39;value&#39;].cast(&#39;string&#39;).alias(&#39;key_str&#39;))\<br>      .drop(&#39;value&#39;)<br><br>df = df.withColumn(&#39;value_json&#39;, f.from_json(df[&#39;value_str&#39;], schema))</pre><p><strong>Write spark stream dataframe to bigquery</strong></p><p>After all required transformation, final dataframe will be written to bigquery. Here it requires following parameters -</p><p><strong>temporaryGcsBucket</strong> : gcs bucket for spark internal computation purpose</p><p><strong>checkpointLocation</strong> : Absolute path of checkpoint</p><p><strong>table</strong> : bigquery table name</p><pre>gcs_bucket = &quot;gcs-bucket-for-streaming&quot;<br>checkpointLocation = &quot;gs://checkpoint-gcs-bucket/checkpoint-path/&quot;<br>table = &quot;dataset_name.bigquery_table_name&quot;<br><br>output_query = df\<br>    .writeStream\<br>    .outputMode(&quot;append&quot;)\<br>    .trigger(processingTime=&quot;5 minutes&quot;)\<br>    .format(&quot;bigquery&quot;)\<br>    .option(&quot;temporaryGcsBucket&quot;,gcs_bucket)\<br>    .option(&quot;checkpointLocation&quot;, checkpointLocation)\<br>    .option(&quot;table&quot;, table)\<br>    .start()</pre><p>Last but not least</p><pre>output_query.awaitTermination()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c825b9bbe4e5" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/kafka-to-bigquery-through-pyspark-stream-c825b9bbe4e5">Kafka to Bigquery through PySpark Stream</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>