<?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 krishnaprasad k on Medium]]></title>
        <description><![CDATA[Stories by krishnaprasad k on Medium]]></description>
        <link>https://medium.com/@krishnaprasad-k?source=rss-119ec0c9b3a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*U-sz0-zQNeBAy2ZM.</url>
            <title>Stories by krishnaprasad k on Medium</title>
            <link>https://medium.com/@krishnaprasad-k?source=rss-119ec0c9b3a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:18:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishnaprasad-k/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[Apache Spark 4.0: Key Features]]></title>
            <link>https://krishnaprasad-k.medium.com/apache-spark-4-0-key-features-3c6371594c1a?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6371594c1a</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 13:34:00 GMT</pubDate>
            <atom:updated>2025-11-29T13:37:13.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark 4.0 marks a vital step forward for the analytics engine. We’ll explore the most impactful changes, specifically in <strong>SQL expressiveness</strong> and the <strong>Python API</strong>, which aim to boost productivity of data engineers and enhances data integrity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVukeuNdVQlfrgl3SsJERg.png" /></figure><h3>SQL Enhancements</h3><p>In the below examplea we will be using delivery logistics data for our examples.</p><p><a href="https://www.kaggle.com/datasets/kundanbedmutha/delivery-logistics-dataset-india-multi-partner">Delivery Logistics Dataset (India - Multi-Partner)</a></p><pre>scala&gt; val df=spark.read.option(&quot;header&quot;, &quot;true&quot;).csv(&quot;/spark_4_test/dataset/Delivery_Logistics.csv&quot;)<br>val df: org.apache.spark.sql.DataFrame = [delivery_id: string, delivery_partner: string ... 13 more fields]<br><br>scala&gt; df.printSchema<br> |-- delivery_id: string (nullable = true)<br> |-- delivery_partner: string (nullable = true)<br> |-- package_type: string (nullable = true)<br> |-- vehicle_type: string (nullable = true)<br> |-- delivery_mode: string (nullable = true)<br> |-- region: string (nullable = true)<br> |-- weather_condition: string (nullable = true)<br> |-- distance_km: string (nullable = true)<br> |-- package_weight_kg: string (nullable = true)<br> |-- delivery_time_hours: string (nullable = true)<br> |-- expected_time_hours: string (nullable = true)<br> |-- delayed: string (nullable = true)<br> |-- delivery_status: string (nullable = true)<br> |-- delivery_rating: string (nullable = true)<br> |-- delivery_cost: string (nullable = true)</pre><p><strong>SQL pipe syntax</strong></p><p>Spark 4.0 introduces a new <strong>PIPE</strong> (|&gt;) syntax that lets you chain SQL operations more naturally. Here’s an example demonstrating how to use the pipe operator to perform data aggregations:</p><pre>scala&gt; spark.sql(&quot;select delivery_id from delivery_logistics |&gt; AGGREGATE count(delivery_id)&quot;).show()<br>+------------------+<br>|count(delivery_id)|<br>+------------------+<br>|             25000|<br>+------------------+</pre><p><strong>SQL User Defined Functions</strong></p><p>Spark 4.0 introduces SQL UDFs, enabling users to define reusable custom functions directly in SQL. These functions simplify <strong>complex logic, improve maintainability</strong>, and integrate seamlessly with Spark’s query optimizer, enhancing query performance compared to traditional code-based UDFs.</p><pre>CREATE <br>OR REPLACE TEMPORARY FUNCTION from_delivery_id(delivery_id STRING) RETURNS STRING READS SQL DATA SQL SECURITY DEFINER RETURN <br>SELECT <br>  FIRST(delivery_partner) <br>FROM <br>  delivery_logistics <br>WHERE <br>  delivery_id = from_delivery_id.delivery_id</pre><pre>scala&gt; spark.sql(&quot;select from_delivery_id(&#39;373.0&#39;)&quot;).show()<br>+-----------------------+<br>|from_delivery_id(373.0)|<br>+-----------------------+<br>|                    dhl|<br>+-----------------------+<br><br><br>scala&gt; spark.sql(&quot;select from_delivery_id(&#39;4856.0&#39;)&quot;).show()<br>+------------------------+<br>|from_delivery_id(4856.0)|<br>+------------------------+<br>|              xpressbees|</pre><p><strong>Session Variables</strong></p><p>Spark 4.0 introduces session local variables, which can be used to keep and manage state within a session without using host language variables.</p><pre>DECLARE <br>or replace tomorrow DATE DEFAULT current_date + INTERVAL &#39;1&#39; DAY &quot;</pre><pre>scala&gt; spark.sql(&quot;select tomorrow&quot;).show()<br>+----------+<br>|  tomorrow|<br>+----------+<br>|2025-11-30|</pre><p><strong>Parameter markers</strong></p><p>Spark 4.0 introduces named (“:var”) and unnamed (“?”) style parameter markers.</p><p>This feature allows you to parameterize queries.</p><p><strong>Named markers</strong></p><p>Allows parameters to be passed as a python dict.</p><pre>&gt;&gt;&gt; spark.sql(&quot;SELECT :x * :y * :z AS volume&quot;, args = { &quot;x&quot; : 3, &quot;y&quot; : 4, &quot;z&quot; : 5 }).show()<br>+------+<br>|volume|<br>+------+<br>|    60|<br>+------+</pre><p><strong>Unnamed markers</strong></p><p>Allows parameter to be passed as a list</p><pre>&gt;&gt;&gt; spark.sql(&quot;SELECT ? * ? * ? AS volume&quot;, args = [ 3, 4, 5 ]).show()<br>+------+<br>|volume|<br>+------+<br>|    60|<br>+------+</pre><h3>Python API Advances</h3><p>Python users have even more to celebrate with the release of Spark 4.0. This update introduces several features designed to make Spark more Pythonic and significantly improve performance.</p><p><strong>Python Data Source API</strong></p><p>Python Data Source APIs make it possible to integrate PySpark with a wide range of data sources, including custom ones. In the example below, we demonstrate how to connect PySpark with the <strong>faker</strong> library to generate sample data.</p><p>In a later article, we will cover how to define custom data sources in PySpark in more detail</p><pre>from pyspark_datasources.fake import FakeDataSource<br>spark.dataSource.register(FakeDataSource)<br><br>&gt;&gt;&gt; spark.read.format(&quot;fake&quot;).load().show()<br>+-----------------+----------+-------+-------------+<br>|             name|      date|zipcode|        state|<br>+-----------------+----------+-------+-------------+<br>|    Jamie Francis|2007-12-12|  05888|     Nebraska|<br>|      Jill Murphy|1981-07-14|  15790|    Wisconsin|<br>|Virginia Franklin|1972-09-19|  03878|New Hampshire|<br>+-----------------+----------+-------+-------------+</pre><p><strong>Python User Defined Table Functions(UDTFs)</strong></p><p><strong>PySpark </strong>now supports User-Defined Table Functions in Python. You can create a Python class as a <strong>UDTF </strong>using a decorator that yields an iterator of output rows, and register it so it can be called from Spark SQL or the DataFrame API.</p><p>A user-defined table function (UDTF) allows you to register functions that return tables instead of scalar values.</p><pre>from pyspark.sql.functions import lit, udtf<br><br>@udtf(returnType=&quot;sum: int, diff: int&quot;)<br>class GetSumDiff:<br>    def eval(self, x: int, y: int):<br>        yield x + y, x - y<br><br>&gt;&gt;&gt; GetSumDiff(lit(1), lit(2)).show()<br>+---+----+<br>|sum|diff|<br>+---+----+<br>|  3|  -1|<br>+---+----+</pre><p><strong>Native Plotting Support</strong></p><p>Data exploration in PySpark just got easier — Spark 4.0 adds native plotting capabilities to PySpark DataFrames.</p><pre>data = [(&quot;A&quot;, 10, 1.5), (&quot;B&quot;, 30, 2.5), (&quot;C&quot;, 20, 3.5)]<br>columns = [&quot;category&quot;, &quot;int_val&quot;, &quot;float_val&quot;]<br><br>df = spark.createDataFrame(data, columns)<br><br>df.plot.bar(x=&quot;category&quot;, y=&quot;int_val&quot;).show() // bar chart<br>df.plot.scatter(x=&quot;category&quot;, y=&quot;int_val&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6_PK3pSOCuSdIFVIy-WwA.png" /><figcaption>Scatter plot example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCam_XR0fxxyX8qEQh_XEQ.png" /><figcaption>Bar chart example</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6371594c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Airflow for Modern RAG Pipelines]]></title>
            <link>https://krishnaprasad-k.medium.com/airflow-dag-for-modern-rag-applications-e8dc876c114c?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8dc876c114c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 13:04:44 GMT</pubDate>
            <atom:updated>2025-06-24T02:43:07.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QG2UuQ1nUQuthu08_PRWQ.jpeg" /></figure><p><strong>Apache Airflow</strong> is a widely adopted orchestration tool in modern data applications. In this article, we will explore how to use Airflow to ingest data into a vector database and schedule the corresponding DAG to run on a daily basis.</p><p><strong>AI engineering in modern application development</strong></p><p><strong>AI Engineering</strong> is one of the fastest-growing domains today, driven by the integration of foundational models like <strong>OpenAI GPT-4o / GPT-4 / GPT-3.5</strong>,<strong>Google Gemini </strong>or <strong>Meta LLaMA</strong> into real-world applications. A core aspect of AI engineering involves crafting effective prompts to generate accurate and context-aware responses from these models.</p><p>One critical challenge that arises in this process is: <strong>how can we dynamically enrich prompts with relevant information</strong> to improve model output quality?</p><h3>RAG pipelines</h3><p><strong>Retrieval-Augmented Generation (RAG)</strong> is a powerful technique used in modern AI applications to enhance Large Language Models (LLMs) by incorporating external knowledge during inference.</p><ol><li><strong>Retrieval</strong>: Relevant information is fetched from an external knowledge base, in this example a vector database.</li><li><strong>Augmentation</strong>: The retrieved content is combined with the user’s input (prompt) to provide richer context.</li><li><strong>Generation</strong>: A large language model uses this augmented prompt to generate accurate, context-aware responses.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*y2YtyQEufVQrM_xE2iGW8A.png" /><figcaption>RAG workflow</figcaption></figure><p><strong>Advantages of using RAG applications</strong></p><ul><li>Accessing up to date data dynamically.</li><li>Improve accuracy in the retrieved response by adding more relevant prompt given to the LLM application.</li></ul><p><strong>Airflow for ingesting data into vector database</strong></p><p><strong>Apache Airflow</strong> can be effectively used to automate the ingestion of frequently changing data into a vector database. In this example, we will use <strong>Milvus</strong> as the target vector database.</p><h3>Advantages of Using Airflow for Data Ingestion</h3><ul><li><strong>Automated Scheduling</strong>: Easily schedule data pipelines to run on a daily (or custom) basis.</li><li><strong>Robust Error Handling</strong>: Built-in retry mechanisms and failure handling ensure reliable execution.</li><li><strong>Notification Support</strong>: Integrates with tools like Slack and email for real-time alerts and updates.</li><li><strong>Pipeline Monitoring</strong>: Provides a web-based UI to monitor, track, and debug DAG runs and task status.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*IGEhERQXvJJNXdvPCwqE3g.png" /><figcaption>Flow diagram for data ingestion using airflow</figcaption></figure><p><strong>Airflow DAG</strong></p><p>For the data ingestion pipeline I have broken down my DAG into four tasks</p><ul><li>Retrieving relevant data.</li><li>Creating a collection if do not exists.</li><li>Create vector embedding.</li><li>Insert data into vector database.</li></ul><p><strong>Example code for data ingestion and retrieval</strong></p><p>In this example, we are using <strong>Milvus as an in-memory vector database</strong> to store relevant information and retrieve it efficiently during query time.</p><pre>from pymilvus import MilvusClient<br>from pymilvus import model<br><br>client = MilvusClient(&quot;milvus_demo.db&quot;)<br><br>&quot;&quot;&quot;<br>Creating collection if doesnot exists<br>Step 1<br>&quot;&quot;&quot;<br><br>if client.has_collection(collection_name=&quot;demo_collection&quot;):<br>    client.drop_collection(collection_name=&quot;demo_collection&quot;)<br>client.create_collection(<br>    collection_name=&quot;demo_collection&quot;,<br>    dimension=768,  # The vectors we will use in this demo has 768 dimensions<br>)<br><br>&quot;&quot;&quot;<br>Step2<br>Collecting relevant information<br>&quot;&quot;&quot;<br><br>docs = [<br>    &quot;The Great Gatsby by F. Scott Fitzgerald is a classic novel set in the Jazz Age, exploring themes of wealth, love, and the American Dream through the mysterious millionaire Jay Gatsby.&quot;,<br>    &quot;To Kill a Mockingbird by Harper Lee is a powerful story about racial injustice and moral growth in the American South, told through the eyes of young Scout Finch.&quot;,<br>    &quot;1984 by George Orwell is a dystopian novel depicting a totalitarian society where critical thought is suppressed and the government controls every aspect of life.&quot;,<br>    &quot;Pride and Prejudice by Jane Austen follows the spirited Elizabeth Bennet as she navigates love, marriage, and social class in Georgian-era England.&quot;,<br>    &quot;The Hobbit by J.R.R. Tolkien is an epic fantasy adventure following Bilbo Baggins on his quest to help reclaim a dwarf kingdom from a fearsome dragon.&quot;<br>]<br><br>&quot;&quot;&quot;<br>step3<br>Creating vector embeddings<br>&quot;&quot;&quot;<br>embedding_fn = model.DefaultEmbeddingFunction()<br>vectors = embedding_fn.encode_documents(docs)<br>print(&quot;Dim:&quot;, embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)<br><br>data = [<br>    {&quot;id&quot;: i, &quot;vector&quot;: vectors[i], &quot;text&quot;: docs[i], &quot;subject&quot;: &quot;books&quot;}<br>    for i in range(len(vectors))<br>]<br><br>print(&quot;Data has&quot;, len(data), &quot;entities, each with fields: &quot;, data[0].keys())<br>print(&quot;Vector dim:&quot;, len(data[0][&quot;vector&quot;]))<br><br>&quot;&quot;&quot;<br>Step4<br>Inserting into a vector database<br>&quot;&quot;&quot;<br>res = client.insert(collection_name=&quot;demo_collection&quot;, data=data)<br>print(res)<br><br>query_vectors = embedding_fn.encode_queries([&quot;Suggest me a fantasy adventure book&quot;])<br># If you don&#39;t have the embedding function you can use a fake vector to finish the demo:<br># query_vectors = [ [ random.uniform(-1, 1) for _ in range(768) ] ]<br><br>res = client.search(<br>    collection_name=&quot;demo_collection&quot;,  # target collection<br>    data=query_vectors,  # query vectors<br>    limit=2,  # number of returned entities<br>    output_fields=[&quot;text&quot;],  # specifies fields to be returned<br>)<br><br>print(res)</pre><p><strong>Orchestrating the workflow using Airflow DAG</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*v47GEZk05xNVuLgkCz2_vQ.png" /></figure><ul><li><strong>create_collection_if_not_exists</strong>: Create a new collection in the vector DB if not already exists</li><li><strong>extract_data</strong>: Extract latest data from a file.</li><li><strong>transform_data</strong>: Create vector embedding.</li><li><strong>load_to_vector_db</strong>: Load embedding into a vector database.</li></ul><pre>from airflow.decorators import dag, task<br>from datetime import datetime, timedelta<br>import json<br><br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br><br><br>@dag(<br>    dag_id=&#39;vector_db_ingestion_pipeline&#39;,<br>    default_args=default_args,<br>    description=&#39;A DAG to ingest data into a vector database daily&#39;,<br>    schedule=&quot;@daily&quot;,<br>    start_date=datetime(2024, 1, 1),<br>    catchup=False,<br>    tags=[&#39;example&#39;, &#39;vector&#39;, &#39;taskflow&#39;],<br>)<br>def ingestion_dag():<br><br>    @task<br>    def creata_collection_if_not_exists():<br>        from pymilvus import MilvusClient<br>        client = MilvusClient(&quot;milvus_demo.db&quot;)<br>        if client.has_collection(collection_name=&quot;demo_collection&quot;):<br>            client.drop_collection(collection_name=&quot;demo_collection&quot;)<br>            client.create_collection(<br>            collection_name=&quot;demo_collection&quot;,<br>            dimension=768,  # The vectors we will use in this demo has 768 dimensions<br>            )<br><br>    @task<br>    def extract_data():<br>        file_path = &quot;/airflow_3_test/code_test/data.json&quot;<br>        with open(file_path, &quot;r&quot;) as f:<br>            data = json.load(f).get(&quot;data&quot;)  # Expects a list of records<br>        return data<br><br>    @task<br>    def transform_data(data):<br>        from pymilvus import model<br>        embedding_fn = model.DefaultEmbeddingFunction()<br>        vectors = embedding_fn.encode_documents(data)<br><br>        docs = [<br>            {&quot;id&quot;: i, &quot;vector&quot;: vectors[i].tolist(), &quot;text&quot;: data[i], &quot;subject&quot;: &quot;books&quot;}<br>            for i in range(len(vectors))<br>            ]<br>        # Add mock embeddings or metadata<br>        return docs<br><br>    @task<br>    def load_to_vector_db(transformed_data):<br>        # Simulate loading to a vector DB<br>        from pymilvus import MilvusClient<br>        client = MilvusClient(&quot;milvus_demo.db&quot;)<br>        res = client.upsert(collection_name=&quot;demo_collection&quot;, data=transformed_data)<br>        print(res)<br><br>   <br><br>    # DAG Flow<br>    create=creata_collection_if_not_exists()<br>    raw_data = extract_data()<br>    processed_data = transform_data(raw_data)<br>    load=load_to_vector_db(processed_data)<br>    query=query_data()<br>    create &gt;&gt; raw_data &gt;&gt;processed_data &gt;&gt;load<br><br># Register the DAG<br>ingestion_pipeline = ingestion_dag()</pre><p>Sample Query</p><pre>query_vectors = embedding_fn.encode_queries([&quot;Suggest me a fantasy adventure book&quot;])<br># If you don&#39;t have the embedding function you can use a fake vector to finish the demo:<br># query_vectors = [ [ random.uniform(-1, 1) for _ in range(768) ] ]<br><br>res = client.search(<br>    collection_name=&quot;demo_collection&quot;,  # target collection<br>    data=query_vectors,  # query vectors<br>    limit=2,  # number of returned entities<br>    output_fields=[&quot;text&quot;],  # specifies fields to be returned<br>)<br><br>print(res)</pre><p>Query response</p><pre>[2025-06-21, 18:21:17] INFO - data: [[{&#39;id&#39;: 4, &#39;distance&#39;: 0.4790608286857605, &#39;entity&#39;: {&#39;text&#39;: &#39;The Hobbit by J.R.R. Tolkien is an epic fantasy adventure following Bilbo Baggins on his quest to help reclaim a dwarf kingdom from a fearsome dragon.&#39;}}]]: chan=&quot;stdout&quot;: source=&quot;task&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8dc876c114c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to asset driven Scheduling in Airflow 3.0]]></title>
            <link>https://towardsdev.com/introduction-to-asset-driven-scheduling-in-airflow-3-0-07ac62f9e648?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/07ac62f9e648</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[event-based-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 11 May 2025 09:46:59 GMT</pubDate>
            <atom:updated>2025-05-19T16:09:07.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*EWK-qf_TwuPh_UuyUuW2rA.jpeg" /></figure><p><strong>Event based scheduling</strong></p><p>Event based triggering refers to triggering a DAG when a particular event occures,instead of relying on time based schedules like hourly and daily.</p><p>In one of my previous article we have discussed different ways to trigger DAGs based on events. In this article let’s discuss the newly added feature for event based scheduling in airflow 3.0</p><blockquote><a href="https://medium.com/codex/event-based-dags-in-airflow-7c8ee851665f">https://medium.com/codex/event-based-dags-in-airflow-7c8ee851665f</a></blockquote><p><strong>Where can we use event based triggers</strong></p><p>Apache airflow allows event based scheduling based on external events rather than predefined schedules. This is useful in modern data architecture were workflows need to react with data changes</p><ul><li><strong>Data ingestion pipelines:</strong> Trigger ETL workflows when new data arrives in the storage system</li><li><strong>Machine learning workflows</strong>: Start training with new data sets when latest data becomes available in the storage system.</li><li><strong>Event driven architecture:</strong> Trigger DAG when an API is invoked.</li></ul><p><strong>Asset aware scheduling in airflow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*lu-FtZNkfxXxrXj5I2plRQ.png" /><figcaption>Asset based scheduling</figcaption></figure><p><strong>Asset-based scheduling</strong> in Apache Airflow allows DAGs to run in response to data updates-called <em>assets</em>-rather than just on a fixed time schedule. This approach enables more data-aware and event-driven workflows,</p><p><strong>Terminologies</strong></p><p><strong>Asset schedule:</strong> A schedule of the DAG that is triggered as soon as an asset event is created.</p><p><strong>Producer Task: </strong>A task that is responsible for creating assets.</p><p><strong>Asset based scheduling examples</strong></p><p>A producer task can be used to create as asset. In the below example I have created a producer DAG which creates a file using a bash command.</p><p>The asset to which the data needs to be written is specified using the <strong><em>outlet</em></strong><em> </em>parameter<em>.</em></p><pre>from airflow.sdk import Asset,DAG<br>from airflow.providers.standard.operators.bash import BashOperator<br>from datetime import datetime<br>example_asset = Asset(&quot;/mnt/c/Users/krishnaprasad.k/Documents/airflow_3_test/resources/example.txt&quot;)<br><br>with DAG(<br>    dag_id=&quot;producer&quot;,<br>    start_date=datetime(2023, 1, 1),<br>    catchup=False,<br>    tags=[&quot;example&quot;],<br>) as dag:<br><br>    hello_task = BashOperator(<br>        task_id=&quot;create_files&quot;,<br>        outlets=[example_asset],<br>        bash_command=&quot;echo This is a line of text. &gt; example.txt&quot;<br><br>    )<br>    hello_task</pre><p>After creating the producer DAG we need to define the DAG scheduled by this Asset. We can use <strong>Asset </strong>class in airflow for schedule definition.</p><pre>from airflow.sdk import Asset,DAG<br>from airflow.operators.python import PythonOperator<br>from datetime import datetime<br><br><br>def print_values():<br>    with open(&quot;example.txt&quot;, &quot;r&quot;) as file:<br>        for line in file:<br>            print(line.strip())<br><br>with DAG(<br>    dag_id=&quot;asset_schedule&quot;,<br>    start_date=datetime(2023, 1, 1),<br>    schedule=[Asset(&quot;example.txt&quot;)],<br>    catchup=False,<br>    tags=[&quot;example&quot;],<br>) as dag:<br><br>    hello_task = PythonOperator(<br>        task_id=&quot;print_values&quot;,<br>        python_callable=print_values,<br>    )<br>    hello_task</pre><p>Now we can see the dependency created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sbj0QTgPuehTu8jn1R38Dw.png" /><figcaption>Asset dependencies for producer and asset based DAG</figcaption></figure><p>The schedule of <strong>asset_schedule </strong>DAG will be based on the asset created.</p><p><strong>Conditional Scheduling</strong></p><p>You can use the logical operators provided by schedule parameters to combine any number of assets. The logical operators are <strong>&amp; for and | for or</strong>.</p><p>The below given example shows Assets combined using <strong>or </strong>operator.</p><pre>with DAG(<br>    dag_id=&quot;asset_schedule&quot;,<br>    start_date=datetime(2023, 1, 1),<br>    schedule=[Asset(&quot;/mnt/c/Users/krishnaprasad.k/Documents/airflow_3_test/resources/example.txt&quot;) | Asset(&quot;/mnt/c/Users/krishnaprasad.k/Documents/airflow_3_test/resources/example2.txt&quot;)],<br>    catchup=False,<br>    tags=[&quot;example&quot;],<br>) as dag:</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07ac62f9e648" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/introduction-to-asset-driven-scheduling-in-airflow-3-0-07ac62f9e648">Introduction to asset driven Scheduling in Airflow 3.0</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[Notifications in airflow using callbacks]]></title>
            <link>https://medium.com/codex/notifications-in-airflow-using-callbacks-725d009423e2?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/725d009423e2</guid>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[workflow-management]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 13:19:12 GMT</pubDate>
            <atom:updated>2025-01-01T13:34:58.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU4bHlCpcH1kicYm3hUFjQ.png" /></figure><p>Apache airflow is one of the best orchestration engine available to manage workflows.</p><p>However using the Apache Airflow UI to manage and handle errors can be inefficient, particularly when:</p><ul><li>Multiple team members need to be notified about failures to take timely action.</li><li>Monitoring hundreds of pipelines across multiple environments becomes tedious and challenging.</li></ul><p>Fortunately airflow has a system called callbacks that can be used in case if any kind of event happen</p><h4>Types of callbacks in airflow</h4><p>Apache airflow provides a number of callbacks that can be used when particular event occures in airflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*1OS60ZlSe-ayBLP4RLPa9A.png" /><figcaption>Types of callbacks in airflow</figcaption></figure><p>These callbacks available can be used to provide notification to an external system in this article we will be exploring mainly two types of notification system.</p><ul><li>Notification via emails</li><li>Notification via slack channels</li></ul><h4><strong>Notifications at DAG Level</strong></h4><p>Notifications for different scenarios in airflow can be created at both <strong>DAG</strong> and <strong>task </strong>levels. Below given are example for airflow notifications at DAG level. that is send notification to in case of above given event occure ate DAG level.</p><p><strong>Mail Notifications</strong></p><p>email notifications can be used to get an alert via email when a particular event occures.</p><blockquote><strong>For sending email notification I will be using mailtrap.<em>mailtrap catches all your test emails and displays them in virtual inboxes. With Mailtrap Email Testing, development teams can easily test, view, share transactional and other emails.</em></strong></blockquote><p><a href="https://mailtrap.io/">try using mailtrap</a></p><p><strong>Prerequisites for creating mail notifications</strong></p><ul><li>Setup and email delivery platform. In this blog I have used <strong>mailtrap.io</strong></li><li>Add the variables into the <strong>smtp </strong>section of the file <strong>airflow.cfg</strong></li></ul><pre>[smtp]<br>smtp_host= sandbox.smtp.mailtrap.io<br>smtp_starttls=False<br>smtp_ssl=False<br>smtp_user=<br>smtp_password = <br>smtp_port=2525<br>smtp_mail_from=sample@gmail.com</pre><p><strong>Creating email notifications</strong></p><p>Below example gives code to create an email on the <strong>successful completion</strong> of the DAG. The DAG will call the function <em>success_email_function </em>on the successful completion.</p><pre>from airflow.decorators import dag,task<br>from airflow.utils.email import send_email<br>from datetime import datetime, timedelta<br><br><br>def success_email_function(context):<br>    &quot;&quot;&quot;<br>    Custom function to send email on DAG success<br>    &quot;&quot;&quot;<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    subject = f&quot;DAG {dag_run.dag_id} Completed Successfully&quot;<br>    html_content = f&quot;&quot;&quot;<br>    &lt;h3&gt;DAG Execution Success&lt;/h3&gt;<br>    &lt;p&gt;DAG: {dag_run.dag_id}&lt;/p&gt;<br>    &lt;p&gt;Execution Date: {dag_run.execution_date}&lt;/p&gt;<br>    &lt;p&gt;Status: Successful&lt;/p&gt;<br>    &quot;&quot;&quot;<br>    send_email(<br>        to=[&#39;fokoca8615@gholar.com&#39;],  # Replace with your email<br>        subject=subject,<br>        html_content=html_content<br>    )<br><br><br>@dag(<br>    start_date=datetime(2023, 1, 1),<br>    catchup=False,<br>    default_args={<br>        &#39;on_success_callback&#39;: success_email_function<br>    }<br>)<br>def example_email_success_dag():<br>    @task<br>    def test():<br>        print(&quot;hiii&quot;)<br><br>    test()<br><br><br>example_email_success_dag()</pre><p>After the successful completion of the task following email will be delivered into the mailbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*elDqzI2haklKlgfalXOEGQ.png" /><figcaption>success email notification</figcaption></figure><h4>Slack channel notification on DAG Success</h4><p>Similar to email another common method used for notification is notifying via the slack channel.</p><p><strong>Prerequisites for notifying via slack channel</strong></p><ul><li><a href="https://medium.com/applied-data-science/how-to-build-you-own-slack-bot-714283fd16e5">Create a bot in slack channel follow the below article.</a></li><li>Add a connection called <em>slack_api_default in </em>airflow connections using.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuF6Y8a9vQe8UJZQCLdxgA.png" /><figcaption>slack api default connection</figcaption></figure><p><strong>Sending slack notifications</strong></p><p>Similarly, notifications can be sent to a Slack channel by customizing the logic within the callback function. In the example below, only the logic inside the success callback differs.</p><pre>from airflow.decorators import dag, task<br>from datetime import datetime, timedelta<br>from airflow.providers.slack.notifications.slack import SlackNotifier<br>from airflow.models import Variable<br><br><br>def success_slack_function(context):<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    notifier = SlackNotifier(<br>        slack_conn_id=&quot;slack_api_default&quot;,<br>        text=f&quot;The DAG {dag_run.dag_id} succeeded successfully!&quot;,<br>        channel=&quot;#all-test&quot;,<br>        username=&quot;monitor&quot;<br>    )<br>    notifier.notify()<br><br><br>@dag(<br>    start_date=datetime(2023, 1, 1),<br>    catchup=False,<br>    default_args={<br>        &#39;on_success_callback&#39;: success_slack_function<br>    }<br>)<br>def example_slack_msg_success_dag():<br>    @task<br>    def test():<br>        print(&quot;helllll&quot;)<br><br>    test()<br><br><br>example_slack_msg_success_dag()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*-YrQFEL2cece0f2tzCt5eQ.png" /><figcaption>Slack notification example</figcaption></figure><h4>Notifications at the task level</h4><p>Just like DAG-level notifications, failure and success callbacks can also be configured at the task level.</p><p>Below are two code snippets demonstrating this for <strong>email </strong>and <strong>Slack</strong> notifications. The example includes two tasks — one triggers a failure callback, and the other triggers a success callback — ensuring the respective channels are notified about each task’s outcome.</p><pre>import os<br>from datetime import datetime<br>from airflow import DAG<br>from airflow.sensors.filesystem import FileSensor<br>from airflow.operators.python_operator import PythonOperator<br>import pandas as pd<br>from airflow.exceptions import AirflowException<br>from airflow.providers.slack.notifications.slack import SlackNotifier<br><br><br>def success_alert(context):<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    notifier=SlackNotifier(<br>        slack_conn_id=&quot;slack_api_default&quot;,<br>        text=f&quot;The DAG {dag_run.dag_id} succeeded successfully!&quot;,<br>        channel=&quot;#all-test&quot;,<br>        username=&quot;monitor&quot;<br>    )<br>    notifier.notify()<br><br><br>def failure_alert(context):<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    notifier = SlackNotifier(<br>        slack_conn_id=&quot;slack_api_default&quot;,<br>        text=f&quot;The DAG {dag_run.dag_id} failed&quot;,<br>        channel=&quot;#all-test&quot;,<br>        username=&quot;monitor&quot;<br>    )<br>    notifier.notify()<br><br><br>def success_task():<br>    print(&quot;successfully completed task&quot;)<br><br><br>def failed_task():<br>    raise AirflowException(&quot;task failed&quot;)<br><br><br># Define the default arguments for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>}<br><br># Instantiate the DAG<br>with DAG(<br>        &#39;task_level_slack_callbacks&#39;,<br>        default_args=default_args,<br>        description=&#39;Success and failure callbacks example&#39;,<br>        schedule_interval=None,<br>) as dag:<br>    success_example = PythonOperator(<br>        task_id=&#39;callback_example&#39;,<br>        python_callable=success_task,<br>        on_success_callback=[success_alert],<br><br>    )<br>    failure_example = PythonOperator(<br>        task_id=&#39;failure_example&#39;,<br>        python_callable=failed_task,<br>        on_failure_callback=[failure_alert],<br><br>    )<br><br>    success_example &gt;&gt; failure_example</pre><p>The code snippet for sending email notification for the above tasks are.</p><pre>import os<br>from datetime import datetime<br>from airflow import DAG<br>from airflow.sensors.filesystem import FileSensor<br>from airflow.operators.python_operator import PythonOperator<br>import pandas as pd<br>from airflow.exceptions import AirflowException<br>from airflow.utils.email import send_email<br><br><br>def success_alert(context):<br>    &quot;&quot;&quot;<br>    Custom function to send email on DAG success<br>    &quot;&quot;&quot;<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    subject = f&quot;Task Failed&quot;<br>    html_content = f&quot;&quot;&quot;<br>    &lt;h3&gt;Task Execution Success&lt;/h3&gt;<br>    &lt;p&gt;Execution Date: {dag_run.execution_date}&lt;/p&gt;<br>    &lt;p&gt;Status: Successful&lt;/p&gt;<br>    &quot;&quot;&quot;<br>    send_email(<br>        to=[&#39;fokoca8615@gholar.com&#39;],  # Replace with your email<br>        subject=subject,<br>        html_content=html_content<br>    )<br><br><br>def failure_alert(context):<br>    &quot;&quot;&quot;<br>    Custom function to send email on DAG success<br>    &quot;&quot;&quot;<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    subject = f&quot;Task Failed&quot;<br>    html_content = f&quot;&quot;&quot;<br>    &lt;h3&gt;Task failure_example  Failed&lt;/h3&gt;<br>    &lt;p&gt;Execution Date: {dag_run.execution_date}&lt;/p&gt;<br>    &lt;p&gt;Status: Failed&lt;/p&gt;<br>    &quot;&quot;&quot;<br>    print(&quot;hellllllllllllllllllll&quot;)<br>    send_email(<br>        to=[&#39;fokoca8615@gholar.com&#39;],  # Replace with your email<br>        subject=subject,<br>        html_content=html_content<br>    )<br><br><br>def success_task():<br>    print(&quot;successfully completed task&quot;)<br><br><br>def failed_task():<br>    raise AirflowException(&quot;task failed&quot;)<br><br><br># Define the default arguments for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>}<br><br># Instantiate the DAG<br>with DAG(<br>        &#39;task_level_email_callbacks&#39;,<br>        default_args=default_args,<br>        description=&#39;Success and failure callbacks example&#39;,<br>        schedule_interval=None,<br>) as dag:<br>    success_example = PythonOperator(<br>        task_id=&#39;callback_example&#39;,<br>        python_callable=success_task,<br>        on_success_callback=[success_alert],<br><br>    )<br>    failure_example = PythonOperator(<br>        task_id=&#39;failure_example&#39;,<br>        python_callable=failed_task,<br>        on_failure_callback=[failure_alert],<br><br>    )<br><br>    success_example &gt;&gt; failure_example</pre><h4>SLA Failed notifications in airflow</h4><p>In Apache Airflow, you can define an SLA (Service Level Agreement) for a task to receive notifications if the task fails to meet the specified SLA.</p><pre>from airflow.decorators import dag, task<br>from airflow.utils.email import send_email<br>import datetime<br>import pendulum<br>import time<br><br><br>def sla_callback(dag, task_list, blocking_task_list, slas, blocking_tis):<br>    &quot;&quot;&quot;<br>       Custom function to send email on DAG success<br>       &quot;&quot;&quot;<br>    dag_run = context.get(&quot;dag_run&quot;)<br>    html_content = f&quot;&quot;&quot;<br>       &lt;h3&gt;DAG Missed SLA&lt;/h3&gt;<br>       &lt;p&gt;DAG: {dag_run.dag_id}&lt;/p&gt;<br>       &lt;p&gt;Execution Date: {dag_run.execution_date}&lt;/p&gt;<br>       &lt;p&gt;Status: Missed SLA&lt;/p&gt;<br>       &quot;&quot;&quot;<br>    send_email(<br>        to=[&#39;fokoca8615@gholar.com&#39;],  # Replace with your email<br>        subject=subject,<br>        html_content=html_content<br>    )<br><br><br>@dag(<br>    schedule=datetime.timedelta(minutes=1),<br>    start_date=pendulum.datetime(2021, 1, 1, tz=&quot;UTC&quot;),<br>    catchup=False,<br>    default_args={&#39;sla&#39;: datetime.timedelta(seconds=10),&quot;email&quot;: &quot;email@example.com&quot;},<br>    sla_miss_callback=sla_callback,<br>)<br>def sla_miss_email_dag():<br>    @task(sla=datetime.timedelta(seconds=1))<br>    def sleep_20():<br>        time.sleep(20000)<br><br>    sleep_20()<br><br><br>sla_miss_email_dag()</pre><p>Inside the function <em>sla_callback</em> you can write your own logic for sending sla.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*Vi2_2d4Wpdd2KSbrnx2g1A.png" /><figcaption>SLA miss email example</figcaption></figure><p>The above example shows the email send by scheduler about SLA misses of all the tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=725d009423e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/notifications-in-airflow-using-callbacks-725d009423e2">Notifications in airflow using callbacks</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event-based DAGs in airflow]]></title>
            <link>https://medium.com/codex/event-based-dags-in-airflow-7c8ee851665f?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c8ee851665f</guid>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 14:35:29 GMT</pubDate>
            <atom:updated>2024-10-29T17:04:51.885Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache airflow is a platform developed for creating, maintaining, and monitoring workflows, where <strong>event-based</strong> and <strong>time-based</strong> are two different ways to run actions in an orchestration engine like airflow. We may need to choose between these two based on our workflow and architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*PnV-Mz5rcAErYN62GyGOZA.png" /></figure><h3>Event-based and time-based Trigger</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*tgSdX97uS1AITjdVD41Tmg.png" /></figure><p><strong>Event-based Triggers</strong> create an action when a specific event occurs. For example, a file being <strong>created modified, or edited</strong>.</p><p><strong>Time-based</strong> scheduling creates recurring schedules that run at a specific time. Time-based scheduling can be used to create customized schedules based on <strong>time and days</strong>. For example, daily running workflows can be scheduled using cron.</p><h3><strong>Use cases for event-based triggering</strong></h3><p>Running DAGs on an ad-hoc basis can be helpful for many applications. A few scenarios that requires event-based triggering are given below.</p><p><strong>Scenario 1: </strong>When a user clicks <strong>the submit button</strong> for a web page A DAG needs to be triggered for processing data.</p><p><strong>Scenario 2: </strong>Trigger a DAG when a file in the s3 bucket is created, modified, or deleted.</p><p><strong>Scenario 3</strong>: Trigger a DAG when a model training is completed.</p><h3>How can I create event-based DAGs</h3><h4><strong>Using Airflow sensors</strong></h4><p>Airflow sensors can be used to check whether an event has occurred or not and trigger and action when that particular event occures. <strong>For example</strong>, trigger an airflow DAG when a file arrives at your <strong>s3 bucket</strong> or an <strong>external service</strong> marked as completed.</p><p>Using airflow sensors can be expensive as the <strong>worker slot</strong> will be occupied as long as the task <strong>waits for the event to occur</strong>. This can be used as an effective method when arrival of a file can be any time within a given day, so the DAG will be <strong>scheduled for every day</strong> and executes only when the file arrives or will be <strong>timed out</strong>.</p><p><strong>See the example below:</strong> an airflow sensor that executes <strong>sum operation</strong> when a csv file arrives in the folder.</p><pre>id,count<br>1,100<br>2,200<br>3,300</pre><p>We will be using <strong>pandas data-frame API</strong> to calculate the <strong>sum of counts.</strong></p><pre>import os<br>from datetime import datetime<br>from airflow import DAG<br>from airflow.sensors.filesystem import FileSensor<br>from airflow.operators.python_operator import PythonOperator<br>import pandas as pd<br><br># Function to read the file and compute the sum<br>def calculate_sum():<br>    df=pd.read_csv(&quot;/airflow_article/test_values/test.csv&quot;)<br>    count_sum = df[&#39;count&#39;].sum()<br>    print(&quot;Sum of count:&quot;, count_sum)<br><br># Define the default arguments for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>}<br><br># Instantiate the DAG<br>with DAG(<br>    &#39;file_sensor_sum_dag&#39;,<br>    default_args=default_args,<br>    description=&#39;A DAG that waits for a file and calculates sum of numbers&#39;,<br>    schedule_interval=None,<br>) as dag:<br><br>    # Task 1: FileSensor waits for the file to appear<br>    wait_for_file = FileSensor(<br>        task_id=&#39;wait_for_file&#39;,<br>        filepath=&quot;/airflow_article/test_values/test.csv&quot;,<br>        poke_interval=30,  # Check every 30 seconds<br>        timeout=600,       # Timeout after 10 minutes if the file isn&#39;t found<br>    )<br><br>    # Task 2: Calculate the sum once the file is available<br>    calculate_sum_task = PythonOperator(<br>        task_id=&#39;calculate_sum&#39;,<br>        python_callable=calculate_sum,<br>    )<br><br>    # Define task dependencies<br>    wait_for_file &gt;&gt; calculate_sum_task</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Np4nSo6L0-iXzbI_awhK1Q.png" /><figcaption>Sensor waiting for file in the source folder</figcaption></figure><p>In the above example the <strong>wait_for_file </strong>will wait until the file arrives at the location and then triggers the<strong> calculate_sum_task.</strong></p><p>Once the execution completes the sum of count will be printed to the output.</p><pre>2024-10-25, 06:35:43 UTC] {logging_mixin.py:190} INFO - Sum of count: 600<br>[2024-10-25, 06:35:43 UTC] {python.py:240} INFO - Done. Returned value was: None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*2FYDI7CUg5V5GbrLjIDlmQ.png" /><figcaption>Pros and cons for airflow sensors</figcaption></figure><p><strong>Using Deferrable operators</strong></p><p>Deferrable operators are ideal for cases when waiting time is expensive.</p><blockquote>When it has nothing to do but wait, an operator can suspend itself and free up the worker for other processes by <strong><em>deferring</em></strong>. When an operator defers, execution moves to the triggerer, where the trigger specified by the operator will run. The trigger can do the polling or waiting required by the operator. Then, when the trigger finishes polling or waiting, it sends a signal for the operator to resume its execution. During the deferred phase of execution, since work has been offloaded to the triggerer, the task no longer occupies a worker slot, and you have more free workload capacity.</blockquote><p><strong>Deferrable operators</strong> frees the worker slot and this slot can be used for other tasks. When an operator defers the polling will be moved to the <strong>triggerer. </strong>Whenever the triggerer finishes polling the operation will be <strong>resumed</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f15d-U5m56QHmVg_l3-zew.png" /><figcaption>workflow for deferrable operators</figcaption></figure><p>Refer the below <em>mode=’reschedule’ </em>given to make the task deferrable.</p><pre>import os<br>from datetime import datetime<br>from airflow import DAG<br>from airflow.sensors.filesystem import FileSensor<br>from airflow.operators.python_operator import PythonOperator<br>import pandas as pd<br><br># Function to read the file and compute the sum<br>def calculate_sum():<br>    df=pd.read_csv(&quot;/mnt/c/Users/krishnaprasad.k/Documents/airflow_article/test_values/test.csv&quot;)<br>    count_sum = df[&#39;count&#39;].sum()<br>    print(&quot;Sum of count:&quot;, count_sum)<br><br># Define the default arguments for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>}<br><br># Instantiate the DAG<br>with DAG(<br>    &#39;file_sensor_sum_dag_defarrable&#39;,<br>    default_args=default_args,<br>    description=&#39;A DAG that waits for a file and calculates sum of numbers&#39;,<br>    schedule_interval=None,<br>) as dag:<br><br>    # Task 1: FileSensor waits for the file to appear<br>    wait_for_file = FileSensor(<br>        task_id=&#39;wait_for_file&#39;,<br>        filepath=&quot;/mnt/c/Users/krishnaprasad.k/Documents/airflow_article/test_values/test.csv&quot;,<br>        poke_interval=30,  # Check every 30 seconds<br>        timeout=600,       # Timeout after 10 minutes if the file isn&#39;t found<br>        mode=&#39;reschedule&#39;, # This is the key part for deferrable<br>    )<br><br>    # Task 2: Calculate the sum once the file is available<br>    calculate_sum_task = PythonOperator(<br>        task_id=&#39;calculate_sum&#39;,<br>        python_callable=calculate_sum,<br>    )<br><br>    # Define task dependencies<br>    wait_for_file &gt;&gt; calculate_sum_task</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*yhF86InuF1vHyhs2tHH3SA.png" /><figcaption>deferrable sensor example</figcaption></figure><h4>Custom Deferrable operators</h4><p>Sensors for all the operations may not be available so we may need to create our own deferrable operators.</p><p>Below is an example of a deferrable operator that waits for one minute and then marks the task as completed.</p><pre>import time<br>from datetime import timedelta<br>from typing import Any<br><br>from airflow.configuration import conf<br>from airflow.sensors.base import BaseSensorOperator<br>from airflow.triggers.temporal import TimeDeltaTrigger<br>from airflow.utils.context import Context<br><br><br>class WaitOneMinuteSensor(BaseSensorOperator):<br>    def __init__(<br>        self, deferrable: bool = True, **kwargs<br>    ) -&gt; None:<br>        super().__init__(**kwargs)<br>        self.deferrable = deferrable<br><br>    def execute(self, context: Context) -&gt; None:<br>        if self.deferrable:<br>            self.defer(<br>                trigger=TimeDeltaTrigger(timedelta(minutes=1)),<br>                method_name=&quot;execute_complete&quot;,<br>            )<br>        else:<br>            time.sleep(60)<br><br>    def execute_complete(<br>        self,<br>        context: Context,<br>        event: dict[str, Any] | None = None,<br>    ) -&gt; str:<br>        # We have no more work to do here. Mark as complete.<br>        return &quot;Task complete&quot;</pre><p><strong><em>self.defer</em></strong><em> </em>is used to transfer the polling to trigger and then uses<em> </em><strong><em>TimeDeltaTrigger </em></strong>to wait for exactly one minute after completion handles back to execute_complete and finishes the execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*vc7pIPs3SO0xRnu2mjsNMg.png" /><figcaption>Waiting for file in deferred state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*YF6PeyJAEc4h53e76q2dbw.png" /><figcaption>pros and cons of deferrable operators</figcaption></figure><h4><strong>Using airflow REST APIs</strong></h4><p><strong>Airflow REST APIs</strong> can be used to trigger the DAG when an event occures. One of the scenario is when the user clicks the submit button in a web page, an API call is triggered with relevant user data.</p><p>The below example shows triggering an airflow DAG with a <strong>conf </strong>and printing the value. The code snippet prints the value inside the name key in</p><pre>from datetime import datetime<br>from airflow import DAG<br>from airflow.operators.python_operator import PythonOperator<br><br># Define the function to print &quot;Hello, World!&quot;<br>def print_values(**kwargs):<br>    name= kwargs[&#39;dag_run&#39;].conf[&#39;name&#39;]<br>    print(f&quot;hello {name}&quot;)<br># Define the default arguments for the DAG<br>default_args = {<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>}<br><br># Instantiate the DAG<br>with DAG(<br>    &#39;print_values&#39;,<br>    default_args=default_args,<br>    description=&#39;A simple DAG&#39;,<br>) as dag:<br><br>    # Define the task<br>    hello_task = PythonOperator(<br>        task_id=&#39;print_values&#39;,<br>        python_callable=print_values,<br>    )<br><br>    # Set the task dependencies if needed<br>    hello_task</pre><p>The <strong>POST </strong>request will be sent to the below URL, using a basic authentication mechanism to authenticate into airflow.</p><pre>http://localhost:8080/api/v1/dags/print_values/dagRuns</pre><p>Sample request body.</p><pre>{<br>    &quot;conf&quot;:{<br>        &quot;name&quot;:&quot;hello&quot;<br>    }<br>}</pre><p>The above POST request will trigger the print_values DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*JgFAMiw2PAZmfjrPoSEsiA.png" /><figcaption>Print values DAG after completing execution</figcaption></figure><pre>[2024-10-25, 09:43:32 UTC] {logging_mixin.py:190} INFO - hello hello</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*iLr8Jcn92HUaH8KaQiwANg.png" /><figcaption>Pros and cons for triggering using airflow REST APIs</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8ee851665f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/event-based-dags-in-airflow-7c8ee851665f">Event-based DAGs in airflow</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four Alternatives to pandas for processing large datasets]]></title>
            <link>https://medium.com/codex/four-alternatives-to-pandas-for-processing-large-datasets-ea88445eb6b5?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea88445eb6b5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 06:56:53 GMT</pubDate>
            <atom:updated>2023-01-18T21:28:22.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*_Koj704N2IeP3zupDwVpHQ.jpeg" /></figure><h3><strong>Ten things I hate about pandas</strong></h3><p>For years pandas have become the de-facto library for python developers for data analytics and manipulating Dataframes. However, pandas could be better at handling large datasets.</p><blockquote><strong>my rule of thumb for pandas is that you should have 5 to 10 times as much RAM as the size of your datasets</strong></blockquote><p>Wes Mckenny the creator of pandas has somewhat of a similar opinion, read the following article by Mckennny about <em>10 things I hate about pandas</em></p><blockquote><a href="https://wesmckinney.com/blog/apache-arrow-pandas-internals/">https://wesmckinney.com/blog/apache-arrow-pandas-internals/</a></blockquote><p>In this article, we will be looking into 4 different libraries that can be used as an alternative to pandas.</p><ul><li>Dask</li><li>Ray</li><li>Modin</li><li>Vaex</li></ul><h3><strong>Dask</strong></h3><p>A Dask DataFrame is a large parallel DataFrame composed of many smaller pandas DataFrames. These dataframes may live on different machines in a cluster, and one dask dataframe operation will trigger multiple pandas DataFrame operations.</p><pre>pip install &quot;dask[complete]&quot;</pre><p><strong>Scale pandas library</strong></p><p>Because the dask.DataFrame application programming interface (API) is a subset of the pd.DataFrame API, it should be familiar to pandas users.</p><pre>import dask.dataframe as dd<br>df = dd.read_csv(&#39;/Downloads/archive/Hotel_Reservations.csv&#39;)<br>print(df)<br></pre><p><strong>Scale any python code</strong></p><p>Dask supports a real-time task framework that extends Python’s <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent.futures</a> interface.</p><p>Create a dask client</p><pre>from dask.distributed import Client<br>client = Client()  # start local workers as processes<br># or<br>client = Client(processes=False)  # start local workers as threads</pre><p>you can submit tasks to dask client using the submit method.</p><pre>def add(a):<br>    return a+10<br><br>a = client.submit(add, 10)<br>print(a)</pre><h3>Ray Datasets</h3><p>Ray is a unified framework for scaling AI and Python applications.</p><pre>pip install ray[complete]</pre><p>Ray Datasets are the standard way to load and exchange data in Ray libraries and applications.</p><pre>import ray<br>df=ray.data.read_csv(&quot;/Downloads/archive/Hotel_Reservations.csv&quot;)<br>print(df)</pre><h3><strong>Modin</strong></h3><pre>pip install modin</pre><p>Modin uses <a href="https://github.com/ray-project/ray/">Ray</a>, <a href="https://dask.org/">Dask</a> or <a href="https://github.com/modin-project/unidist/">Unidist</a> to provide an effortless way to speed up your pandas notebooks, scripts, and libraries. Unlike other distributed Dataframe libraries, Modin provides seamless integration and compatibility with existing pandas code. Even using the Dataframe constructor is identical.</p><pre>import modin.pandas as pd<br><br>df=pd.read_csv(&quot;/Downloads/archive/Hotel_Reservations.csv&quot;)<br>print(df)</pre><h3>vaex</h3><p>Vaex is a high performance Python library for lazy <strong>Out-of-Core DataFrames</strong> (similar to Pandas), to visualize and explore big tabular datasets. It calculates <em>statistics</em> such as mean, sum, count, standard deviation etc, on an <em>N-dimensional grid</em> for more than <strong>a billion</strong> (10^9) samples/rows <strong>per second</strong>. Visualization is done using <strong>histograms</strong>, <strong>density plots</strong> and <strong>3d volume rendering</strong>, allowing interactive exploration of big data.</p><pre>pip install vaex</pre><pre>import vaex<br>df=vaex.read_csv(&quot;/Downloads/archive/Hotel_Reservations.csv&quot;)<br>print(df)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea88445eb6b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/four-alternatives-to-pandas-for-processing-large-datasets-ea88445eb6b5">Four Alternatives to pandas for processing large datasets</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extractors in Scala]]></title>
            <link>https://medium.com/codex/extractors-in-scala-fb0b7949562b?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0b7949562b</guid>
            <category><![CDATA[extractor]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[case-class]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 07:13:39 GMT</pubDate>
            <atom:updated>2022-04-03T10:01:22.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*IizzflXXDYmEczPPNooNVA.png" /></figure><p>If you are a scala developer you may be accustomed with the use of <strong>case class</strong> in pattern matching. For example Some(x) is a valid pattern because Some(x) is a case class, let us see an example of case class for extracting an email address.</p><pre>case class Email(User: String, domain: String)</pre><p>A case class <strong>Email</strong> which contains User and domain. A pattern would match if the string contains an embedded<em> ‘@’</em> symbol.</p><pre>def pattern(email: Email) = {<br>    email match {<br>      case <em>Email</em>(user, domain) =&gt; <em>println</em>(user, domain)<br>      case _ =&gt; <em>println</em>(&quot;Not a valid email&quot;)<br>    }<br><br><br>  }<br>  <br>}</pre><p>Extractors provides a way to create patterns without providing case classes.</p><p><strong>Extractor</strong></p><p>Extractor in Scala is an object that has an <strong>unapply</strong> method associated with it, the purpose of this unapply method is to match a value and take it apart.</p><p>Using extractor for extracting an email address.</p><pre>object EMail {<br>  // The injection method (optional)<br>  def apply(user: String, domain: String) = user + &quot;@&quot; + domain<br>  // The extraction method (mandatory)<br>  def unapply(str: String): Option[(String, String)] = {<br>    val parts = str split &quot;@&quot;<br>    if (parts.length == 2) <em>Some</em>(parts(0), parts(1)) else None<br>  }<br>}</pre><p>The object email has two methods associated with it the apply method and the unapply method.</p><ul><li>apply method takes two string and converts it into an email.</li><li>unapply method does exactly the opposite of apply method it takes a string and split into two parts but unlike the apply method the unapply must handle the case the string is not an email that is why the unapply returns an <strong>option</strong> over <strong>pair of string</strong>.</li></ul><pre><em>println</em>(EMail.<em>unapply</em>(&quot;someone@example.com&quot;))<br><em>println</em>(EMail.<em>unapply</em>(&quot;someone&quot;))</pre><pre>Some((someone,example.com))<br>None</pre><p><strong>Patterns with zero or more variables</strong></p><p>It is also possible that the extractor patterns does not bind any variables, in that case unapply method returns a true or false.</p><pre>object UpperCase {<br>  def unapply(s: String): Boolean = s.toUpperCase == s<br>}</pre><p>The above function will return true if the string is in uppercase else false.</p><p><strong>variable argument extractor</strong></p><p>In the previous example for email address all returned a fixed number of values. Sometimes this is not flexible enough. For example</p><p><em>tom@java.org</em></p><p>For the above email address you may want the domain name as a sequence of string.</p><pre>object ExpandedEMail {<br>  def unapplySeq(email: String)<br>  : Option[(String, Seq[String])] = {<br>    val parts = email split &quot;@&quot;<br>    if (parts.length == 2)<br>      <em>Some</em>(parts(0), parts(1).split(&quot;\\.&quot;).reverse)<br>    else<br>      None<br>  }</pre><p>The above method will return user as a string and domain as sequence of string.</p><pre>val <em>email1</em>=&quot;tom@java.example.org&quot;<br><em>println</em>(ExpandedEMail.<em>unapplySeq</em>(<em>email1</em>))</pre><pre>Some((tom,WrappedArray(org, example, java)))</pre><p><strong>Extractors versus Case classes</strong></p><p>Even though they are very useful they have one shortcoming they expose the concrete representation of data. Extractors break the link between data representations and patterns, the pattern have nothing to do with the data type of the object selected on. This property is called representational independence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0b7949562b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/extractors-in-scala-fb0b7949562b">Extractors in Scala</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Graph powered machine learning]]></title>
            <link>https://towardsdev.com/introduction-to-graph-powered-machine-learning-f97ef19aac20?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97ef19aac20</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 08:01:54 GMT</pubDate>
            <atom:updated>2022-02-21T07:35:33.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uNj9_PyC3hbC__5aqsWFyw.png" /></figure><p>We are surrounded by graphs. Facebook, LinkedIn, Twitter are the most famous examples of social networks. Graphs are powerful structures that can not only be used for storing connection information but also supports multiple kinds of analysis.</p><p>Graphs support machine learning by doing what they do best.</p><ul><li>Representing data in a way easily understandable and accessible.</li><li>Graphs make all processes faster and more accurate.</li></ul><p><strong>What is a graph</strong></p><p>A graph is a simple and quite old mathematical concept consisting of a set of edges(nodes/points) and vertices(relationships/lines). Graphs can be <strong>directed/undirected </strong>based on the direction of traversals<strong>, cyclic/acyclic</strong> based on loops.</p><figure><img alt="Directed Acyclic Graphs(DAGs) graphs with direction and without loops" src="https://cdn-images-1.medium.com/max/685/1*WlsaDylQuarrCvObXfm8Gw.png" /><figcaption>Directed Acyclic Graphs</figcaption></figure><p><strong>Graphs as models of networks</strong></p><p>Graphs are useful for representing how things are linked in a simple or complex structure. Some of the examples are</p><ul><li>A <em>social networ</em>k in which <strong>people are nodes</strong> and relationships are represented using vertices (friends, family, co-workers).</li><li>An <em>information networ</em>k in which <strong>edges are web pages</strong> and vertices are relationships among web pages (hyperlinks, citations, etc).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*c_l3HMIasgmx_jA_gvWwrg.png" /><figcaption>‘Directed’ relation between movie and person</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ipGLvfBta0fgpOjWFI-3Tg.png" /><figcaption>‘Acted in’ relation between person and movie</figcaption></figure><p>Looking at the above two figures we can understand another important character of graphs. Using them as information maps.</p><ul><li>Find complex patterns.</li><li>Make them visible for future investigations and interpretations.</li></ul><p>When the power of machine learning is combined with the power of the human brain it enables powerful and efficient data processing and pattern recognition.</p><p><strong>The role of graphs in machine learning</strong></p><p>Graphs are used to characterize the interaction between objects and relations, to model multiple and complex networks, or in general to represent real-world problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*8dD7jvyO1MmV-P0MdPGMIg.png" /><figcaption>Graph Features of machine learning</figcaption></figure><p>The graph features of machine learning can be grouped into 3 categories.</p><ul><li><strong>Data management:</strong> Graphs that help machine learning projects to deal with the data.</li><li><strong>Data analysis:</strong> Graph features can be used for learning and predicting.</li><li><strong>Data visualization</strong>: Graph tools for visualization</li></ul><p><strong>Data management</strong></p><p>Graphs allow you to explore more of your data easily, access it easily and clean, and enrich it faster.</p><ul><li><strong>Connected sources of truth</strong>: Graphs allow you to merge multiple data sources into a single location.</li><li><strong>Data enrichment:</strong> Extend existing data with external sources.</li><li><strong>feature selection</strong>: Identifying relevant features inside data</li></ul><p><strong>Data analytics</strong></p><p>Graphs can be used to model and analyze the relationship between entities and their properties.</p><ul><li><strong>Graph algorithms</strong>: Some of the graph algorithms such as clustering and page ranking can be used to get useful insights.</li><li><strong>Mixing of models</strong>: Multiple models can co-exist in the same graphs they can be merged during the prediction phase.</li><li><strong>Fast model access</strong>: Graph patterns provide the right patterns for real-time predictions.</li></ul><p><strong>Data visualization</strong></p><p>Graphs have high communication power, they can represent multiple complex information in a way that the human mind can easily understand and process.</p><ul><li><strong>Data navigation</strong>: Easy to navigate between different elements.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97ef19aac20" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/introduction-to-graph-powered-machine-learning-f97ef19aac20">Introduction to Graph powered machine learning</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[Regression to the mean]]></title>
            <link>https://krishnaprasad-k.medium.com/regression-to-the-mean-a64fb110b9d8?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64fb110b9d8</guid>
            <category><![CDATA[halo-effect]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[economics]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 07:57:13 GMT</pubDate>
            <atom:updated>2022-02-13T08:05:48.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*BJht7rMq0OqLR6AJZp7zlA.jpeg" /></figure><p><strong>Psychology of effective training</strong></p><p>One of the questions I was asking myself was the pyshology of effective training, how to train skills efficiently ?</p><p>One of the important principle of skill training is rewards for improved performance work better than punishment for mistakes. This proposition is supported by much evidence from research on birds,animals and humans.</p><p>Well some of you may argue that this is not correct. Reward is not better than punishment, well this may be true for animals and birds but not for humans. Praises are usually followed by a bad performance while punishment are followed by significant improvement.</p><p>The observation of people of second opinion is is astute and correct, but the inference they had drawn is wrong .</p><blockquote>What they had observerd is known as <strong>randomness to the mean</strong>, which is randomness in the fluctuation of quality of performance.</blockquote><p><strong>Understanding Regression</strong></p><p>Whether undected or wrongly explained, the phenomenon of regression is strange to human mind. So strange that it was identified and understood only two hundred years after invention of gravitational theory and calculus.</p><p>It was identified and discovered by sir Francis Galton. A half cousin of Charles Darwin and renowned mathematician of 19th century.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*IKRiOkirkfofOwV38h7AfQ.jpeg" /><figcaption>Francis Galton</figcaption></figure><p>The<strong> correlation coeffiecient</strong> between two measures, which varies between 0 and 1 , is a measure of the relative weight of factors they share. For example we all share half of our genes from our parents, so the correlation from a parent to child is not far from <strong><em>.50</em></strong>.</p><p>It took Galton several years to identify that the correlation and regression are not two concepts they are different perspectives of the same concept.</p><ul><li>When the correlation between two scores is imperfect there will be regression to mean</li></ul><h4>Praises are usually followed by a bad performance while punishment are folllowed by significant improvement.</h4><p>Now we can explain why the may be correct and inference is wrong the correlation between punishment and performance is is not perfect but in some cases we can observe this scenarion that punishment leading to better performace.</p><blockquote>He said that experiece taught him that criticism is more effective than praise, what he doesn’t understand is that it’s all due to regression to mean</blockquote><p><strong>The illusion of understanding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsKzvvlCRT1H1zpSC52vfQ.jpeg" /></figure><p>The falwed stories of the past shape our views of the world and our expectations of the future, these are called<strong> narrative fallacies</strong> .</p><p>narrative fallacies continously arise from our attempt to make sense of the world. The narrative fallacies can arise due to halo effect. If you like the president’s politics, you probably like his voice and appearance as well. The tendency to like (or dislike) a person including things you have not observered is known as halo effect.</p><p>The examples of halo effect can be seen everywhere if a sports person is handome and attractive you may think that he is likely to perform well in the match and vise versa.</p><p><strong>How to tame the Halo effect</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWT0ENIgjp9idIx5TV7Jqg.jpeg" /></figure><p>One of the best stratigies used to tame halo effect is to use a general principal called <strong>decorelate error.</strong></p><p>This principal is easy to explain with an example, if you are assigned with a task to count the number of coins in a jar, for an individual the judgement for this kind of task can be poor but if you average out the opinion of a group of people your judgement can be remarkably well.</p><p>Some people may underestimate and some may overestimate but if we average out all of their opinion it will give better judgement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64fb110b9d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Databases and Object Graph Mapping with neo4j and python]]></title>
            <link>https://towardsdev.com/graph-databases-and-object-graph-mapping-with-neo4j-and-python-49bbb5a46b32?source=rss-119ec0c9b3a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/49bbb5a46b32</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[graph-data-structure]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[krishnaprasad k]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 09:03:05 GMT</pubDate>
            <atom:updated>2022-01-18T12:37:28.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*TH4oVQI0XTLfXFDRyPXTCA.jpeg" /></figure><p><strong>Why Graph Databases</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b2f-gIi-InZ6z8Id__5pQ.jpeg" /></figure><p>Why should you use a graph database of your choice, it is quite often for people to logically try to model,describe their particular problem in graph like structure and concepts even though they may not use graph database as their ultimate data store.</p><p>The below given is a social media example where users can be represented as friends of each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA7mspKCsRfIj_34wKS2-g.png" /><figcaption>Users represented as friends of each other</figcaption></figure><p><strong>Graph data with neo4j</strong></p><p>Neo4j stores data as vertices and edges or in neo4j terminology, nodes and relationships. Users will be represented as <strong>nodes</strong> and their friendship will be represented as <strong>relationships</strong> between nodes.</p><blockquote>The key difference between traditional relational databases and neo4j is that there won’t be any columns and tables in neo4j nor there won’t be any <strong>select</strong> or <strong>join</strong> queries.</blockquote><p><strong>What is the secret behind neo4j’s speed</strong></p><p>The secret is the the data structure behind neo4j, the localized nature of the graphs makes it very fast for these kinds of traversals. Imagine yourself sitting in a football stadium and asked to count the number of people sitting 15 feet around you, what you will do is that you will get up and start counting one by one. You will be able to count with the same speed even if you are sitting in a larger stadium(Given the population density is same) .</p><p>The neo4j engine works in a similar way, it visits the nodes connected to the starting node, even if the number of nodes increases the performance remains the same.</p><p><strong>Python driver for neo4j connectivity</strong></p><p>To install the latest stable release.</p><pre>python -m pip install neo4j</pre><p>Connect to the neo4j server using the connection URI. After connection create two different types of nodes</p><ul><li>Movie</li><li>person</li></ul><p>Define the relationships between these two nodes movie and person.</p><ul><li>Acted eg: Keanu reeves <strong>acted</strong> in ‘<em>The matrix’</em></li><li>Directed: Joels <strong>directed</strong> the movie ‘<em>The matrix’</em></li></ul><pre>uri = &quot;neo4j://@localhost:7687&quot;<br>driver = GraphDatabase.driver(uri, auth=(&quot;neo4j&quot;, &quot;passsword&quot;))</pre><pre>&quot;&quot;&quot;<br>Create different nodes<br>* Movie<br>* Person</pre><pre>Provide relations between Person and Movie<br>* Acted In<br>* Directed<br>&quot;&quot;&quot;</pre><pre>def create_node(tx):<br>    tx.run(<br>        &quot;&quot;&quot;CREATE (TheMatrix:Movie {title:&#39;The Matrix&#39;, released:1999, tagline:&#39;Welcome to the Real World&#39;})<br>      CREATE (Keanu:Person {name:&#39;Keanu Reeves&#39;, born:1964})<br>      CREATE (Carrie:Person {name:&#39;Carrie-Anne Moss&#39;, born:1967})<br>      CREATE (Laurence:Person {name:&#39;Laurence Fishburne&#39;, born:1961})<br>      CREATE (Hugo:Person {name:&#39;Hugo Weaving&#39;, born:1960})<br>      CREATE (LillyW:Person {name:&#39;Lilly Wachowski&#39;, born:1967})<br>      CREATE (LanaW:Person {name:&#39;Lana Wachowski&#39;, born:1965})<br>      CREATE (JoelS:Person {name:&#39;Joel Silver&#39;, born:1952})<br>      CREATE<br>      (Keanu)-[:ACTED_IN {roles:[&#39;Neo&#39;]}]-&gt;(TheMatrix),<br>      (Carrie)-[:ACTED_IN {roles:[&#39;Trinity&#39;]}]-&gt;(TheMatrix),<br>      (Laurence)-[:ACTED_IN {roles:[&#39;Morpheus&#39;]}]-&gt;(TheMatrix),<br>      (Hugo)-[:ACTED_IN {roles:[&#39;Agent Smith&#39;]}]-&gt;(TheMatrix),<br>      (LillyW)-[:DIRECTED]-&gt;(TheMatrix),<br>      (LanaW)-[:DIRECTED]-&gt;(TheMatrix),<br>      (JoelS)-[:PRODUCED]-&gt;(TheMatrix)&quot;&quot;&quot;<br>    )</pre><pre>with driver.session() as session:<br>    session.write_transaction(create_node)<br>driver.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*5hfjb3bFSj8tFYlmsxv3NA.png" /><figcaption>Directed relation between movie and person</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*0ccuB1_aPpLbxOYz2oOsqg.png" /><figcaption>Actor relation between movie and person</figcaption></figure><p><strong>Object Graph Mapping with python</strong></p><p>neomodel library in python which uses the neo4j driver can be used to map python objects into neo4j graphs.</p><p>Install the latest stable release.</p><pre>pip install neomodel</pre><p>Set connection using neomodel with neo4j.</p><pre>from neomodel import db<br>db.set_connection(&quot;neo4j://neo4j:password@localhost:7687&quot;)</pre><p>Create two classes Country and Person with the relation which <strong>country the person is from</strong>, this object and relation between them will be mapped into a graph.</p><pre>class Country(StructuredNode):<br>    code = StringProperty(unique_index=True, required=True)<br><br><br>class Person(StructuredNode):<br>    uid = UniqueIdProperty()<br>    name = StringProperty(unique_index=True)<br>    age = IntegerProperty(index=True, default=0)<br><br>    # Defining a relationship with the table country ie the person &#39;is from&#39; which country<br>    country = RelationshipTo(Country, &#39;IS_FROM&#39;)</pre><p><strong>Create and update operations</strong></p><pre>&quot;&quot;&quot;<br>Create and update  operation in neo4j with neomodel<br>&quot;&quot;&quot;<br>jim = Person(name=&#39;Jim&#39;, age=3).save()  # Create<br>jim.age = 4<br>jim.save()<br>&quot;&quot;&quot;<br>Delete operation in neomodel<br>&quot;&quot;&quot;<br>jim.delete()</pre><p><strong>Defining relations</strong></p><p>The below example shows the relation between jim and the country in which he is from.</p><pre>&quot;&quot;&quot;<br>Defining relationships<br>&quot;&quot;&quot;<br>germany = Country(code=&#39;DE&#39;).save()<br>jim.country.connect(germany)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*1DbFPoCKWbxGjLK5cVQp9w.png" /><figcaption>Relation between jim and his Country which he is from</figcaption></figure><p><strong>Retrieving nodes</strong></p><p>If there exists no such node an exception will be raised.</p><pre># Return all nodes<br>all_nodes = Person.nodes.all()<br><br># Returns Person by Person.name==&#39;Jim&#39; or raises neomodel.DoesNotExist if no match<br>jim = Person.nodes.get(name=&#39;Jim&#39;)<br>print(jim)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49bbb5a46b32" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/graph-databases-and-object-graph-mapping-with-neo4j-and-python-49bbb5a46b32">Graph Databases and Object Graph Mapping with neo4j and python</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>