<?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 Naveen Sorout on Medium]]></title>
        <description><![CDATA[Stories by Naveen Sorout on Medium]]></description>
        <link>https://medium.com/@nksnaveen13?source=rss-1004e26d5321------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xQ0c3BpZrKQQ-vQM</url>
            <title>Stories by Naveen Sorout on Medium</title>
            <link>https://medium.com/@nksnaveen13?source=rss-1004e26d5321------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:01:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nksnaveen13/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[Merging with Precision: Data Deduplication in Databricks’ Delta Tables]]></title>
            <link>https://medium.com/@nksnaveen13/merging-with-precision-data-deduplication-in-databricks-delta-tables-2695756fa9cd?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/2695756fa9cd</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[delta-tables]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-deduplication]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 21:22:23 GMT</pubDate>
            <atom:updated>2023-08-09T21:22:23.429Z</atom:updated>
            <content:encoded><![CDATA[<p>The Delta Lake table, defined as the Delta table, is both a batch table and the streaming source and sink. The Streaming data ingest, batch historic backfill, and interactive queries all work out of the box. Delta Lake provides the ability to specify the schema and also enforce it, which further helps ensure that data types are correct and the required columns are present, which also helps in building the delta tables and also preventing the bad data from causing data corruption in both delta lake and delta table. The Delta can write the batch and the streaming data into the same table, allowing a simpler architecture and quicker data ingestion to the query result. Also, the Delta provides the ability to infer the schema for data input which further reduces the effort required in managing the schema changes. The sources can often generate duplicate log records, and the downstream deduplication steps are also needed to take care of them. The common ETL(Extract Transform and Load) use case collects the logs into the Delta, appending them to the table. So, using merge, it can be avoided inserting duplicate records. Also, the duplicate records can optimize the query further by partitioning table by date, as when it is confirmed that the duplicate records will be generated for few days, and then specifying the date range of the target table to match on.</p><h3>Implementing Merge in Delta table using Data Deduplication</h3><pre># Importing packages from delta.tables import * from pyspark.sql.functions import *</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*hHZstH_my83_UY-3Gi2e8w.png" /></figure><p>The Delta tables and PySpark SQL functions are imported to perform UPSERT(MERGE) in a Delta table in Databricks.</p><pre># Implementing Merge in Delta table using Data Deduplication # Logs deltaTable = DeltaTable.forPath(spark, &quot;/data/events_old/&quot;) # New Deduped Logs newDedupedLogs = spark.read.format(&quot;delta&quot;).load(&quot;/data/events/&quot;) # Executing merge function # Using Data Ddeduplication deltaTable.alias(&quot;logs&quot;).merge( newDedupedLogs.alias(&quot;newDedupedLogs&quot;), &quot;logs.id = newDedupedLogs.id&quot;) \ .whenNotMatchedInsertAll() \ .execute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*eWmLd-WdAe1lP7iU_DLzsg.png" /></figure><p>The Logs in a Delta table are present in the path “/data/events_old/” using the “Logs” value. The “newDedupedLogs” value contains Deduped Logs, which are further written in a Delta table stored in the path “/data/events/.” The merge function is executed using the two delta tables by matching the “logs.id” with “newDedupedLogs.id”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2695756fa9cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Change Data Capture (CDC) in Databricks’ Delta Tables]]></title>
            <link>https://medium.com/@nksnaveen13/understanding-change-data-capture-cdc-in-databricks-delta-tables-227c7a759876?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/227c7a759876</guid>
            <category><![CDATA[cdc]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 06:17:03 GMT</pubDate>
            <atom:updated>2023-08-09T06:17:03.949Z</atom:updated>
            <content:encoded><![CDATA[<p>The Delta Lake table, defined as the Delta table, is both a batch table and the streaming source and sink. The Streaming data ingest, batch historic backfill, and interactive queries all work out of the box. Delta Lake provides the ability to specify the schema and also enforce it, which further helps ensure that data types are correct and the required columns are present, which also helps in building the delta tables and also preventing the bad data from causing data corruption in both delta lake and delta table. The Delta can write the batch and the streaming data into the same table, allowing a simpler architecture and quicker data ingestion to the query result. Also, the Delta provides the ability to infer the schema for data input which further reduces the effort required in managing the schema changes. The Delta Lake is additionally integrated with Spark Structured Streaming through the “readStream” and “writeStream.” The data can be written into the Delta table using the Structured Streaming. The Change Data Capture(CDC) applies all the data changes generated from the external database into the Delta table; that is, a set of updates, deletes, and the inserts used to the external table need to be applied to the Delta table.</p><h3>Implementing Data Table CDC</h3><pre>// Importing packages import org.apache.spark.sql.functions._ import io.delta.implicits._ import io.delta.tables._</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*rEoKCDT0VgnfK457TJhSCQ.png" /></figure><p>The Spark SQL functions, Delta implicit package, and Delta table package are imported in the environment to implement CDC(Change Data Capture) in the Delta table in Databricks.</p><pre>// Implementing Delta table CDC // Implementing Delta table CDC object DeltaTableCDC extends App { val spark: SparkSession = SparkSession.builder() .master(&quot;local[1]&quot;) .appName(&quot;Spark CDC Delta table&quot;) .getOrCreate() spark.sparkContext.setLogLevel(&quot;ERROR&quot;) case class Data(key: String, value: String) // Changes in the Data defined as follows // newValue = new value for the key, or null if the key was deleted // deleted = whether key was deleted // time = timestamp needed for ordering changes, useful collapsing multiple // changes to the same key by finding the latest effective change case class ChangetheData(key: String, newValue: String, deleted: Boolean, time: Long) { assert(newValue != null ^ deleted) } // Defining the Target Delta Table val target = Seq( Data(&quot;a&quot;, &quot;0&quot;), Data(&quot;b&quot;, &quot;1&quot;), Data(&quot;c&quot;, &quot;2&quot;), Data(&quot;d&quot;, &quot;3&quot;) ).toDF().write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).saveAsTable(&quot;target&quot;) // Defining the ChangeData Delta Table val changeDataSource = Seq( ChangetheData(&quot;a&quot;, &quot;10&quot;, deleted = false, time = 0), ChangetheData(&quot;a&quot;, null, deleted = true, time = 1), // a was updated and then deleted ChangetheData(&quot;b&quot;, null, deleted = true, time = 2), // b was just deleted once ChangetheData(&quot;c&quot;, null, deleted = true, time = 3), // c was deleted and then updated twice ChangetheData(&quot;c&quot;, &quot;20&quot;, deleted = false, time = 4), ChangetheData(&quot;c&quot;, &quot;200&quot;, deleted = false, time = 5) ).toDF().createOrReplaceTempView(&quot;changes&quot;) val deltaTable = DeltaTable.forName(&quot;target&quot;) // DataFrame with the changes having the following columns // - key: key of change // - time: time of change for ordering between changes // - newValue: updated or inserted value if the key was not deleted // - deleted: true if the key was deleted, false if key was inserted or updated val changesDF = spark.table(&quot;changes&quot;) // Find latest change for each key based on the timestamp // Note: For the nested structs, max on struct is computed as // max on the first struct field, if equal fall back to second fields etc val latestChangeForEachKey = changesDF .selectExpr(&quot;key&quot;, &quot;struct(time, newValue, deleted) as otherCols&quot; ) .groupBy(&quot;key&quot;) .agg(max(&quot;otherCols&quot;).as(&quot;latest&quot;)) .selectExpr(&quot;key&quot;, &quot;latest.*&quot;) // Show latest change for each key latestChangeForEachKey.show() deltaTable.as(&quot;t&quot;) .merge( latestChangeForEachKey.as(&quot;s&quot;), &quot;s.key = t.key&quot;) .whenMatched(&quot;s.deleted = true&quot;) .delete() .whenMatched() .updateExpr(Map(&quot;key&quot; -&gt; &quot;s.key&quot;, &quot;value&quot; -&gt; &quot;s.newValue&quot;)) .whenNotMatched(&quot;s.deleted = false&quot;) .insertExpr(Map(&quot;key&quot; -&gt; &quot;s.key&quot;, &quot;value&quot; -&gt; &quot;s.newValue&quot;)) .execute() }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*wW8HGIq17O6p0QKyoAdptQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*5YOusoDlXyRp67rFALO6EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*L10aHw6Wo7N7JPCt2u4xfw.png" /></figure><p>The DeltaTableCDC object is created in which a spark session is initiated. The “Data” class and “ChangetheData” class are defined to help store data. The “Target” delta table and “ChangeData” delta table are defined to store the data. The Dataframes are defined both in delta tables that are “changesDF” values. The “latestChangeForEachKey” value is defined to store the latest changes in the “changesDF” value. Further, CDC is implemented using the merge() function with final execute() function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227c7a759876" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark and Contingency Tables: A Practical How-To Guide]]></title>
            <link>https://medium.com/@nksnaveen13/pyspark-and-contingency-tables-a-practical-how-to-guide-90b59a245499?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b59a245499</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 07:06:01 GMT</pubDate>
            <atom:updated>2023-08-08T07:06:01.128Z</atom:updated>
            <content:encoded><![CDATA[<p>Data merging and data aggregation are essential parts of big data platforms’ day-to-day activities in most big data scenarios. In this scenario, we will perform data aggregation on a DataFrame; we will create a contingency table we can also call cross-tabulation. In statistics, a contingency table (also known as a cross-tabulation or crosstab) is a type of table in a matrix format that displays the (multivariate) frequency distribution. They are heavily used in survey research, business intelligence, engineering, and scientific research. They provide a primary picture of the interrelation between two variables and can help find interactions between them.</p><h3>Step 1: Prepare a Dataset</h3><p>Here we use the users-related comma-separated values (CSV) dataset to read in a jupyter notebook from the local. Download the CSV file into your local download, download the data set which we are using in this scenario</p><p>The output of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bojvy-ccM2BJ20ldPrCtcQ.jpeg" /></figure><h3>Step 2: Import the modules</h3><p>In this scenario, we are going to import the pyspark and pyspark SQL modules and create a spark session as below :</p><pre>import pyspark from pyspark.sql import SparkSession from pyspark.sql.types import StructType,StructField, StringType, IntegerType from pyspark.sql.types import ArrayType, DoubleType, BooleanType from pyspark.sql.functions import col,array_contains from pyspark.sql.types import * from pyspark.sql.functions import *</pre><p>Create a spark session and Read the CSV file from the local as below</p><pre>spark = SparkSession.builder.appName(&#39;ContingencyTable&#39;).getOrCreate() Usersdf = spark.read.option(&quot;Delimiter&quot;, &quot;,&quot;).csv(&quot;/home/bigdata/Downloads/users.csv&quot;) Usersdf.printSchema()</pre><p>The output of the above lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*u3xCpbB4oB6Y0B1GQqwPjQ.jpeg" /></figure><p>To show the top five lines from the dataframe as shown below:</p><pre>Usersdf.show(5)</pre><p>The output of the above lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPVBhqPQyM7VjYG8F1d0dA.jpeg" /></figure><h3>Step 3: Create a schema</h3><p>Here we are creating a StructField for each column. Then we will develop a schema of the full DataFrame. We can create that using a StructType object,</p><p>as the following code line as below:</p><pre>id = StructField(&quot;id&quot;,IntegerType(),True) title = StructField(&quot;title&quot;,StringType(),True) first = StructField(&quot;first&quot;,StringType(),True) last = StructField(&quot;last&quot;,StringType(),True) street = StructField(&quot;street&quot;,StringType(),True) city = StructField(&quot;city&quot;,StringType(),True) state = StructField(&quot;state&quot;,StringType(),True) zip = StructField(&quot;zip&quot;,IntegerType(),True) gender = StructField(&quot;gender&quot;,StringType(),True) email = StructField(&quot;email&quot;,StringType(),True) username = StructField(&quot;username&quot;,StringType(),True) password = StructField(&quot;password&quot;,StringType(),True) phone = StructField(&quot;phone&quot;,StringType(),True) cell = StructField(&quot;cell&quot;,StringType(),True) ssn = StructField(&quot;ssn&quot;,StringType(),True) date_of_birth = StructField(&quot;date_of_birth&quot;,StringType(),True) reg_date = StructField(&quot;reg_date&quot;,StringType(),True) large = StructField(&quot;large&quot;,StringType(),True) medium = StructField(&quot;medium&quot;,StringType(),True) thumbnail = StructField(&quot;thumbnail&quot;,StringType(),True) version = StructField(&quot;version&quot;,IntegerType(),True) nationality = StructField(&quot;nationality&quot;,StringType(),True)</pre><p>Then we specify the columns into a variable as below:</p><pre>columnList = [id,title,first,last,street,city,state,zip,gender,email,username,password,phone,cell,ssn,date_of_birth,reg_date,large,medium,thumbnail,version,nationality] UsersDfSchema = StructType(columnList)</pre><p>To Print the dataframe to check the schema, output of the structure :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xj3tkWsEj5-e7Gg9D8Q7WQ.jpeg" /></figure><h3>Step 4: Read CSV file</h3><p>Here we are going to read the CSV file from local where we downloaded the file, and also we are specifying the above-created schema to CSV file as below code :</p><pre>usersDf = spark.read.csv(&#39;/home/bigdata/Downloads/users.csv&#39;, header=True,schema=UsersDfSchema)</pre><p>In the above lines, we are reading the CSV file and storing it as a dataframe</p><p>To print the top 4 lines from usersDf dataframe as below</p><pre>usersDf.show(4)</pre><p>The output of the above line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWAAeNFW9UUUE6L45xRZfw.jpeg" /></figure><p>To print the schema of the dataframe as shown below:</p><pre>usersDf.printSchema()</pre><p>The output of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywgy0y9OGFQL3e34ynMokg.jpeg" /></figure><h3>Step 5: To Create a Contingency Table</h3><p>We can use a contingency table to compute the probabilities of various events by calculating the ratios between counts. Contingency tables (also called crosstabs or two-way tables) are used in statistics to summarize the relationship between several categorical variables.</p><p>We are going to drop the not required columns as below :</p><pre>userDf = usersDf.drop(&quot;id&quot;,&quot;cell&quot;,&quot;ssn&quot;,&quot;date_of_birth&quot;,&quot;city&quot;,&quot;version&quot;,&quot;password&quot;,&quot;reg_date&quot;,&quot;large&quot;,&quot;medium&quot;,&quot;thumbnail&quot;)</pre><p>To print the top 5 rows from dataframe</p><pre>userDf.show(5)</pre><p>The output of the above lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrA21A34wQcrLDTe_OQsrQ.jpeg" /></figure><p>Now we are going to create a contingency table. For that, we will use the crosstab() function. This function takes two columns as arguments as shown below:</p><pre>userDf.crosstab(&quot;gender&quot;,&quot;nationality&quot;).show()</pre><p>The output of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmPMYVxGI8VMMYwGltpRJQ.jpeg" /></figure><p>We are going to the same table for the other two columns</p><pre>userDf.crosstab(&quot;state&quot;,&quot;gender&quot;).show()</pre><p>The output of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wm9TYBJ_WFDourRf4zaoGw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b59a245499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of Spark in Airflow: The SparkSubmitOperator Explained]]></title>
            <link>https://medium.com/@nksnaveen13/harnessing-the-power-of-spark-in-airflow-the-sparksubmitoperator-explained-692dcf28a311?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/692dcf28a311</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 22:46:38 GMT</pubDate>
            <atom:updated>2023-08-06T22:46:38.379Z</atom:updated>
            <content:encoded><![CDATA[<p>In big data scenarios, we schedule and run your complex data pipelines. To ensure that each task of your data pipeline will get executed in the correct order and each task gets the required resources, Apache Airflow is the best open-source tool to schedule and monitor. Airflow represents workflows as Directed Acyclic Graph. Essentially this means workflows are represented by a set of tasks and dependencies between them.</p><p>In this scenario, we will schedule a dag file to submit and run a spark job using the SparkSubmitOperator.</p><p>Before you create the dag file, create a pyspark job file as below in your local</p><pre>sudo gedit sparksubmit_basic.py</pre><p>In this sparksubmit_basic.py file, we are using sample code to word and line count program.</p><pre>from pyspark import SparkContext logFilepath = &quot;file:////home/hduser/wordcount.txt&quot; sc = SparkContext(&quot;local&quot;, &quot;first app&quot;) logData = sc.textFile(logFilepath).cache() numAs = logData.filter(lambda s: &#39;a&#39; in s).count() numBs = logData.filter(lambda s: &#39;b&#39; in s).count() print(&quot;Lines with a: %i, lines with b: %i&quot; % (numAs, numBs))</pre><p>As you see above, we are using some text files to use to count. Create a text file, add some text and give the path as above.</p><p>To create a dag file in /airflow/dags folder using the below command as follows.</p><pre>sudo gedit sparkoperator_demo.py<br></pre><p>After making the dag file in the dags folder, follow the below steps to write a dag file.</p><h3>Step 1: Importing modules</h3><p>Import Python dependencies needed for the workflow</p><pre>import airflow from datetime import timedelta from airflow import DAG from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator from airflow.utils.dates import days_ago</pre><h3>Step 2: Default Arguments</h3><p>Define default and DAG-specific arguments</p><pre>default_args = { &#39;owner&#39;: &#39;airflow&#39;, #&#39;start_date&#39;: airflow.utils.dates.days_ago(2), # &#39;end_date&#39;: datetime(), # &#39;depends_on_past&#39;: False, # &#39;email&#39;: [&#39;airflow@example.com&#39;], # &#39;email_on_failure&#39;: False, #&#39;email_on_retry&#39;: False, # If a task fails, retry it once after waiting # at least 5 minutes #&#39;retries&#39;: 1, &#39;retry_delay&#39;: timedelta(minutes=5), }</pre><h3>Step 3: Instantiate a DAG</h3><p>Give the DAG name, configure the schedule, and set the DAG settings</p><pre>dag_spark = DAG( dag_id = &quot;sparkoperator_demo&quot;, default_args=args, # schedule_interval=&#39;0 0 * * *&#39;, schedule_interval=&#39;@once&#39;, dagrun_timeout=timedelta(minutes=60), description=&#39;use case of sparkoperator in airflow&#39;, start_date = airflow.utils.dates.days_ago(1) )</pre><p>we can schedule by giving preset or cron format as you see in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*HcLfwnZg1GlXBXuQKvOxuw.png" /></figure><p>Note: Use schedule_interval=None and not schedule_interval=’None’ when you don’t want to schedule your DAG.</p><h3>Step 4: Set the Tasks</h3><p>The next step is setting up the tasks which want all the tasks in the workflow. Here in the code, spark_submit_local code is a task created by instantiating.</p><pre>spark_submit_local = SparkSubmitOperator( application =&#39;/home/hduser/basicsparksubmit.py&#39; , conn_id= &#39;spark_local&#39;, task_id=&#39;spark_submit_task&#39;, dag=dag_spark )</pre><h3>Step 5: Setting up Dependencies</h3><p>Here we are Setting up the dependencies or the order in which the tasks should be executed. Here are a few ways you can define dependencies between them:</p><pre>spark_submit_local if __name__ == &quot;__main__&quot;: dag_spark.cli()</pre><p>The above code lines explain that spark_submit_local will execute. A DAG is just a Python file used to organize tasks and set their execution context. DAGs do not perform any actual computation.</p><p>Instead, tasks are the element of Airflow that actually “do the work” we want to be performed. And it is your job to write the configuration and organize the tasks in specific orders to create a complete data pipeline.</p><h3>Step 6: Creating the connection.</h3><p>Creating the connection airflow to connect the spark as shown in below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*HoP4Nsj-Rcu8uf1XEkDjWw.jpeg" /></figure><p>Go to the admin tab select the connections; then, you will get a new window to create and pass the details of the hive connection as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKzhzjgI8InII3PbCsB2QA.jpeg" /></figure><p>Click on the plus button beside the action tab to create a connection in Airflow to connect spark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zq2femNRsu23hK46yzEMgQ.jpeg" /></figure><p>Give the conn Id what you want and the select hive for the connType and give the Host and then specify Host and specify the spark home in the extra.</p><h3>Step 7: Verifying the tasks</h3><p>In the below, as seen that we unpause the sparkoperator _demo dag file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pvJ7Gx2a2B_yf5QlCuoBw.jpeg" /></figure><p>Click on the “sparkoperator_demo” name to check the dag log file and then select the graph view; as seen below, we have a task called spark_submit_task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQsXt9se9vkYhMhRfRjDCw.jpeg" /></figure><p>To check the log file how the query ran, click on the spark_submit_task in graph view, then you will get the below window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SH6vK3SY6ZoaAUidQVDIZQ.jpeg" /></figure><p>Click on the log tab to check the log file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTDKEjCATsygi_kDcjmwRQ.jpeg" /></figure><p>The above log file shows that the task is started running, and the below image shows the task’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4fvyEie-Rq9DzKaFrY-Ag.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692dcf28a311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next-Level Data Management: Saving DataFrames to MongoDB using PySpark]]></title>
            <link>https://medium.com/@nksnaveen13/next-level-data-management-saving-dataframes-to-mongodb-using-pyspark-a377a2542af6?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/a377a2542af6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 03:17:12 GMT</pubDate>
            <atom:updated>2023-06-03T03:17:12.412Z</atom:updated>
            <content:encoded><![CDATA[<p>In most big data scenarios, a DataFrame in Apache Spark can be created in multiple ways: It can be created using different data formats. For example, loading the data from JSON, CSV. Data merging and data aggregation are an essential part of the day-to-day activities in big data platforms. In this scenario, we will load the data frame to the MongoDB database table or save the dataframe to the table.</p><h3>Step 1: Import the modules</h3><p>In this scenario, we are going to import the pyspark and pyspark SQL modules and create a spark session as below:</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql import Row</pre><pre>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;mongodbtest1&quot;) \<br>    .master(&#39;local&#39;)\<br>    .config(&quot;spark.mongodb.input.uri&quot;, &quot;mongodb://hduser:bigdata@127.0.0.1:27017/dezyre&quot;) \<br>    .config(&quot;spark.mongodb.output.uri&quot;, &quot;mongodb://hduser:bigdata@127.0.0.1:27017/dezyre&quot;) \<br>    .config(&#39;spark.jars.packages&#39;, &#39;org.mongodb.spark:mongo-spark-connector_2.12:3.0.1&#39;) \<br>    .getOrCreate()</pre><h3>Step 2: Create Dataframe to store in MongoDB</h3><p>Here we will create a dataframe to save in a MongoDB table for that The Row class is in the pyspark.sql submodule. As shown above, we import the Row from class.</p><pre>studentDf = spark.createDataFrame([<br>    Row(id=1,name=&#39;vijay&#39;,marks=67),<br>    Row(id=2,name=&#39;Ajay&#39;,marks=88),<br>    Row(id=3,name=&#39;jay&#39;,marks=79),<br>    Row(id=4,name=&#39;binny&#39;,marks=99),<br>    Row(id=5,name=&#39;omair&#39;,marks=99),<br>    Row(id=6,name=&#39;divya&#39;,marks=98),<br>])</pre><h3>Step 3: To view the Schema</h3><p>Here we will read the schema of the stored table as a dataframe, as shown below.</p><pre>studentDf.printSchema()</pre><p>The output of the schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8h4tIJVM1S2ds1TonP2Xw.jpeg" /></figure><p>Here we are going to view the data top 5 rows in the dataframe as shown below.</p><pre>studentDf.show(5)</pre><p>The output of the dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL3c0ISEhaJDTi350tR32A.jpeg" /></figure><h3>Step 4: To Save Dataframe to MongoDB Table</h3><p>Here we are going to save the dataframe to the mongo database table which we created earlier. To save, we need to use a write and save method as shown in the below code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmWjx-ZTW3eNmjW_6jdEdQ.jpeg" /></figure><p>To check the output of the saved data frame in the MongoDB table, login to the MongoDB database. The output of the saved dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuTAJ7HJoihFVNzvy52Ekw.jpeg" /></figure><p>As shown in the above image, we have written the dataframe to create a table in the MongoDB database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a377a2542af6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating Date Differences and Months Between with PySpark in Databricks: A Comprehensive Guide]]></title>
            <link>https://medium.com/towards-data-engineering/calculating-date-differences-and-months-between-with-pyspark-in-databricks-a-comprehensive-guide-63607db36e0e?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/63607db36e0e</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-processing]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 02:57:27 GMT</pubDate>
            <atom:updated>2023-12-29T04:11:52.515Z</atom:updated>
            <content:encoded><![CDATA[<p>The date diff() function in Pyspark is popularly used to get the difference of dates and the number of days between the dates specified. The “datediff(date, date)” is the syntax of the datediff() function where the first argument specifies the input of the Date and the Second argument specifies an additional Date argument from which the first argument is differentiated. The months_between() function in Apache PySpark is popularly used to get the difference of dates and the number of months between the dates specified. The “months_between(date, date)” is the syntax of the months_between() function where the first argument specifies the input of the Date and the Second argument specifies an additional Date argument from which the first argument is differentiated.</p><h3>Implementing the datediff() and months_between() function in Databricks in PySpark</h3><pre># Importing package<br>import pyspark.sql<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import *</pre><p>The SparkSession and all packages are imported in the environment to perform usage of datediff() and months_between() functions in PySpark</p><pre># Implementing CSV file in PySpark <br><br>spark = SparkSession.builder.appName(&#39;PySpark Read CSV&#39;).getOrCreate()<br><br># Reading csv file<br>dataframe = spark.read.csv(&quot;/FileStore/tables/zipcodes-2.csv&quot;)<br>dataframe.printSchema()<br><br># Using header record for the column names<br>dataframe2 = spark.read.option(&quot;header&quot;,True) \<br>              .csv(&quot;/FileStore/tables/zipcodes-2.csv&quot;)<br>dataframe2.printSchema()<br>   <br># Using delimiter<br>dataframe3 = spark.read.options(header=&#39;True&#39;, delimiter=&#39;,&#39;) \<br>              .csv(&quot;/FileStore/tables/zipcodes-2.csv&quot;)<br>dataframe3.printSchema()<br><br># Writing pyspark dataframe to csv file<br>dataframe3.write.option(&quot;header&quot;,True) \<br> .csv(&quot;/FileStore/tables/zipcodes-345.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*PGObQ1ujPfv8tazwTh72cQ.png" /></figure><p>The “dataframe” value is created in which the data is defined. Using the date diff() function to get the difference of dates is getting the number of days between the dates specified. Further, alias like “datediff” is defined to identify the datediff() function output column easily. Using the months_between() function, getting the difference of dates is getting the number of months between the dates specified. The alias like “Dates_Diff”, “Months_Diff”, “Months_Diff_round”, “Years_Diff” and “Years_Diff_round” are defined to define the output of months_between() function. The “dataframe2” value is created in which the data is defined not in their default format of “YYYY-MM-DD.” The input dates are converted to their default format of “YYYY-MM-DD” using the to_date() function on the dataframe2 else; the output will be NULL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63607db36e0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/calculating-date-differences-and-months-between-with-pyspark-in-databricks-a-comprehensive-guide-63607db36e0e">Calculating Date Differences and Months Between with PySpark in Databricks: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Text to Time: Mastering String to Timestamp Conversion in PySpark and Databricks]]></title>
            <link>https://medium.com/@nksnaveen13/from-text-to-time-mastering-string-to-timestamp-conversion-in-pyspark-and-databricks-fb593eff8562?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb593eff8562</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[trending]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 02:52:14 GMT</pubDate>
            <atom:updated>2023-06-01T02:52:14.102Z</atom:updated>
            <content:encoded><![CDATA[<p>The to_timestamp() function in Pyspark is popularly used to convert String to the Timestamp(i.e., Timestamp Type). The default format of the Timestamp is “MM-dd-yyyy HH:mm: ss.SSS,” and if the input is not in the specified form, it returns Null. The “to_timestamp(timestamping: Column, format: String)” is the syntax of the Timestamp() function where the first argument specifies the input of the timestamp string that is the column of the dataframe. The Second argument specifies an additional String argument which further defines the format of the input Timestamp and helps in the casting of the String from any form to the Timestamp type in the PySpark.</p><h3>Implementing the to_timestamp() functions in Databricks in PySpark</h3><pre># Importing packages<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import *</pre><p>The SparkSession and all packages are imported in the environment to perform conversion of string to timestamp function in PySpark.</p><pre><br># Implementing String to Timestamp in Databricks in PySpark<br><br>spark = SparkSession.builder \<br>          .appName(&#39;PySpark String to Timestamp&#39;) \<br>          .getOrCreate()<br><br>dataframe = spark.createDataFrame(<br>        data = [ (&quot;1&quot;,&quot;2021-08-26 11:30:21.000&quot;)],<br>        schema=[&quot;id&quot;,&quot;input_timestamp&quot;])<br>dataframe.printSchema()<br><br># Converting String to Timestamp<br>dataframe.withColumn(&quot;timestamp&quot;,to_timestamp(&quot;input_timestamp&quot;)) \<br>  .show(truncate=False)<br>  <br># Using Cast to convert String to Timestamp<br>dataframe.withColumn(&#39;timestamp&#39;, \<br>         to_timestamp(&#39;input_timestamp&#39;).cast(&#39;string&#39;)) \<br>  .show(truncate=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*VpI91mN7T6jXl7ZZ4bjn3g.png" /></figure><p>The “dataframe” value is created in which the data is defined — using the to_timestamp() function that is converting the String to Timestamp (TimestampType) in the PySpark. Using the cast() function, the conversion of string to timestamp occurs when the timestamp is not in the custom format and is first converted into the appropriate timestamp format.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb593eff8562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Timestamp to Date Conversion in PySpark: Unlocking Time-Based Insights with Databricks]]></title>
            <link>https://medium.com/towards-data-engineering/mastering-timestamp-to-date-conversion-in-pyspark-unlocking-time-based-insights-with-databricks-eeddb1532782?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeddb1532782</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Wed, 31 May 2023 02:47:10 GMT</pubDate>
            <atom:updated>2023-12-29T04:12:12.947Z</atom:updated>
            <content:encoded><![CDATA[<p>The to_date() function in Apache PySpark is popularly used to convert Timestamp to the date. This is mainly achieved by truncating the Timestamp column’s time part. The to_date() function takes TimeStamp as its input in the default format of “MM-dd-yyyy HH:mm:ss.SSS”. The Timestamp Type(timestamp) is also defined as input of the to_date() function in the format of “MM-dd-yyyy HH:mm:ss”. The “to_date(timestamping: Column, format: Timestamp)” is the syntax of the to_date() function where the first argument specifies the input of the timestamp string that is the column of the dataframe. The Second argument specifies an additional Timestamp argument that further specifies the input Timestamp format and helps cast the Timestamp from any format to the Default Timestamp type in the PySpark.</p><h3>Implementing The to_date() Function In PySpark Using Databricks</h3><pre># Importing package<br>import pyspark.sql<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import *</pre><p>The SparkSession and all packages are imported into the environment to convert Timestamp to Date in PySpark.</p><pre># Implementing the to_date() function in Databricks in PySpark<br><br>spark = SparkSession.builder \<br>          .appName(&#39;PySpark to_date()&#39;) \<br>          .getOrCreate()<br><br>dataframe = spark.createDataFrame(<br>        data = [ (&quot;1&quot;,&quot;2021-08-26 11:30:21.000&quot;)],<br>        schema=[&quot;id&quot;,&quot;input_timestamp&quot;])<br>dataframe.printSchema()<br><br># Converting Timestamp String to DateType<br>dataframe.withColumn(&quot;date_type&quot;,to_date(&quot;input_timestamp&quot;)) \<br>  .show(truncate=False)<br><br># Coverting Timestamp Type to DateType<br>dataframe.withColumn(&quot;date_type&quot;,to_date(current_timestamp())) \<br>  .show(truncate=False) <br><br># Converting Timestamp Type(timestamp) to Datatype<br>dataframe.withColumn(&quot;ts&quot;,to_timestamp(col(&quot;input_timestamp&quot;))) \<br>  .withColumn(&quot;datetype&quot;,to_date(col(&quot;ts&quot;))) \<br>  .show(truncate=False)<br><br># Using Cast to convert the Timestamp String to DateType<br>dataframe.withColumn(&#39;date_type&#39;, col(&#39;input_timestamp&#39;).cast(&#39;date&#39;)) \<br>       .show(truncate=False)<br><br># Using Cast to convert the TimestampType to DateType<br>dataframe.withColumn(&#39;date_type&#39;, to_timestamp(&#39;input_timestamp&#39;).cast(&#39;date&#39;)) \<br>  .show(truncate=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*fbVVFnY6J_cj14oudqNiEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*y_VVR11QVnsBcCpC29lHQA.png" /></figure><p>The “dataframe” value is created in which the data is defined — using the to_date() function converting the Timestamp String to Datatype, TimeString to Timestamp (TimestampType) in the PySpark. Using the cast() function, the string conversion to timestamp occurs when the timestamp is not in the custom format and is first converted into the appropriate one.</p><h3>How To Convert The Timestamp Datatype In PySpark?</h3><p>In PySpark, the TimestampType is used to represent date and time values. To convert a timestamp from one format to another, you can use the to_timestamp function provided by PySpark. This function takes two arguments: the timestamp column you want to convert and the format to which you want to convert it.</p><p>For example, if you have a timestamp column called my_timestamp in the format ‘yyyy-MM-dd HH:mm:ss’ and you want to convert it to the format ‘yyyy-MM-dd’, you can use the following code:</p><p><em>from pyspark.sql.functions import to_timestamp</em></p><p><em>df = df.withColumn(“new_timestamp”, to_timestamp(“my_timestamp”, “yyyy-MM-dd”).cast(“timestamp”))</em></p><p>Here, we first import the to_timestamp function and then apply it to the my_timestamp column. We specify the format we want to convert to as “yyyy-MM-dd”. Finally, we cast the result to the TimestampType. The resulting column is added to the dataframe as new_timestamp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeddb1532782" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/mastering-timestamp-to-date-conversion-in-pyspark-unlocking-time-based-insights-with-databricks-eeddb1532782">Mastering Timestamp to Date Conversion in PySpark: Unlocking Time-Based Insights with Databricks</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Date to String Conversion in PySpark: Unleashing the Power of Data Transformation in Databricks]]></title>
            <link>https://medium.com/@nksnaveen13/date-to-string-conversion-in-pyspark-unleashing-the-power-of-data-transformation-in-databricks-c076355546f8?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/c076355546f8</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[big-dat]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Tue, 30 May 2023 01:41:46 GMT</pubDate>
            <atom:updated>2023-05-30T01:41:46.527Z</atom:updated>
            <content:encoded><![CDATA[<p>The date_format() function in Apache Pyspark is popularly used to convert the DataFrame column from the Date to the String format. The date_format() function supports all the Java Date formats. The “date_format(column, format)” is the syntax of the date_format() function where the first argument specifies the input of the Date that is the column of the dataframe, and the Second argument specifies an additional Date argument which further defines the format of the input Date in the PySpark.</p><h3>Implementing the date_format() function in Databricks in PySpark</h3><pre># Importing package<br>import pyspark.sql<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import *</pre><p>The SparkSession and all packages are imported in the environment to perform conversion of Date to String in PySpark.</p><pre># Implementing the date_format() function in Databricks in PySpark<br>spark = SparkSession.builder \<br>.appName(&#39;PySpark date_format()&#39;) \<br>.getOrCreate()<br># Defining dataframe<br>dataframe = spark.createDataFrame([[&quot;1&quot;]],[&quot;id&quot;])<br># Using date_format() format<br>dataframe.select(current_date().alias(&quot;Current_Date&quot;), \<br>date_format(current_date(),&quot;yyyy MM dd&quot;).alias(&quot;yyyy MM dd&quot;), \<br>date_format(current_timestamp(),&quot;MM/dd/yyyy hh:mm&quot;).alias(&quot;MM/dd/yyyy&quot;), \<br>date_format(current_timestamp(),&quot;yyyy MMM dd&quot;).alias(&quot;yyyy MMMM dd&quot;), \<br>date_format(current_timestamp(),&quot;yyyy MMMM dd F&quot;).alias(&quot;yyyy MMMM dd F&quot;) \<br>).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*PGObQ1ujPfv8tazwTh72cQ.png" /></figure><p>The “dataframe” value is created in which the data is defined. The date_format() function converts the DataFrame column from the Date to the String format. Further, alias like “MM/dd/yyyy,” “yyyy MMMM dd F,” etc., are also defined to quickly identify the column names and the generated outputs by date_format() function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c076355546f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Real-Time Insights: A Guide to Initiating Streaming Queries in Pyspark]]></title>
            <link>https://medium.com/@nksnaveen13/unlocking-real-time-insights-a-guide-to-initiating-streaming-queries-in-pyspark-39f28219e109?source=rss-1004e26d5321------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f28219e109</guid>
            <dc:creator><![CDATA[Naveen Sorout]]></dc:creator>
            <pubDate>Mon, 29 May 2023 01:37:10 GMT</pubDate>
            <atom:updated>2023-05-29T01:37:10.111Z</atom:updated>
            <content:encoded><![CDATA[<p>In most big data scenarios, data merging and data aggregation are an essential part of the day-to-day activities in big data platforms. Spark Streaming is an extension of the core Spark API that allows data engineers and data scientists to process real-time data from various sources, including (but not limited to) Kafka, Flume, and Amazon Kinesis. This processed data can be pushed out to file systems, databases, and live dashboards. In this scenario, we are going to initiate a streaming query in Pyspark.</p><h3>Step 1: Import the modules</h3><p>In this scenario, we are going to import the pyspark and pyspark SQL modules and create a spark session as below :</p><pre>Import pyspark from pyspark.sql import SparkSession from pyspark.sql.types import StructType spark = SparkSession.builder\ .master(&quot;local&quot;).appName(&quot;pyspark_stream_setup&quot;).getOrCreate()</pre><h3>Step 2: Create Schema</h3><p>Here we are going to create a schema and assign it to the newly created DataFrame.</p><pre>schooldrivers_Schema = StructType() \ .add(&quot;school_year&quot;, &quot;string&quot;)\ .add(&quot;vendor_name&quot;, &quot;string&quot;)\ .add(&quot;type_of_service&quot;, &quot;string&quot;)\ .add(&quot;active_employees&quot;, &quot;string&quot;)\ .add(&quot;job_type&quot;, &quot;string&quot;)</pre><p>Then we are going to print the content of the schema. Please follow the below code.</p><pre>schooldrivers_Schema.simpleString()</pre><p>The output of the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RV3GBHNF-mwg1wR3lHb3Jw.jpeg" /></figure><p>In the output, we can see both the columns just added in the schema.</p><h3>Step 3: Create Dataframe from Streaming</h3><p>Here we are going to create the DataFrame from streaming as shown in the below code</p><pre>schooldrivers_stream_Df = spark.readStream\ .option(&quot;sep&quot;, &quot;,&quot;)\ .schema(schooldrivers_Schema)\ .csv(&quot;/home/hduser/school_drives&quot;)</pre><p>To make sure the DataFrame is in streaming mode, we use the isStreaming method shown below here.</p><pre>schooldrivers_stream_Df.isStreaming</pre><p>The output of the dataframe is in streaming mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yn6WBVdv-Gn9YCUZjrNPzA.jpeg" /></figure><h3>Step 4: Write to Stream</h3><p>Here we will create a stream using the writeStream method, which will write into the console and keep on appending the incoming data.</p><pre>query = schooldrivers_stream_Df.writeStream\ .format(&quot;console&quot;).outputMode(&quot;append&quot;).start()</pre><p>When you run code, you will not see any output. When you place the drivers-1.csv file into the school_drivers directory, notice what happens then. You can observe the following output in the console where you start the jupyter notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGihdh5-Pa5_V3fcgy-2Cw.jpeg" /></figure><p>The output of the streaming data: when we placed drivers-1.csv, it gave an output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YN-4KYtf-Hu5XkV9spEUNQ.jpeg" /></figure><h3>Conclusion</h3><p>Here we learned to Initiate a streaming query in Pyspark.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f28219e109" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>