<?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 Michael Flores on Medium]]></title>
        <description><![CDATA[Stories by Michael Flores on Medium]]></description>
        <link>https://medium.com/@msf894?source=rss-53a265c77f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gVg1iqz6vXoYV6n0PU1WBw.png</url>
            <title>Stories by Michael Flores on Medium</title>
            <link>https://medium.com/@msf894?source=rss-53a265c77f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:39:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msf894/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[Transactions in SQL Server]]></title>
            <link>https://msf894.medium.com/transactions-in-sql-server-f6b90ff172a0?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6b90ff172a0</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 22:19:07 GMT</pubDate>
            <atom:updated>2021-04-18T22:19:07.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*fDD6xP4wtnQCfKe4.png" /><figcaption><a href="https://sqlserverrider.wordpress.com/2013/02/24/get-the-current-transaction-state-of-user-request-using-xact_state-sql-server/">Source</a></figcaption></figure><p>In my last <a href="https://msf894.medium.com/how-to-handle-errors-in-sql-54208958cd6">blog</a>, I talked about errors in SQL Server and the methods used to handle them. In this blog, I will talk more about how SQL transactions works. This blog is a continuation of information from DataCamp’s “Transactions and Error Handling in SQL Server” course. The data used for the concepts in this blog is a bank account transaction dataset, containing information from customers, accounts, and transactions.</p><h4>Transactions</h4><p>The definition of a transaction is the execution of one or more operations, such that either all or none of the operations are executed. An example of transaction using our dataset is an account transfer of $100 from one account to another. For this transaction to occur, we must first subtract $100 from one account and then add $100 to the other account. Both operations must occur for a successful transaction but if any of the operations fail, the transaction also fails.</p><p>The way a transaction occurs, with its all or nothing functionality, reflects a key property of data integrity within SQL known as <strong>Atomicity</strong>. Atomicity is reliant on the fact that transactions are either successful or can be rolled back if they failed. This ensures data integrity even if a transaction were to fail mid-way through execution.</p><p>To declare a transaction, we use BEGIN TRAN or BEGIN TRANSACTION as the starting point of the statement.</p><pre>BEGIN { TRAN | TRANSACTION }        <br>[ { transaction_name | @tran_name_variable }         <br>[ WITH MARK [ &#39;description&#39; ] ]<br>       ]<br>[ ; ]</pre><p>COMMIT is used to designate the end of a successful transaction. When COMMIT gets executed, the transaction can no longer be reversed.</p><pre>COMMIT [ { TRAN | TRANSACTION }  [ transaction_name | @tran_name_variable ] ] <br>[ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]   <br>[ ; ]</pre><p>ROLLBACK TRAN or ROLLBACK TRANSACTION is used to revert a transaction back to the beginning or a previous savepoint. I will talk more about save points later in this blog.</p><pre>ROLLBACK { TRAN | TRANSACTION }         <br>[ transaction_name | @tran_name_variable        <br>| savepoint_name | @savepoint_variable ]    <br>[ ; ]</pre><p>Going back to the previous example of transferring money between two accounts, we can perform this using our transaction statements within a TRY…CATCH block. We will declare our transaction within the TRY block using BEGIN TRAN. Our transaction will consist of changing the current_balance of the accounts appropriately to reflect a $100 transfer. Afterwards, we will COMMIT the transaction to confirm the changes. If, at any point, the transaction fails, we move to the CATCH block where we will ROLLBACK the transaction along with any operations or changes that might have taken place.</p><pre>BEGIN TRY<br>    BEGIN TRAN;<br>        UPDATE accounts SET current_balance = current_balance - 100 WHERE account_id = 1;<br>        INSERT INTO transactions VALUES (1, -100, GETDATE());</pre><pre>        UPDATE accounts SET current_balance = current_balance + 100 WHERE account_id = 5;<br>        INSERT INTO transactions VALUES (5, 100, GETDATE());<br>    COMMIT TRAN;<br>END TRY<br>BEGIN CATCH<br>    ROLLBACK TRAN;<br>END CATCH</pre><p>@@TRANCOUNT returns the number of BEGIN TRAN statements that are currently active within your instance of SQL. 0 means that there are no open transactions and any number greater than 0 represents the number of open transactions. Every BEGIN TRAN statement that is executed will increment @@TRANCOUNT by 1 and every executed COMMIT TRAN statement will decrement it by 1. ROLLBACK TRAN will decrease the value of @@TRANCOUNT to 0, unless there is a savepoint.</p><h4>Savepoints</h4><p>Savepoints are checkpoints we can set within a transaction. They allow us to rollback to simply the savepoint rather than the whole transaction. We set a savepoint using the SAVE TRAN or SAVE TRANSACTION statement. We can state a savepoint_name for ease of use.</p><pre>SAVE { TRAN | TRANSACTION } { savepoint_name | @savepoint_variable }   [ ; ]</pre><p>In the following example, we use savepoints within our transaction. We declare a savepoint after the beginning of our transaction as savepoint1 using SAVE TRAN savepoint1. We then insert into our customers table a new customer and then state ROLLBACK TRAN savepoint1. This will rollback any operations and changes that occur between the declaration and the rollback of savepoint1. At the end of this transaction, only Jeremy Johnsson will be present in the customers table.</p><pre>BEGIN TRAN;<br>-- Mark savepoint1<br>    SAVE TRAN savepoint1;<br>    INSERT INTO customers VALUES (&#39;Mark&#39;, &#39;Davis&#39;, &#39;markdavis@mail.com&#39;, &#39;555909090&#39;);</pre><pre>-- Rollback savepoint1<br>    ROLLBACK TRAN savepoint1;</pre><pre>-- Mark savepoint2<br>    SAVE TRAN savepoint2;</pre><pre>    INSERT INTO customers VALUES (&#39;Jeremy&#39;, &#39;Johnsson&#39;, &#39;jeremyjohnsson@mail.com&#39;, &#39;555929292&#39;);</pre><pre>-- Commit the transaction<br>COMMIT TRAN;</pre><h4>XACT_ABORT and XACT_STATE()</h4><p>When dealing with errors with our transactions, we have two means of controlling them. XACT_ABORT is a setting used to specify whether SQL Server will roll back a transaction when an error occurs. It can be set to either ON or OFF and by default, it is set to off. When it is set to ON, SQL Server will automatically rollback the transaction and abort the execution of the transaction if there is an error. If it is OFF, the transaction can be rollbacked or not, depending on the type of error.</p><p>XACT_STATE() is a function that returns a value depending on whether there are open transactions or not. It will return 0 if there are no open transactions, 1 for open and committable transactions, or -1 for open and uncommittable transactions. An uncommittable or doomed transaction is one that cannot be committed or rolled back to a savepoint. We can use XACT_STATE(), for example, to rollback a transaction if it returns as -1 or to commit it if it returns as 1.</p><pre>SET XACT_ABORT OFF;<br>BEGIN TRY<br>    BEGIN TRAN;<br>        INSERT INTO customers VALUES (&#39;Mark&#39;, &#39;Davis&#39;, &#39;markdavis@mail.com&#39;, &#39;555909090&#39;);<br>        INSERT INTO customers VALUES (&#39;Dylan&#39;, &#39;Smith&#39;, &#39;dylansmith@mail.com&#39;, &#39;555888999&#39;);<br>    COMMIT TRAN;<br>END TRY<br>BEGIN CATCH<br>    -- Check if there is an open transaction<br>    IF XACT_STATE() &lt;&gt; 0<br>        -- Rollback the transaction<br>        ROLLBACK TRAN;<br>    -- Select the message of the error<br>    SELECT ERROR_MESSAGE() AS Error_message;<br>END CATCH</pre><p>It was interesting to learn more about SQL Server transactions and how they work. Data integrity is a crucial step in maintaining data warehouses and the data science process. In my next blog, I will look to cover how concurrency is maintained in SQL Server. Thank you for reading!</p><h3><strong>Sources</strong></h3><p><a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/transactions-transact-sql?view=sql-server-ver15">Transactions (Transact-SQL) - SQL Server</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b90ff172a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Errors in SQL]]></title>
            <link>https://medium.com/geekculture/how-to-handle-errors-in-sql-54208958cd6?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/54208958cd6</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[error-message]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 20:10:14 GMT</pubDate>
            <atom:updated>2021-04-11T21:48:50.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Handle Errors in SQL Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*KR9QWFIbZMrlnrGQ.png" /><figcaption>Sample error message. <a href="https://www.codeproject.com/Articles/809083/SQL-server-error-details">Source</a></figcaption></figure><p>In my previous <a href="https://medium.com/geekculture/how-to-clean-data-in-sql-server-76a4103010a">blog</a>, I talked about how I wanted to develop certain aspects of my SQL skills. One such aspect that I wanted to learn more about was how to handle errors when performing SQL scripts. There may be instances upon running a SQL script that it may not execute properly and it is important to understand why this occur and how to debug this.</p><p>In this blog, I will talk about error handling in SQL using information from DataCamp’s “Transactions and Error Handling in SQL Server” course. The dataset used in this course is based on an electric bike store, containing information about Products, Buyers, Staff, and Orders.</p><h3>Error Anatomy</h3><p>Before talking about how to handle errors, I should first talk about what an error is. An error occurs when the SQL script could not be completely executed for a certain reason. This reason can be anything from a table not existing to there being an issue with the software.</p><p>Within the first line of an error message, we have valuable information as to the details of the error.</p><pre>Msg #, Level #, State #, Line #</pre><p>The first value corresponds to the error number from 1 to 49999. User-created errors start at 50001 but I will talk more about those later in the blog. A full list of every error and its details can be found <a href="https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver15">here</a>.</p><p>The second value is the severity level of the error. Level 0–10 are informational messages that serve more as warnings. Level 11–16 corresponds to errors that can be fixed by the user such as syntax errors or an object not existing. Levels 17–24 are the most severe, with them corresponding to issues like lack of resources in the software or an issue with the operating system.</p><p>The third value is the state of the error. The fourth value indicates on which line of your code that the error occurred, useful for debugging code when it goes awry.</p><p>Within SQL Server, there are prebuilt functions that are able to return details from the error message. These functions are named based on what feature they will return from the error message. ERROR_NUMBER() returns the error number, ERROR_SEVERITY() returns the error severity, and so on. These functions are commonly used within a TRY…CATCH statement.</p><h3><strong>TRY…CATCH</strong></h3><p>Suppose that in our Products table, we have a column called product_name in which we put a unique constraint on. Now, let’s say that I try to insert into Products a new item with a product_name that already exists within the table. I will receive an error that states :</p><pre>Violation of UNIQUE KEY constraint &#39;unique_product_name&#39;. Cannot insert duplicate key in object &#39;dbo.Products&#39;.</pre><p>A way of preventing this error from occurring is to use a TRY…CATCH statement. This type of statement consists of two blocks of code in which we will TRY a segment of code and if an error arises from this, control is passed to the CATCH block. A TRY block starts with BEGIN TRY and ends with END TRY. The same syntax applies for CATCH, with BEGIN CATCH and END CATCH, denoting the start and end of the CATCH block respectively. If no error occurs after performing the code within the TRY block, the CATCH block will be skipped entirely.</p><pre>BEGIN TRY<br>    {sql_statement | statement_block}<br>END TRY<br>BEGIN CATCH<br>    [{sql_statement | statement_block}]<br>END CATCH</pre><p>It is also possible to nest TRY…CATCH statements within each other. Within a CATCH block, we can have another TRY and CATCH block. In the following example, we are attempting to enter a new buyer into the buyers table. If there are errors upon trying to inserting the buyer, we want to insert a new entry into a table called errors. If that entry into errors fails, then we will print a statement acknowledging failing to insert into errors.</p><pre>-- Set up the first TRY block<br>BEGIN TRY<br>    INSERT INTO buyers (first_name, last_name, email, phone)<br>        VALUES (&#39;Peter&#39;, &#39;Thompson&#39;, &#39;peterthomson@mail.com&#39;,              &#39;555000100&#39;);<br>END TRY</pre><pre>-- Set up the first CATCH block<br>BEGIN CATCH<br>    SELECT &#39;An error occurred inserting the buyer! You are in the first CATCH block&#39;;</pre><pre>-- Set up the nested TRY block<br>    BEGIN TRY<br>        INSERT INTO errors<br>            VALUES (&#39;Error inserting a buyer&#39;);<br>        SELECT &#39;Error inserted correctly!&#39;;<br>    END TRY</pre><pre>-- Set up the nested CATCH block<br>    BEGIN CATCH<br>        SELECT &#39;An error occurred inserting the error! You are in the nested CATCH block&#39;;<br>    END CATCH<br>END CATCH</pre><p>While this statement can be useful, there are certain errors that a TRY…CATCH statement will not be able to catch. Errors with a severity lower than 11 are not catchable because they are simply warnings. In addition, errors with a severity above 20 aren’t caught if they stop the connection. A TRY…CATCH statement will also not work if we have compilation errors such as executing a script on a table or column that does not exist.</p><h3>Raising and Throwing Errors</h3><p>We also have the ability to raise errors of our own. SQL Server provides two functions to raise errors: RAISERROR() and THROW().</p><pre>-- Syntax for SQL Server and Azure SQL Database. Taken from <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver15">link</a>   <br>RAISERROR ( { msg_id | msg_str | @local_variable }       <br>{ ,severity ,state }<br>[ ,argument [ ,...n ] ] )<br>[ WITH option [ ,...n ] ]</pre><p>Within the RAISERROR() function, we have multiple parameters for the message ID, the severity and state of the error, as well as additional arguments such as strings or numbers.</p><p>In the following example, we are attempting to select a product of a given product_id from the products table. If the SELECT statement does not find the product, it will raise an error stating that “No product with id 5” was found, with a severity level of 11 and a state of 1. Note that in RAISERROR(), we are allowed to use parameter placeholder such as %s and %d unlike THROW.</p><pre>-- RAISERROR example<br>DECLARE @product_id INT = 5;</pre><pre>IF NOT EXISTS (SELECT * FROM products WHERE product_id = @product_id)<br>    RAISERROR(&#39;No product with id %d.&#39;, 11, 1, @product_id);<br>ELSE<br>    SELECT * FROM products WHERE product_id = @product_id;</pre><p>For a THROW statement, the parameters we pass in are the error number, error message, and error state. If we do not specify parameters for our THROW statement, it will re-throw the original error statement. One key note about the syntax is that THROW does not allow you to specify the severity of the error, setting it to 16 for all.</p><pre>-- Throw statement syntax. Taken from <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql?view=sql-server-ver15">link</a><br>THROW [ { error_number },  <br>        { message },  <br>        { state } ]   <br>[ ; ]</pre><p>Another key note about THROW when using it within CATCH statements is that order matters. If we place our THROW before any lines of code within the CATCH statement, it will re-throw the original error, ignoring the lines of code after it within the CATCH statement. If it is placed after, however, any code preceding it will run and then it will THROW the error.</p><p>In the following example, we are trying to SELECT all information about a member from staff with a particular staff_id. If the statement does not find a member with that corresponding staff_id, we THROW an error with error number 50001, error message stating ‘No staff member with such id’, and a state of 1.</p><pre>DECLARE @staff_id INT = 4;</pre><pre>IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = @staff_id)<br>    -- Invoke the THROW statement with parameters<br>    THROW 50001, &#39;No staff member with such id&#39;, 1;<br>ELSE<br>    SELECT * FROM staff WHERE staff_id = @staff_id</pre><p>I previously mentioned that THROW does not allow for placeholder parameters when generating an error message. We are, however, able to generate customized error messages through other means. If we generate our custom error message and declare it as a variable, we can then pass that variable within the message parameter. We can achieve this by either utilizing CONCAT() or FORMATMESSAGE() to help generate our messages with parameters.</p><pre>DECLARE @first_name NVARCHAR(20) = &#39;Pedro&#39;;</pre><pre>-- Concat the message<br>DECLARE @my_message NVARCHAR(500) =<br>    CONCAT(&#39;There is no staff member with &#39;, @first_name, &#39; as the first name.&#39;);</pre><pre>IF NOT EXISTS (SELECT * FROM staff WHERE first_name = @first_name)<br>    -- Throw the error<br>    THROW 50000, @my_message, 1;</pre><p>Those are the ways I learned how to deal with handling errors in SQL Server from this course. In my next blog, I will look to cover more about how SQL transactions work and how to ensure concurrency with SQL scripts. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54208958cd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-handle-errors-in-sql-54208958cd6">How to Handle Errors in SQL</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Clean Data in SQL Server]]></title>
            <link>https://medium.com/geekculture/how-to-clean-data-in-sql-server-76a4103010a?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/76a4103010a</guid>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 16:47:58 GMT</pubDate>
            <atom:updated>2021-04-05T22:33:17.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*_MQVJPoPMwBnYrRranyT1g.png" /></figure><p>For my blog this week, I wanted to shift gears towards developing my SQL skills further. One of the topics that I wanted to focus on was how to work with messy data and how to properly clean it. Maintaining clean data is an essential part of the data science process. It allows for easy navigation and exploration of the data for further analysis.</p><p>In order to learn more about how data cleaning is done in SQL, I took DataCamp’s<em> “Cleaning Data in SQL Server Databases”</em> course. In the course, I learned how to deal with improper string values, missing or duplicate values, converting data types, and more. The dataset that was mainly used in this course is based on USA monthly airline flights in 2014 and 2015.</p><h3>Cleaning Strings</h3><h4>Leading Zeroes</h4><p>The first exercise I had to deal with was filling numbers with leading zeroes. In the dataset provided, we have a column named registration_code which contains values of different formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*86ogqtSeGgQgM-FeNIQFLQ.png" /><figcaption>Sample of registration_code column values</figcaption></figure><p>Some values in the column contain only three digits but the correct format is with nine digits. In order to fix the values with missing digits, we need to add leading zeroes to the values that are missing zeroes. We utilize the REPLICATE() and the CONCAT() function.</p><pre>SELECT <br>CONCAT(REPLICATE(&#39;0&#39;, 9 -LEN(registration_code)), registration_code) AS registration_code<br>FROM flight_statistics</pre><p>The REPLICATE() function will repeat a string a specified number of times. For the values that have only three digits, we’ll need to add six zeroes. By getting the length of the values using LEN(), we can then subtract that length from 9 and obtain the number of leading zeroes we need to add. We then concatenate that string of zeroes with the original value and we have fixed the formatting for that column. Another way of doing this is using the FORMAT() function.</p><pre>SELECT FORMAT(CAST(registration_code AS INT), &#39;000000000&#39;) AS registration_code<br>FROM flight_statistics</pre><p>The FORMAT() function will format a value with the specified format. We cast our registration_code as an integer and then reformat it so that it consists of nine digits. Any value that does not have nine digits will be formatted to have zeroes filled in for missing digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*rNN7rt0QcETUQiO2K1x0sw.png" /><figcaption>Fixed format of registration_code column</figcaption></figure><h4>Messy Strings</h4><p>A common mistake we can find with strings are extra leading and trailing spaces. Some values of the airport_name column have extra spaces. This can be resolved using the TRIM() function which removes a specified character from the start and end of a string. In versions of SQL Server older than 2017, we utilize RTRIM() and LTRIM(), where RTRIM removes trailing spaces and LTRIM removes leading spaces.</p><pre>SELECT airport_code, TRIM(airport_name) AS airport_name, airport_city, airport_state <br>FROM airports</pre><p>There may be instances in which we have different string values within a column to represent the same value. Suppose that we wanted to query our dataset to find only the airports located in the city Chicago. In the airport_city column, Chicago is represented as ‘Chicago’ or as an abbreviation such as ‘CH’ or ‘ch’. We would want to find a way to combine these cases into one singular value for ease of analysis.</p><p>Suppose in the previous example that we wish to have only the city name spelled out. In order to replace the incorrect values, we use the REPLACE() function. REPLACE() will replace all instances of a substring with another substring we specify. Our first instinct would be to replace all instances of ‘CH’ with ‘Chicago’ but this poses a problem since it would turn ‘Chicago’ into ‘Chicagoicago’. The best way to approach this is to use a CASE statement that would only replace values that are not ‘Chicago’.</p><pre>SELECT airport_code, airport_name,<br>    CASE<br>        WHEN airport_city &lt;&gt; &#39;Chicago&#39; THEN REPLACE(airport_city, &#39;ch&#39;, &#39;Chicago&#39;)<br>        ELSE airport_city<br>    END AS airport_city,<br>airport_state<br>FROM airports<br>WHERE airport_code IN (&#39;ORD&#39;, &#39;MDW&#39;)</pre><h3>Missing and Duplicate Data</h3><h4>Missing Data</h4><p>There may be instances in which we have missing values within our columns. This can happen for a variety of reasons, such as the intentional lack of a value or some error upon inputting the data. You have a number of options at your disposal for dealing with missing data. We can choose to leave the rows with missing values as is, remove them from our queries, or use some other value as a replacement value, such as the average value for that column.</p><p>If we want to simply select all the rows where a column value is not missing, we need to add WHERE column_name IS NOT NULL to our queries. If instead we want to find the rows that have missing values for that column, we instead use IS NULL .</p><pre>SELECT *<br>FROM airports<br>WHERE airport_city IS NOT NULL</pre><p>What about the instances in which the value is not actually null but has a value such as a blank space or ‘UNKNOWN’? In the WHERE clause of our queries, we can use &lt;&gt; or = to isolate the rows we want. If we know that blank spaces are being used for null values, we can select rows where airport_city is not a blank space as airport_city &lt;&gt; ‘’.</p><pre>-- Exclude the rows where airport_city is missing<br>SELECT *<br>FROM airports<br>WHERE airport_city &lt;&gt; &#39;&#39;</pre><p>We may not necessarily want to exclude rows with null values. However, in order to proceed further, we cannot have NULL values in these columns. Suppose we wanted to use ‘Unknown’ as a placeholder value for columns in which we do have null values. To replace these null values, we use ISNULL() and state that the string we want to replace them with is ‘Unknown’.</p><pre>SELECT airport_code, airport_name,<br>ISNULL(airport_city, &#39;Unknown&#39;) AS airport_city,<br>ISNULL(airport_state, &#39;Unknown&#39;) AS airport_state<br>FROM airports</pre><p>Now let’s suppose we wanted to create a new column called location. To generate the values in this column, we wanted to pull the first non-null value from multiple columns, first from airport_city and then from airport_state. If there are null values in both columns, we will return the string ‘Unknown’ as the value for location. We will use COALESCE() which will return the first non-null result.</p><pre>SELECT airport_code, airport_name, airport_city, airport_state,<br>COALESCE(airport_city, airport_state, &#39;Unknown&#39;) AS location<br>FROM airports</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lD2o4XttrC0ydkyqs20HzQ.png" /><figcaption>Sample result from query above. Note how COALESCE works with the null columns.</figcaption></figure><h4>Duplicated Data</h4><p>Duplicated data can come in a number of forms. It may simply be repeated rows in which the values for all columns are identical. There may also be rows in which a majority of columns or only a few columns share identical values. In order to help distinguish duplicated rows that are not apparent, we will need to identify the repeating group. The repeating group consists of the columns that are meant to be identifying for a unique instance of an entity. For this dataset, airport_code, carrier_code, and registration_date are considered the repeating group since they are only registered once a month.</p><p>We will use the ROW_NUMBER() function to help identify duplicate rows. In the PARTITION BY clause, we specify our repeating group. The first instance of a will have a row number of 1, meaning it is the first instance of that particular combination of the repeating group columns. If there are multiple instances of that repeating group, their row number will sequentially increase based on the number of rows that have previously been identified.</p><pre>SELECT *,<br>ROW_NUMBER() OVER (<br>    PARTITION BY<br>        airport_code,<br>        carrier_code,<br>        registration_date<br>            ORDER BY<br>        airport_code,<br>        carrier_code,<br>        registration_date<br>    ) row_num<br>FROM flight_statistics</pre><p>If we wanted to identify solely non-duplicate rows, we will call the previous query and have it exclude duplicate rows by only finding rows with a row_num of 1.</p><pre>WITH cte AS (<br>    SELECT *,<br>        ROW_NUMBER() OVER (<br>            PARTITION BY<br>                airport_code,<br>                carrier_code,<br>                registration_date<br>            ORDER BY<br>                airport_code,<br>                carrier_code,<br>                registration_date<br>         ) row_num<br>    FROM flight_statistics<br>)<br>SELECT * FROM cte<br>-- Exclude duplicates<br>WHERE row_num = 1;</pre><h3>Converting Data Types</h3><p>The data type of a column is important in determine what operations we can perform on it. For example, we won’t be able to perform comparisons or use aggregate functions on columns of VARCHAR type. By using either the CAST() or CONVERT() functions, we can specify what data type we want to convert our columns into.</p><pre>SELECT AVG(CAST(num_ratings AS INT))<br>FROM series<br>WHERE CAST(num_ratings AS INT) BETWEEN 0 AND 5000<br>---------------------------------------------------------</pre><pre>SELECT AVG(CONVERT(INT, num_ratings))<br>FROM series<br>WHERE CONVERT(INT, num_ratings) BETWEEN 0 AND 5000</pre><h4>Date Formatting</h4><p>Dates can have a number of different formats depending on location and language. Month/day/year, day/month/year, and year/month/day are just some of the formats in which we can represent a date. If we wish to change the date format to another format, we will again need to use CAST() or CONVERT() .</p><pre>SELECT CAST(registration_date AS DATE), 101) AS registration_date<br>FROM flight_statistics<br>WHERE CONVERT(VARCHAR(10), CAST(registration_date AS DATE), 101)<br>BETWEEN &#39;01/01/2014&#39; AND &#39;06/30/2014&#39;<br>----------------------------------------------------------------<br>SELECT FORMAT(CAST(entry_date AS DATE), &#39;dd/MM/yyyy&#39;) AS entry_date<br>from pilots</pre><p>For CONVERT(), we denote the style in which we wish to convert through an integer that corresponds to a specific style. For instance , if I wanted to convert a date column to mm/dd/yyyy format, I would use 101 as the style. A list of formats that date can be converted to can be found at this <a href="https://www.w3schools.com/sql/func_sqlserver_convert.asp">link</a>. For FORMAT(), we specify the format we want with specific parameters, such as short date/long date, the actual desired order for days, months, year, and an optional language parameter. The list of available formats can be found <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-ver15">here</a>.</p><h3>Inaccurate Data</h3><p>Something we may come across in our dataset are values that are outside the range of expected values. It would be incorrect to see someone’s height listed as 400 inches or a movie rating of 11 on a 10 point scale. If we know the expected range for those values, we can query for rows in which the value for that column is BETWEEN the upper and lower limits of the range. The same applies for finding rows that are outside of the range. We can use either the BETWEEN keyword or any comparison operators like &gt;, &lt;, &lt;=, &gt;=.</p><pre>SELECT * <br>FROM series<br>WHERE num_ratings &gt;= 0 AND num_ratings &lt;= 5000</pre><p>These were some of the ways in which I learned how to clean data in Microsoft SQL Server. These techniques provide a proper starting point for most instances but every situation will be different from each other. There may be instances in which more intricate coding or other functions are required. As always, using your best judgement is crucial in determining the best approach for handling dirty data. For now, I feel as though I am more proficient at being able to properly clean my data in SQL and look forward to using what I learned in the future. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76a4103010a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-clean-data-in-sql-server-76a4103010a">How to Clean Data in SQL Server</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</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 Microsoft Power BI]]></title>
            <link>https://msf894.medium.com/introduction-to-microsoft-power-bi-bd5426558979?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5426558979</guid>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 00:05:01 GMT</pubDate>
            <atom:updated>2021-04-09T02:56:01.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*usIuvE32OZc__VOb.png" /></figure><p>Microsoft Power BI is a data visualization tool that allows its users to create visualizations, reports, and dashboards. It is one of, if not the most commonly used data visualization tool for business intelligence and possesses a large market share among Fortune 500 companies. In preparation for an upcoming job opportunity, I completed Datacamp’s “Introduction to Power BI” course to get more familiar with how it works.</p><h3><strong>Introduction:</strong></h3><p>Power BI is available for use in two ways: Desktop and Service. Desktop is the version that is accessible through your local computer. It is free to use and includes many features such as the Power Query Editor. Service is the cloud-based version of Power BI. It is used primarily for sharing and distributing reports, since it does not have as many features as the Desktop version. There is also Power BI Pro, which is a paid version that has certain capabilities, such as the ability to collaborate with other Power BI users and to publish work to the cloud platform. The version used in the course was Power BI Desktop.</p><p>Upon opening Power BI, you have three views on the interface for your datasets: Report, Data, and Model. On the Report view, you are able to create visualizations and reports. On the Data view, you see the dataset used for your reports. On the Model view, you are able to see the relationships between different tables for the data model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxBjhfhAQmIvt27m9XeI0w.png" /><figcaption>Each different view for your data in PowerBI</figcaption></figure><p>The Report view is the default view when you start. The large white space is the Canvas where all of your visualizations are created. To the right of the canvas, we have multiple sections for Filters, Visualizations, and Fields. Filters allow you to filter the visualizations. Visualizations are where you specify what type of visualization to make, such as bar graphs or donut charts. Fields are the available fields that can be used for our visualizations. We can use columns from our tables or calculated fields from our columns. It is also possible to load pre-existing reports along with the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q43Iz1k9D2rjUdquVoc6VA.png" /><figcaption>Report View</figcaption></figure><p>A key feature for Power BI’s is its interactivity for visualizations. For example, suppose we want to know our total profits for only 2016. By clicking on the 2016 bar on our chart, all other metrics and data on the canvas will change accordingly from this filter. We are able to create additional slicer filters, such as specific employees or locations, to further filter our data to our needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*KAjjFVeDezHsgm66F_CgKw.png" /><figcaption>Report to show Sales Data for only Sophia Hinton in 2016</figcaption></figure><p>Power BI is able to connect data from a variety of sources, from CSV files to webpages to SQL server databases. We load in our data and we can view the dataset in the Data view. If we have tables that are related or share a key, we are able to connect them in the Model view.</p><p>There may be times in which the data we are trying to import requires additional attention. For example, we may not need every column from the dataset or there may be formatting errors in multiple rows. In order to clean our data, we will transform our data prior to loading using the Power Query Editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0b1pgLQl6srtA5-spOz9w.png" /></figure><p>The Power Query Editor is what allows us to properly clean our data. We have a number of data cleaning actions available to us, depending on our situation. We can delete rows or columns, change data types for columns, and replace values. Anyone familiar with Excel can immediately recognize the ways we can change our data for formats like currency and date. If we have geographic data like cities or countries, we can specify it as such, allowing us to create map visualizations. In addition, there is a history of changes made to the data tracked in the Applied Steps pane, allowing us to revert to a prior step if we wish to. To finalize our changes, we select ‘Close &amp; Apply’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*XmMKsQNA30kVTGmvowm1yg.png" /></figure><h3><strong>Visualizations:</strong></h3><p>Power BI provides a number of chart types and visualizations to fit your needs. These visualizations are interactive and allow for you to hover over for more details. As expected, you have “standard” chart types like bar charts, line charts, and pie charts available.</p><p>There are also visuals that are ideal for displaying metrics for performance. Cards and multi-row cards can be used to show one or multiple values at a time. Gauge and KPI charts are best for displaying performance relative to a certain threshold or goal. We also have the ability to use Tables and Matrices to show relevant data from our datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*jvDSx_oCiE2ZODsW2jrkRQ.png" /><figcaption>Sample for Cards, Multi-row cards, Gauge charts, and KPI charts</figcaption></figure><p>When it comes to filtering or drilling down our data for visualizations, Power BI provides tools that allow us to do so easily. What is meant by “drilling down” is the ability to have a high level view of your data and the option to look at more specific aspects. These are defined as hierarchies.</p><p>Essentially, you are starting out at the top of a pyramid but you have the ability to go down or up levels as you please. Common hierarchies are aspects of dates, going from years to quarters to months, or locations, going from regions to countries to cities. We can even create our own hierarchies and rearrange the fields accordingly to match the hierarchical structure we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*kTuUaS8wO2015TP_Yl6Pbw.png" /><figcaption>Hierarchy that starts with Year, goes to Quarter, Month, Date</figcaption></figure><p>You can choose to drill down all fields on a visualization at once or specify one field at a time. Suppose we have a bar chart showing sales for 2018–2020. By drilling down all fields at once, we will end up with four bars for each quarter. These four bars represent the sum of total sales for each quarter, such as quarter one for 2018, 2019, and 2020 sales combined. If we were to select only 2019 and then drill down, we would have four bars for each quarter for 2019.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LmVL_vBs8eCJ9DIt.gif" /><figcaption>Example of drilling down from year to quarter to month. <a href="https://spreadsheeto.com/power-bi-hierarchy/">Source</a></figcaption></figure><p>Power BI also give us the ability to filter our visualizations. If we wanted to show only top N, we can easily do that by applying a filter. This is accessible through the Filters pane next to our visualizations. Any filter we create can be applied to either all pages or one specific page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*6UIbvTNBb5NSo61EJzbCLA.png" /><figcaption>Visualization filtered to show only top 5 stores by amount sold</figcaption></figure><h3><strong>Data Analysis Expressions (DAX):</strong></h3><p>Data Analysis Expressions or DAX are used to perform calculations and queries on our data. We pass in arguments into formulas in order to generate calculated columns, measures, or tables. For example, if we wanted to find out the sum of all values within a column, we call the SUM() function and pass in the column we wish to apply the function on. Anyone familiar with Microsoft Excel’s formulas will recognize the syntax used for DAX.</p><p>Suppose we wanted to generate a new column in our DimCustomer table to represent a temporary password. Our temporary password is going to be created using the last four digits of a customer’s phone number and the customer’s year of birth. To do this, we hit the New column button and write the appropriate DAX for this. We first state the name of our new column, TempPassword. Using the RIGHT() formula, we can extract the last digits from both the Phone and BirthDate columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjPwfba6Zrbl6TSwWXxxyA.png" /><figcaption>DAX needed to create our temporary password</figcaption></figure><p>We can create calculated measures for use in our visualizations. To do so, we hit the New measure button and enter the appropriate DAX formula for what we want. This measure will now appear in the Fields pane and we can now use it as part of a visualization. It can be useful to create measures using other measures to prevent redundancies. There is also a Quick Measures button that provides commonly used measures, like year-to-date total and average per category. Quick measures can be handy as they provide a way to do complex calculations without having to write any DAX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XTzh_OEUxGoqw3KT24W2g.png" /><figcaption>Calculated Measure called Average Transaction using the Average function and Sales Amount column</figcaption></figure><p>One of the most frequently used DAX functions is the CALCULATE() function. It takes in an aggregation function as well as multiple filters. This is handy for instances for which we wish to calculate a measure for a particular segment of data, such as the total sales amount of products that are colored Blue.</p><p>Using CALCULATE() is easier to rewrite and reuse than it would be if we were using simple slicers and filters. CALCULATE() is also very useful when performing time-based calculations and time analysis. If we wanted to compare our sales number for this with the numbers from last year, we can do so by using as SAMEPERIODLASTYEAR as a filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*OnLOI7jUv3XWUszeK7DY3A.png" /><figcaption>Calculating Prior Year Profits using CALCULATE() and SAMEPERIODLASTYEAR</figcaption></figure><p>By the end of the course, I came away feeling confident in how Power BI works and some of its key features and capabilities. DAX, in particular, is a powerful feature that allows its users to perform whatever calculations they require. Power BI comes across as a tool that is accessible and powerful, both important aspects when developing business intelligence tools. I completely understand now why it is so prevalent in the business world. Hopefully, I will have the opportunity to use Power BI and learn even more in the future. Thank you for reading!</p><p><strong>Sources:</strong></p><p><a href="https://learn.datacamp.com/courses/introduction-to-power-bi">https://learn.datacamp.com/courses/introduction-to-power-b</a>i</p><p><a href="https://docs.microsoft.com/en-us/power-bi/">Power BI documentation - Power BI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5426558979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to AWS Comprehend]]></title>
            <link>https://awstip.com/brief-introduction-to-aws-comprehend-a5182a8202f9?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5182a8202f9</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[aws-comprehend]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 02:45:44 GMT</pubDate>
            <atom:updated>2021-04-01T06:25:29.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d2T-zjnMRVYqU0SC.png" /></figure><p>For the final part of my blog series on AWS Boto3, I decided to take a more in-depth look at AWS Comprehend. Comprehend is a Natural Language Processing(NLP) tool that is used to find and understand sentiment within text. NLP is an important field within computing as its main concept is to understand and attribute meaning to text. As with Rekognition, Comprehend does not require you to be an expert in machine learning or even NLP in order to use it as it uses a pretrained optimized NLP model to analyze text.</p><p>Comprehend has a number of use cases for NLP. If we are trying to locate specific references to a certain subject from a swarm of documents, we can use Comprehend’s topic modeling to do so. We can discover what topics our customers are talking about and how they feel about them. There is also Amazon Comprehend Medical, which can be used to extract important medical information from unstructured text like doctor notes and test results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*X4ZoPde8gUihkS4gVi8aZw.png" /></figure><p>One of the most common use cases for Comprehend is to uncover customer sentiment based on reviews. The vast amount of unstructured data that exists on the internet, such as tweets and product reviews, can be invaluable to a business seeking feedback. As a business, we want to know what we are doing right and what we can improve on. From a passage of text, Comprehend is able to discern sentiment as being either positive, negative, neutral, or mixed.</p><p>We initialize Comprehend the same way we have with the previous services, utilizing the boto3 client. The method we call is <em>detect_sentiment</em>, passing in our text/document as well as the language code. Comprehend supports a number of languages, such as English, French, and Tagalong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*NwqzkMUdbTS2d1qg5m7J7g.png" /></figure><p>The response we receive is a JSON containing the text’s sentiment Comprehend is most confident in and the sentiment score for the four categories. Sentiment scores are read as the probability that the text’s sentiment can be described by its categorization. For the image below, it is 98% likely that the text analyzed by Comprehend had a positive sentiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*Mfjh1ujAG-QvoIDb_1kSBg.png" /><figcaption>Sentiment for the text in the image above</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YZU0DGlItCZjOUt2ibkbw.png" /><figcaption>Detected sentiment for reported problems requests</figcaption></figure><p>The final case study for the course was to analyze residents’ sentiments towards an increased use in scooters around the community. The way this was done is by analyzing the sentiment of all residential requests involving scooters. However, the dataset containing all of the service requests is not solely in English, but other languages as well. This is not a problem, as Comprehend has a <em>detect_dominant_language</em> method that can be used to determine what language the request is in. We will then use the language code from the detected language and determine what is the overall sentiment of the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*W89qR4HeXOlimPhRDaiI6w.png" /><figcaption>Code for detecting sentiment across requests of different languages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*gVxRFcun1NDXntgLAkxJPA.png" /><figcaption>DataFrame grouped by sentiment and language columns</figcaption></figure><p>I came away from the end of the course amazed and excited for what AWS is capable of. The fact that complex concepts and fields of computation have been streamlined for mainstream use is something to admire. A few lines of code is all that’s needed for me to discern what my customers are saying about my products. Small or large business owners are able to engage with their data in a meaningful way and gain valuable insights that would normally take a significant amount of time and money.</p><p>The full documentation can be found at this <a href="https://docs.aws.amazon.com/comprehend/latest/dg/comprehend-general.html">link</a>. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5182a8202f9" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/brief-introduction-to-aws-comprehend-a5182a8202f9">Brief Introduction to AWS Comprehend</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to AWS Rekognition]]></title>
            <link>https://msf894.medium.com/brief-introduction-to-aws-rekognition-2fcab9f28e55?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fcab9f28e55</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[rekognition]]></category>
            <category><![CDATA[image-recognition]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 02:11:09 GMT</pubDate>
            <atom:updated>2021-03-15T02:11:09.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*2th8vNZcRosgschA.png" /></figure><p>One of the last segments of the course mentioned in these <a href="https://msf894.medium.com/introduction-to-boto3-and-s3-1be753dd1f28">previous</a> <a href="https://msf894.medium.com/brief-introduction-to-aws-sns-using-boto3-5f917bcc1d78">blogs</a> was about Amazon Rekognition. Even though it was discussed for merely half of this section, I was fascinated enough by this small tidbit that I wanted to delve deeper into how it works and how it is used.</p><p>Amazon Rekognition is a computer vision service that provides for automatic image and video analysis for identifying objects, such as faces or text. Conventional means for identifying objects of interest involves having individuals tediously going through multiple images and is prone to errors and increasing costs. This also provides difficulty in properly scaling if we are dealing with large quantities of images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OHJKILQqKJCEb5fu.png" /></figure><p>This is where Amazon Rekognition excels, by providing a highly accurate and scalable deep learning API. It is pre-trained and highly optimized for image and video recognition tasks. An important advantage of using Rekognition is that it does not require its users to be experts with computer vision or deep learning models. Rekognition has a wide variety of use cases, from usage in facial search and recognition, text detection, as well as moderation for inappropriate content.</p><p>The course provides examples of how we would use Rekognition for object detection within an image and text detection. In this first example, we are trying to identify bicycles as they pass by a camera. In order to utilize Rekognition using Boto3, we must first provide it with images. We can do this by first initializing the S3 client and then upload a file through its respective method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*C4dyOLHAZWyVHgToafu6ow.png" /></figure><p>After this, we construct the Rekognition client using Boto3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*60V8zVqaUMI7jb7I4V5F4A.png" /></figure><p>For the purpose of object detection, we will call the detect_labels method. Within this method, we specify the image and two optional parameters: MaxLabels and MinConfidence. MaxLabels is the maximum number of labels or objects that we wish to have in our response and MinConfidence is the minimum confidence that Rekognition must have in accuracy for a detected label. In the example below, Rekognition will list only up to 10 labels and labels that were detected with a 95% confidence in its accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*bYl3_xUShyiJUv6lHvuZhQ.png" /></figure><p>The response from detect_labels is an array of labels detected in the image. This response will list all labels detected within the image as well as the respective confidence for those labels. In addition, there is a list of label instances that contains bounding box information. The bounding box information corresponds to the label’s location within the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*dMjeRc7aljaCp1iJxiTRfA.png" /><figcaption>Sample of the detect_labels response for image below</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Ufgvuiy9D3XQkR-FbNjdOw.png" /><figcaption>Rekognition sees a bike, multiple cars, and a person in this image. Note the bounding boxes for each car, the bike, and the person.</figcaption></figure><p>Text detections works in a similar way, using the detect_text method and passing in the image. This response contains two types of detections: lines and words. A word is defined as any combination of characters that isn’t separated by a space. A line is a continuous string of words that has no more text after it. This can prove difficult if, for instance, we are dealing with text detection for two adjacent signs. The response also contains the geometry information of the bounding box for the text’s location on the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*JEfO7uWFp36kDxsIcS28bg.png" /><figcaption>Image used for following examples below</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*s7vT2iA9xr7Bo65Yec7MJQ.png" /><figcaption>All words detected in the image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*m7LDTnOJW_CVHg3qL73zIw.png" /><figcaption>All lines detected in the image</figcaption></figure><p>It was interesting to see how the complex and intricate field of computer vision can be made so accessible for business use cases. The speed and accuracy of Rekognition allows for large companies to help greatly reduce turnaround for recognition tasks. It also provides a way to perform image detection without requiring much prior knowledge of how machine learning models work. The documentation for Rekognition can be found <a href="https://docs.aws.amazon.com/rekognition/latest/dg/what-is.html">here</a>. In the next blog, I will look to cover how Amazon Comprehend works for sentiment analysis. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fcab9f28e55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to AWS SNS using Boto3]]></title>
            <link>https://msf894.medium.com/brief-introduction-to-aws-sns-using-boto3-5f917bcc1d78?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f917bcc1d78</guid>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[datacamp]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 20:06:04 GMT</pubDate>
            <atom:updated>2021-03-07T20:06:04.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HVshVr2UhxwOmMOw.png" /></figure><p>Continuing along with the course mentioned in the <a href="https://msf894.medium.com/introduction-to-boto3-and-s3-1be753dd1f28">previous blog</a>, the next part covered notification services using SNS. Simple Notification services or SNS are crucial when dealing with applications or data pipelines. They allow you to reliably send notifications directly to users for monitoring or alerting. In this blog, I will cover how SNS works and is used for SMS and email alerts.</p><p>In order to create an SNS topic, you must first initialize a Boto3 client for SNS. Initializing still requires a valid access key id and secret access key. Creating a topic is done by calling the <em>create_topic</em> method and stating the name for the new topic. This generates a unique identifier for the topic called a topicARN key. An important caveat to know is that creating topics with the same name as a topic that exists will return the ARN of the existing topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*8mtGcojJgr76CPXAd8iWkw.png" /><figcaption>Creating a ‘city_alerts’ topic through SNS</figcaption></figure><p>In order to list all the topics we are subscribed to, we call the <em>list_topics</em> method. We get a response listing all the topic ARN keys that we have access to. We can also delete a topic by calling in the <em>delete_topic</em> method and passing in the ARN key for the topic we wish to remove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*3bU2VZsnFM97BE4xmn8Tlg.png" /><figcaption>Deleting topics that don’t have ‘critical’ within their ARN key</figcaption></figure><p>Each subscription to a topic has a unique ID (<em>subscriptionARN</em>), an endpoint, a protocol, and status. The delivery protocol refers to how the message is transmitted, such as email, http, or SMS (text messages). The endpoint is the specific address that the message should be sent to. The status of a subscription can either be ‘confirmed’ or ‘pending confirmation’. ‘Pending confirmation’ is used for emails and requires the user confirming the subscription through an separate email containing a confirmation link.</p><p>To create a subscription, we call the <em>subscribe </em>method and pass in the ARN, protocol, and endpoint we wish to use. Deleting subscriptions uses the <em>unsubscribe</em> method and pass in the subscriptionARN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*gjP8E5GzzyTdwrJZ41qONA.png" /><figcaption>Creating SMS/phone subscriptions to the streets_critical topic and printing their respective subscription ARN</figcaption></figure><p>To publish a message to a topic, we use the <em>publish </em>method and pass in the topicARN, along with the message and subject as arguments. This message will then be broadcasted to the subscribers of the topic, who will receive notifications based on the delivery protocol. We also have the ability to send one-off messages to a phone number by simply specifying the phone number and message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*6iLJ4MuRBPjlJdAd0m4GAQ.png" /><figcaption>Creating a custom message that sends an alert if there are over 100 potholes</figcaption></figure><p>The final exercises for this part of the course were for a case study in building a notification system for critical issues for a City Council. We are asked to create a multi-level topic system(critical and extreme) for each city department based on the number of complaints. An extreme alert is considered more serious than a critical alert. A critical topic will alert the staff and managers of that department and an extreme topic will alert politicians and directors. Thus, we have different sets of subscribers depending on the threshold reached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*uXCnP1A4D2TjkXqE3yb0GA.png" /><figcaption>Create multi-level topics for each department</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*sEA-ob0jHbB5AY1hBkoXag.png" /><figcaption>Setting up subscription lists. ‘Critical’ topics subscribers will receive emails and ‘extreme’ topic subscribers will receive text messages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*XzgHprUJo-UXaIluyuhqSg.png" /><figcaption>Creating different messages for critical and extreme alerts</figcaption></figure><p>This was a very basic introduction to SNS as the course does not cover a number of features such as integration with other AWS services, message ordering/filtering, and topic encryption. However, Amazon does maintain <a href="https://docs.aws.amazon.com/sns/latest/api/Welcome.html">documentation</a> for the API to learn more about some of these features. In the next blog, I will look to cover more advanced services, specifically AWS Rekognition and Comprehend. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f917bcc1d78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Boto3 and S3]]></title>
            <link>https://medium.com/swlh/introduction-to-boto3-and-s3-1be753dd1f28?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be753dd1f28</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[datacamp]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 22:08:09 GMT</pubDate>
            <atom:updated>2021-02-28T22:08:09.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*erfs-GJSYCtxtDs2.png" /></figure><p>In a time where datasets are getting larger and the needs of a business are growing in costs, many have turned to cloud computing as a means to mitigate both of these issues. With this increased interest, it is no wonder that Amazon Web Services (AWS) has become increasingly popular over the past couple of years. Parallel or cloud computing provides a level of flexibility and scalability that allows users or businesses to adjust accordingly to their needs.</p><p>AWS has hundreds of services, from cloud storage using S3, notification services with SNS, and even sentiment analysis using Comprehend. Boto3 is the library that allows a user to create and configure AWS instances using Python. In this blog, I will cover the basics of using Boto3 based on information from DataCamp’s “Introduction to AWS Boto in Python” course.</p><h3>Intro to Boto3 and S3</h3><p>Boto3 is a package that must first be installed and imported before using. Before using Boto3, you need an AWS account with the appropriate authentication credentials. In order to initialize a service, you need a valid access key id and secret access key, similar to needing a username and password. To do so, we can use the Identity Access Management (IAM) Console or the AWS Command Line Interface (CLI). We can also create sub-users to control who has access to our account’s AWS resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*OjuhdfZ3qA3vuIgvpLH3TA.png" /><figcaption>Creating a S3 client using our credentials in Boto3.</figcaption></figure><p>First, we go into a little more detail about cloud storage with S3 and how it works. The key feature of S3 is that it allows us to put any file into the cloud and have it be accessible anywhere through a URL. The way S3 functions is through the use of so-called <strong><em>Buckets</em> </strong>and <strong><em>Objects</em></strong>. Buckets act like folders in a file system and they must have a unique name. We can perform operations on buckets such as creating new ones, listing all buckets we have in our account, and deleting buckets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*FlgZ2h4b9P14yUV0N3bCpg.png" /><figcaption>Creating multiple buckets with Bucket names and the response to confirm creation of ‘gim-staging’ bucket.</figcaption></figure><p>We store objects within our buckets. An object can be any type of file from a simple text file to video and audio files. An important feature of an object is its key, which is path of the object from the bucket’s root. Objects can only be in one parent bucket at a time. We can upload, download, and delete files from our buckets as well as pull metadata about any object using the head_object method. Listing all of the objects within a bucket is done with the list_objects method. We can also use this method to search for specific objects, such as ones that start with a particular prefix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*eRFQmVdAa7gf7pfuHw3asw.png" /><figcaption>Uploading a csv file to gid_staging and retrieving its ContentLength through the head_object method.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tGf5fAjghTJen6wiTTJqPA.png" /><figcaption>Listing all objects within the bucket that start with ‘2018/final_’ and deleting them from the bucket.</figcaption></figure><h3>Uploading and Sharing Files Securely</h3><p>While working with objects, we may have certain files that we wish to keep private or limit who has access to them. The default permission for newly uploaded files in S3 is denied permission except for the account’s key and secret. This means that we will have to set opt-in public access to our objects rather than having public access by default. There are multiple ways to control permissions within S3.</p><p>Again, we can use IAM to limit or allow specific users’ access to AWS services and objects. Bucket policies allow us to control permissions on a particular bucket and any objects in it. We also have access control lists (ACLs) which let us denote permissions on specific objects within a bucket.</p><p>When we upload a file to a bucket, its default ACL is set to ‘private’. We can set the ACL to ‘public-read’, allowing anyone to download the file, through the put_object_acl method or passing in an extra argument upon uploading the file. Once an object is public, it can be accessed at a public URL of the format <strong><em>&lt;bucket_name&gt;</em></strong><em>.s3.amazonaws.com/</em><strong><em>&lt;objectKey&gt;</em></strong><em> .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*Ja56jRaglhy4eCuRCUumJw.png" /><figcaption>Passing in an extra argument for public-read ACL upon uploading a file.</figcaption></figure><p>In addition, you can grant temporary access to private files using pre-signed URLs. These are URLs that are meant to expire within a time limit. These are generated through the generate_presigned_url method, in which we define the time limit after which the link expires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*bDpXYxs8hEllzxgo9z6GvQ.png" /><figcaption>Generating a pre-signed URL that expires in one hour.</figcaption></figure><p>S3 is also able to host static HTML pages. This allows us to share our analysis and results with other people. For instance, we can take one of our DataFrames and have it render as a HTML table using Pandas’ to_html method. We can even use this to create an index page, listing multiple HTML links and files that we wish to share. We do this by listing the objects within a bucket that we wish to share, converting the response to a DataFrame, and then creating URLs using a base URL along with the object’s key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*HHE-ujgrJqIT7IPLMMTAHQ.png" /><figcaption>Converting a dataframe to HTML and having its URLs converted to hyperlinks.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*4iD_VZ-b-OXV2p8ohP6qVQ.png" /><figcaption>Creating an index page.</figcaption></figure><p>This was just a small sample of what S3 in AWS can do and how Boto3 is used to interact with our instances. In the next blog, I will cover how AWS automates notification services through SNS and how AWS Rekognition works with text comprehension and image detection. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be753dd1f28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/introduction-to-boto3-and-s3-1be753dd1f28">Introduction to Boto3 and S3</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to Apache Airflow —  Part 2]]></title>
            <link>https://msf894.medium.com/brief-introduction-to-apache-airflow-part-2-468718d26acd?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/468718d26acd</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[datacamp]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 22:53:19 GMT</pubDate>
            <atom:updated>2021-02-21T22:53:19.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>Brief Introduction to Apache Airflow — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*gZUW2Re1rlAAGCe7daRJnw.png" /></figure><p>Continuing along after my first <a href="https://msf894.medium.com/brief-introduction-to-apache-airflow-through-datacamp-133432a9dd70">blog</a> on Apache Airflow, the next sections of the course were about using sensors, executors, templates and putting all the information together towards building a production-quality workflow.</p><p><strong>Sensors </strong>are operators that wait for a specific condition to be true. This can be a condition such as whether a file was created or whether an upload to a database record occurred. In addition to the standard operator attributes, sensors have unique attributes regarded how to check for a condition. Mode determines how the sensor checks for the condition. The default mode is ‘<em>poke</em>’ in which the sensor continuously checks until the condition is complete. A <em>poke_interval</em> can be set to tell the sensor how often to wait in between checks and a timeout field denotes how long to wait before failing the sensor task. Another mode is ‘<em>reschedule</em>’, which means a worker slot is given up and the sensor tries again later.</p><p>One example of a sensor is <em>FileSensor</em>, which checks to see if a file exists at a specific location within a file system. Other sensors include <em>ExternalTaskSensor</em>, which waits for a task within another DAG to be completed first and <em>HTTPSensor</em>, which checks for content within a provided web URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*1AAlKekQj5OWaAhXLsrwNQ.png" /><figcaption>Sample code for a FileSensor task. The filepath set to ‘salesdata.csv’ means that it checks for a file with this name before continuing. This file sensor task runs after initi_sales_cleanup but before generate_report.</figcaption></figure><p>Sensors are useful for when you wish to check if a condition is true but are unsure when exactly is will be completed. Since you can set how often to check the condition, a sensor can continuously check until it is true. A sensor can also be added if we do not wish to immediately fail a DAG when a condition is not satisfied.</p><p><strong>Executors</strong> are what run the tasks that are defined within your workflows. There are different executors available depending on your needs and you can even create your own if desired. The default Airflow executor is the appropriately named <em>SequentialExecutor </em>which runs a task one at a time. Since it is run one at a time, it can be useful for debugging workflows that may not succeed. The fact that it is run sequentially means it is not recommended for large scale workflows since it is limiting for run-time and resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvDitrUoodvzAJrwDLnigQ.png" /></figure><p><em>LocalExecutor</em> runs all tasks on a single system. Each task is treated as a process and it is able to run as many tasks concurrently as allotted by the user or the system’s available resources. This makes it ideal for any single system production system as it allows for all available resources within that system to be used for executing the tasks. <em>CeleryExecutor </em>utilizes Celery, a Python queueing system, to set up multiple systems as a cluster. This is more suitable for large workflow configurations that may require further scaling.</p><p>In order to report the statuses of tasks, Airflow allows for the ability to get an email alert if, for instance, a task succeeded. The expected amount of time for a task or a DAG to run is referred to as its <em>SLA </em>or <em>Service Level Agreement</em>. An SLA Miss means that a task or DAG exceeded the expected time to be completed. This miss gets chronicled through an email alert and a note made in the system logs. SLA Misses can also be viewed through the Airflow web UI. This SLA is determined either through a ‘<em>sla</em>’ argument on the individual task or a dictionary of arguments for any tasks, using the timedelta function from the datetime library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*AdqAzm16nFVZABtM5aRADA.png" /><figcaption>Defining a task SLA as 3 hours through the sla argument</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ts6F4wGWJHco5jk-YKB8GA.png" /><figcaption>Code for creating an EmailOperator task to send an email once generate_report is completed</figcaption></figure><p>A useful aspect when creating multiple tasks is the ability to use <strong>templates </strong>within Airflow. Templates allow for the substitution of data when defining tasks. They are especially useful if we are creating multiple, repetitive tasks. For example, if we are creating tasks to echo a list of files, we could define a task for each file within that list, but that process can get very repetitive if we are dealing with numerous files. Instead, we can set the bash command to a previously defined templated command and pass in a dictionary of parameters for the template to use. We can define a filename string and pass it to the command and the tasks will properly run. You can also create more advanced templates, such as iterating over a list, since Airflow utilizes the Jinja templating language. <em>Macros </em>are variables that Airflow provides to be used for passing in objects to templates, such a datetime or timedelta object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RjTiATn_7mLAc8ZjPriSQ.png" /><figcaption>Comparison of code for defining multiple tasks to echo a list of files: no template command (left), templated command (middle), templated command with iterative list</figcaption></figure><p>The final sections of the course involved using all the knowledge gained towards implementing a workflow into a production pipeline. By the end of this course, I felt as though I had gained a respectable amount of introductory information on Airflow. Getting to see how all these parts work together and help make workflows automated was fascinating. I understand now how powerful a tool like this can be and why it is widely used. I would like to dig deeper into some of Airflow’s documentation and look into potentially setting up my own environment to tinker around with. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=468718d26acd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Introduction to Apache Airflow Through DataCamp]]></title>
            <link>https://msf894.medium.com/brief-introduction-to-apache-airflow-through-datacamp-133432a9dd70?source=rss-53a265c77f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/133432a9dd70</guid>
            <category><![CDATA[datacamp]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[Michael Flores]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 04:09:19 GMT</pubDate>
            <atom:updated>2021-02-15T04:09:19.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJsMPN5kPMI7JuqhsaP7rA.png" /></figure><p>Many companies have been forced to adapt their work organization and structure for their employees working from home due to COVID-19. As a result of this, parallel computing or cloud computing has become much more prevalent due to cost optimization and the fact that certain data centers may not be as easily accessible anymore. In preparation for an upcoming interview, I decided to further my knowledge on the technologies and processes used in data engineering that make this new work structure possible. One such technology that I’ve heard of but have not had a prior chance to work with was Apache Airflow. Since I’ve not had much prior experience with it, I decided to take DataCamp’s “Introduction to Airflow in Python” course to learn more.</p><p>The primary aspect that Airflow is used for is programming data engineer workflows. A workflow refers to the set of steps required in order to accomplish a certain task. These workflow tools exist in order to ensure that dependency requirements are fulfilled to execute the tasks, such as ensuring that a dataset is filtered prior to another computational process. Task dependencies are designated as either upstream or downstream tasks, where an upstream task must be done before a downstream task. The way that Airflow implements its workflow is through directed acyclic graphs or DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*gBHghhpp-d5Hs1YI0xWOYA.png" /><figcaption>Example DAG for a workflow</figcaption></figure><p>Within Airflow, a DAG represents the tasks and dependencies between tasks and contains identifying information such as the name of the workflow and the owner. Being directed means there is a particular flow with respect to the order of operations between each component. Acyclic means that the workflow does not repeat itself. However, it does not mean that the entire operation cannot be rerun, simply that the individual components are executed only once. Each component or task makes up a vertex of the DAG.</p><p>In order to work with DAGs, you use the airflow command line tool and the numerous subcommands available. These subcommands are used to control many operations and aspects of our DAGs, such as running a DAG or setting up a scheduler for all tasks and DAGs. DAGs are written in Python but can use components in other languages if needed. Airflow also has a web UI that is useful for monitoring and developing workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*LXyFIzrYu7zfzM2wfGZZLw.png" /><figcaption>Code to create a DAG object named ‘example_etl’ with arguments dictionary</figcaption></figure><p>Operators represent a single task within a workflow. They run independently, meaning that all the resources needed to complete the task are contained within that operator. Various operators are used in order to perform certain tasks. BashOperator, for instance, executes Bash commands and scripts. DAGs can contain numerous operators that perform different tasks depending on what is needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*w9aS8DAOvJO77q5V6gKjiw.png" /><figcaption>Code for instantiating multiple BashOperators with different commands</figcaption></figure><p>A DAG run refers to an instance of a workflow at a given time. A DAG could be currently running, have failed, or was successfully completed. We can view all DAG runs and their state through the Airflow UI. Scheduling a DAG to run automatically allows for multiple attributes depending on your needs. A <em>start_date</em> is specified for a date/time to initially schedule the DAG. There are other optional attributes, such as <em>max_tries</em> for a number of attempts to retry before failing a DAG run, or <em>schedule_interval</em> to specify how often to schedule a DAG run.</p><p>There are certain peculiarities when scheduling DAGs that need to be mentioned. You can state a start date and end date, but this is not a guarantee of a DAG running within this range, rather a minimum/maximum value of when it could be scheduled. In addition, when using a start date and a schedule interval, Airflow will schedule the DAG once at least one schedule interval has passed beyond the start date. For example, if I scheduled a DAG to run daily and stated the start date as February 14th, Airflow would use February 15th as the earliest possible date for the first run of the DAG. This can cause some issues when dealing with workflows with longer intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*XRDNR8uUvLPCgvbMmhxnZw.png" /><figcaption>Code to schedule a DAG to run every Wednesday at 12:30</figcaption></figure><p>The schedule interview can be defined by certain presets or with a cron style syntax. Airflow presets include @once, @daily, @monthly, among others. Using a cron expression, a string comprising of five or six fields representing a set of time, enables for more specificity when scheduling your workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*P9KmM449QxCJa3Pd0irlqg.png" /><figcaption>Cron expression format for schedule interval <a href="https://ostechnix.com/a-beginners-guide-to-cron-jobs/">Source</a></figcaption></figure><p>In the next segment of this blog, I hope to cover monitoring Airflow workflows and learning how to build production pipelines. I look forward to covering more of Airflow and other cloud computing technologies to help broaden my knowledge and skills further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133432a9dd70" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>