<?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 Jaime Andres Salas on Medium]]></title>
        <description><![CDATA[Stories by Jaime Andres Salas on Medium]]></description>
        <link>https://medium.com/@jsalasmoreira?source=rss-dfe37d6c325------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wM6P4V-uHDgmE4gVPOPvrg.jpeg</url>
            <title>Stories by Jaime Andres Salas on Medium</title>
            <link>https://medium.com/@jsalasmoreira?source=rss-dfe37d6c325------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:42:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsalasmoreira/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 Iceberg the Unofficial Review — Part 1 Iceberg Architecture]]></title>
            <link>https://blog.infostrux.com/apache-iceberg-the-unofficial-review-part-1-iceberg-architecture-7bfabed461de?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bfabed461de</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 12:57:23 GMT</pubDate>
            <atom:updated>2024-08-20T12:57:23.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Iceberg Series: Part 1 — Iceberg Architecture</h3><h4>Apache Iceberg 100</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vflpEq5uN2fJyXbfZdOMWQ.png" /><figcaption>Picture by <a href="https://unsplash.com/@rodlong">Rod Long </a>on Unsplash.</figcaption></figure><p>I began learning about Apache Iceberg this year. However, a few weeks ago, I decided to dive deeply into the technology, understand its advantages compared to other technologies, and understand why many large companies are considering migrating to Iceberg or exploring it as a potential solution.</p><p>So, we will explore what I learned and my thoughts about the Apache Iceberg and why I consider it the future of Data Engineering. If you want other resources, Infostrux, we have started creating blogs and investigating the integration with Snowflake.</p><p>Here is an <a href="https://medium.com/snowflake/an-overview-of-snowflake-apache-iceberg-tables-d5e85864ac99">overview of Snowflake Iceberg tables</a> from an Infostrux Colleague.</p><h3>Introduction</h3><p>Apache Iceberg is a “new technology” that impacts the table format world. It was created by Netflix and Apple and donated to the Apache Foundation.</p><p>Iceberg tables have the same capabilities and functions as traditional SQL tables. They are fully open and accessible, allowing multiple engines (such as Snowflake and Spark) to work with the same dataset. Iceberg offers a variety of features, including:</p><ul><li>Multiple applications can have transactional consistency. Files can be added, removed, or modified atomically. Complete read isolation is ensured. Multiple concurrent writes are allowed.</li><li>Track changes to a table over time by fully evolving the schema.</li><li>Travel time to examine historical data and confirm changes made during updates.</li><li>The partition layout and evolution allow for updates to partition schemes as queries and data volumes change. This is achieved without relying on hidden partitions or physical directories.</li><li>The system offers advanced planning and filtering capabilities to ensure high performance when processing extensive volumes of data.</li></ul><p>All these features are possible because of how Iceberg works with the metadata files. Iceberg maintains the complete history in its table format without relying on storage systems. This allows for an open architecture and the ability to switch systems without affecting users or current workloads. So, let’s explore the architecture of Apache Iceberg more.</p><h4>Apache Iceberg Architecture</h4><p>Conceptually, Iceberg‘’’s various components can be categorized into three distinct layers, as depicted in the following schema.</p><figure><img alt="Diagram from Dremio" src="https://cdn-images-1.medium.com/proxy/1*uwxfAGml8Hn42iM2k617zQ.png" /><figcaption>Diagram from <a href="https://www.dremio.com/blog/a-hands-on-look-at-the-structure-of-an-apache-iceberg-table/">Dremio</a></figcaption></figure><ol><li><strong>Catalog Layer</strong> The catalog contains references to the current metadata pointer, which refers to each table&#39;s most recent metadata file. The catalog is the initial component that the query engine interacts with, regardless of whether it is a read or write operation.</li><li><strong>Metadata Layer</strong> The metadata layer in Apache Iceberg consists of three components: metadata files, manifest lists, and manifest files.</li></ol><ul><li><strong>Metadata files</strong> contain data about an Iceberg table at a specific moment. This data includes the table’s structure, partition details, snapshots, and the current snapshot.</li><li><strong>Manifest list</strong> is a snapshot of an Iceberg table at a specific time. It includes a list of all the manifest files, their location, partitions, and upper and lower bounds for partition columns. These files track datafiles for the table.</li><li><strong>Manifest files</strong> track data files and delete files in the data layer. They also include details and statistics for each file, such as the minimum and maximum values for columns in a data file.</li></ul><p><strong>3. Data Files</strong> contain the data. Apache Iceberg supports various file formats, such as Apache Parquet, Apache ORC, and Apache Avro. This benefits organizations as they can choose the most suitable format for their application.</p><p>In this way, Iceberg can handle metadata-tracked problems that were previously very complex, for example, the concept of partitioning, which can be updated without the need to recreate the entire table because the metadata tracks not only partition values but also historical partition schemes, allowing the partition schemes to evolve.</p><p>Let’s explore more details with an example:</p><h4>Snowflake Tutorial</h4><p>In this example, we will explore the metadata files we created when creating a new table using Snowflake or other services like Spark. You can follow the steps in the <a href="https://docs.snowflake.com/en/user-guide/tutorials/create-your-first-iceberg-table#create-an-iceberg-table">First Iceberg table tutorial</a> from Snowflake. We will explore only the next steps for this tutorial.</p><p><strong>Create a new Iceberg Table</strong></p><p>We can create a new table with the following code; before being able to execute this code, I recommend following the Snowflake tutorial.</p><pre>CREATE OR REPLACE ICEBERG TABLE nation_iceberg (<br>  n_nationkey INTEGER,<br>  n_name STRING<br>)<br>  BASE_LOCATION = &#39;nation_iceberg&#39;<br>  AS SELECT<br>    N_NATIONKEY,<br>    N_NAME<br>  FROM snowflake_sample_data.tpch_sf1.nation;</pre><p>Now, you can find the following infrastructure in the S3 bucket for this table.</p><figure><img alt="Bucket folder for the Iceberg table" src="https://cdn-images-1.medium.com/proxy/1*iRRe8UbKyJmPJVwlkffUww.png" /><figcaption>Bucket folder for the Iceberg table</figcaption></figure><p>Here, we can see more details in the data folder.</p><figure><img alt="Data Folder for Iceberg Table" src="https://cdn-images-1.medium.com/proxy/1*EY4da--yl4aul_M-WST0xg.png" /><figcaption>Data Folder for Iceberg Table</figcaption></figure><p>The Iceberg Table has a tree structure that stores data snapshots for every DML/DDL operation. The metadata folder contains multiple metadata.json files. A new metadata file is created each time a DML or DDL operation is performed.</p><figure><img alt="Metadata Folder for the Iceberg Table" src="https://cdn-images-1.medium.com/proxy/1*yDKuDTIr1oE2PR-H6MO1dA.png" /><figcaption>Metadata Folder for the Iceberg Table</figcaption></figure><p>We will explore the metadata json file and how this works.</p><figure><img alt="Image by Author: Metadata json content" src="https://cdn-images-1.medium.com/proxy/1*CxiCskcRxLTay8aVU9u9Eg.png" /><figcaption>Image by Author: Metadata json content</figcaption></figure><p>So, how does all the magic of Iceberg work from the inside? As you can see, there are details of the Schema, Partition, Snapshots, and a summary of the changes in this new version. This allows Iceberg to keep track of all the changes within the table through metadata, simplifying the process of changes without having to rewrite a table. It also improves performance in data queries.</p><p>Let’s reinforce this concept by going through this step-by-step example.</p><ol><li>We created a new table in Iceberg; when doing this, the Metadata file is made for this table with the first Snapshot only with the table schema.</li><li>We perform an insert into the table, resulting in a V2 of the metadata file, as it is necessary to understand the changes in this new version of the table, which you can better understand in the Summary. This creates a new Snapshot containing the latest version of said table.</li><li>Once the engine has learned the table schema and partitioning scheme, it will begin writing new datafiles and related metadata files. These records will be written into an hourly defined partitioning scheme for the table. If a sort order is specified, the records will be sorted before being written into the datafile.</li><li>After writing the data file, the engine creates a manifest file. This file contains the path of the data file and statistical information, such as column bounds and null value counts. Pruning files helps the query engine optimize performance.</li><li>The engine creates a manifest list to track the manifest file. Existing manifest files associated with this snapshot have also been added to the new list. The engine writes this file to the data lake, including information such as the file’s path, the number of data files/rows added or deleted, and partition statistics like the lower and upper bounds of the partition columns.</li></ol><p>In the following schema, you can see the steps mentioned above and the data created with the example in Snowflake. This lets us understand how data insertion is handled in Iceberg tables. It allows us to manage versions and changes in our tables without worrying about changes that have to be made to rebuild the table because we can manage versions of the metadata and adapt our tables, for example, to the logic of the business without significant problems.</p><figure><img alt="Image by Author: Iceberg component’s after executing the Insert" src="https://cdn-images-1.medium.com/proxy/1*ygh-8TA7glMQHN3CSemVyQ.png" /><figcaption>Image by Author: Iceberg components after executing the Insert</figcaption></figure><h3>Conclusion</h3><p>Iceberg is a highly effective solution for revolutionizing data storage in warehouses and data lakehouses. Its open-source nature enables seamless integration with various platforms, including Snowflake and Databricks. With its rapid growth, it is poised to become a standard in the data industry. While it still requires further development, it is making significant strides towards establishing itself as a leading technology in the years to come. In the upcoming installment of this series, we will delve into the various methods available for optimizing Iceberg, which undoubtedly have the potential to be game-changing.</p><p>I’m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux’s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><h4>Sources:</h4><ul><li><a href="https://www.dremio.com/blog/a-hands-on-look-at-the-structure-of-an-apache-iceberg-table/">https://www.dremio.com/blog/a-hands-on-look-at-the-structure-of-an-apache-iceberg-table/</a></li><li>Apache Iceberg: The Definitive Guide: Data Lakehouse Functionality, Performance, and Scalability on the Data Lake</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bfabed461de" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/apache-iceberg-the-unofficial-review-part-1-iceberg-architecture-7bfabed461de">Apache Iceberg the Unofficial Review — Part 1 Iceberg Architecture</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 2]]></title>
            <link>https://blog.infostrux.com/enhancing-llm-performance-prompt-engineering-in-snowflake-cortex-part-2-fb9687b92a29?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9687b92a29</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 14 May 2024 13:37:34 GMT</pubDate>
            <atom:updated>2024-05-14T16:03:19.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 2</h3><h4>Prompt Engineering Best Practices — Create An Experiment Tracking with Snowflake Cortex, Snowpark, and Weights &amp; Biases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIYjX-Rz8m88gYXiWpTQxA.png" /><figcaption>Photo by Steve Johnson on Unsplash</figcaption></figure><p>Snowflake Cortex is game-changing. It gives you access to one part of the best Large Language models (LLM) you can use now. In this article, I will show you how to set up an experiment to get better results using prompt engineering and how to compare different prompts, select which model is better for my application, and use the best hyper-parameters to get the best results.</p><p><a href="https://blog.infostrux.com/enhancing-llm-performance-prompt-engineering-in-snowflake-cortex-part-1-e8d438e7ddb2">In part 1</a>, we’ve examined the fundamental principles of Prompt Engineering and Evaluating LLMs. We also started preparing our Snowflake account with a new database, schema, and transformations using SQL and Snowpark. We’re ready to create an AI experiment.</p><p>In this article, we’ll see how to set up the experiment, create a pipeline for running in parallel, and log the results in the <a href="https://wandb.ai/site">Weights &amp; Biases(W&amp;B) Platform</a>.</p><h4>Walkthrough Example</h4><p>After finishing the preliminary data engineering process, we can start configuring our experiment using prompt engineering and tracking in W&amp;B.</p><h4><strong>Step 1: Configure The </strong><a href="https://wandb.ai/site">Weights &amp; Biases</a> <strong>W&amp;B Project</strong></h4><p>Initially, I will set up a new project and create my account in W&amp;B. It’s essential to keep the Name of the project and the entity(your username).</p><figure><img alt="New Project in W&amp;B" src="https://cdn-images-1.medium.com/proxy/1*cE1cQ-SQyi_HKrvnzjarow.png" /><figcaption>New Project in W&amp;B</figcaption></figure><h4><strong>Step 2: Create a Function for LLM Snowflake Cortex</strong></h4><p>In this step, I will create a function for calling the SQL Function <strong>COMPLETE</strong> from Snowflake Cortex. You can check my <a href="https://blog.infostrux.com/mastering-ai-in-snowflake-transform-your-dbt-workflow-6dc8c4628126">last article</a>, where I explored the LLM Functions of Snowflake Cortex.</p><p>To start, we will create a Python function that retrieves the response from <strong>Complete</strong> and <strong>Prompt</strong> calls. This function allows experimentation and testing of different prompts to determine the most effective results. You are encouraged to explore the code further. The main objective is to extract the response, assuming it is in JSON format.</p><pre>def extract_entities_with_template(text, template_prompt, system_prompt, model, temperature):<br>    start_time = timeit.default_timer()<br>    prompt = template_prompt.replace(&#39;&lt;text&gt;&#39;, text)<br>    system_content = {<br>        &#39;role&#39;: &#39;system&#39;,<br>        &#39;content&#39;: system_prompt<br>    }<br>    user_content = {<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;: prompt<br>    }<br>    options = {<br>        &#39;temperature&#39; : temperature<br>    }<br>    json_payload = json.dumps([system_content, user_content]).replace(&#39;&quot;&#39;,&quot;&#39;&quot;)<br>    query = f&quot;&quot;&quot;<br>    SELECT SNOWFLAKE.CORTEX.COMPLETE(<br>    &#39;{model}&#39;,<br>    {json_payload},<br>    {options}<br>    )<br>    &quot;&quot;&quot;<br>    df = session.sql(query).collect()<br>    res = df[0][0]<br>    response = json.loads(res)<br>    text = response[&#39;choices&#39;][0][&#39;messages&#39;]<br>    entities = [entity.lower().replace(&#39;--&#39;,&#39;&#39;).replace(&#39;**&#39;,&#39;&#39;) for entity in filter(lambda x: &#39;--&#39; in x, map(str.strip, text.split(&#39;\n&#39;)))]<br>    usage = response[&#39;usage&#39;]<br>    prompt_tokens = usage[&#39;prompt_tokens&#39;]<br>    completion_tokens = usage[&#39;completion_tokens&#39;]<br>    total_tokens = usage[&#39;total_tokens&#39;]<br>    end_time = timeit.default_timer()<br>    elapsed = end_time - start_time<br>    return {<br>        &#39;entities&#39; : entities,<br>        &#39;model&#39; : model,<br>        &#39;prompt&#39; : prompt,<br>        &#39;elapsed&#39; : elapsed,<br>        &#39;prompt_tokens&#39;: prompt_tokens,<br>        &#39;completion_tokens&#39;: completion_tokens,<br>        &#39;total_tokens&#39; : total_tokens}</pre><h4>Step 3: <strong>Calculate Metrics</strong></h4><p>We have developed an assessment measure for our project. In cases where the evaluation process is not as straightforward, an LLM can also be utilized to evaluate the task.</p><pre>def calculate_f1(extracted_entities, ground_truth_entities):<br>    extracted_set = set(map(str.lower,  extracted_entities))<br>    ground_truth_set = set(map(str.lower, ground_truth_entities))<br>    tp_examples = extracted_set &amp; ground_truth_set<br>    tp = len(tp_examples)<br>    fp_examples = extracted_set - ground_truth_set<br>    fp = len(fp_examples)<br>    fn_examples = ground_truth_set - extracted_set<br>    fn = len(fn_examples)<br>    precision = tp / (tp + fp) if (tp + fp) &gt; 0 else 0<br>    recall = tp / (tp + fn) if (tp + fn) &gt; 0 else 0<br>    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) &gt; 0 else 0<br>    return f1, tp, fp, fn</pre><h4>Step 4: <strong>Evaluate the results</strong></h4><p>Our metric is computed for all of our predictions and recorded in a wandb.Table for future review.</p><pre>def evaluate(extracted, labelled_examples):<br>    total_tp, total_fp, total_fn = 0,0,0<br>    eval_table = wandb.Table(columns=[&#39;text&#39;, &#39;pred&#39;, &#39;truth&#39;, &#39;f1&#39;, &#39;tp&#39;, &#39;fp&#39;, &#39;fn&#39;,<br>                                      &#39;prompt_tokens&#39;, &#39;completion_tokens&#39;, &#39;total_tokens&#39;])<br>    for pred, gt in zip(extracted, labelled_examples):<br>        f1, tp, fp, fn = calculate_f1_jasm(pred[&#39;entities&#39;], gt[&#39;entities&#39;])<br>        total_tp += tp<br>        total_fp += fp<br>        total_fn += f1<br>        eval_table.add_data(<br>            gt[&#39;text&#39;], pred[&#39;entities&#39;], gt[&#39;entities&#39;],  f1, tp, fp, fn,<br>            pred[&#39;prompt_tokens&#39;], pred[&#39;completion_tokens&#39;], pred[&#39;total_tokens&#39;]<br>        )<br>    wandb.log({&#39;eval_table&#39;: eval_table})<br>    overall_precision = total_tp / (total_tp + total_fp) if (total_tp + total_fp) &gt; 0 else 0<br>    overall_recall = total_tp / (total_tp + total_fn) if (total_tp + total_fn) &gt; 0 else 0<br>    overall_f1 = 2 * overall_precision * overall_recall / (overall_precision + overall_recall) if (overall_precision + overall_recall) &gt; 0 else 0<br>    return overall_precision, overall_recall, overall_f1</pre><h4>Step 5: <strong>Perform inference in parallel</strong></h4><p>The process of conducting evaluations may experience delays. To increase efficiency, the following code can be utilized to collect examples simultaneously. While not exclusive to W&amp;B, this code can prove to be beneficial.</p><pre>def inference(examples, system_prompt, template_prompt, model, temperature):<br>    extracted = []<br>    # this is needed because exectutor.map wants a func with one arg<br>    llm_function = partial(extract_entities_with_template, model=model,<br>                          system_prompt=system_prompt, template_prompt=template_prompt,<br>                          temperature=temperature)<br>    # Run the model to extract the entities<br>    start_time = timeit.default_timer()<br>    with ThreadPoolExecutor(max_workers=5) as executor:<br>        for i in executor.map(llm_function, [t[&#39;text&#39;].strip() for t in examples]):<br>            extracted.append(i)<br>    end_time = timeit.default_timer()<br>    elapsed = end_time - start_time<br>    return extracted, elapsed</pre><h4>Step 6: <strong>Run our pipeline</strong></h4><p>To begin using W&amp;B, invoke wandb.init and provide the configuration to monitor the current experimentation settings. As you continue to experiment, utilize wandb.log to record your progress, which will be logged to W&amp;B. When finished, call wandb.finish to end tracking, which will be recorded as a single &quot;Run&quot; in W&amp;B. A link to W&amp;B will be provided for you to view all of your logs.</p><pre>NUM_EXAMPLES = 5<br>model = &#39;gemma-7b&#39;<br>temperature = 0.5<br>temperature = 0.7<br>template = &#39;&#39;&#39;<br>text: &lt;text&gt;<br>Return the entities as a list with a new line between each entity and the identificator --  for each entity.<br>&#39;&#39;&#39;<br>system_prompt = &#39;You are an excellent entity extractor reading newspapers and extracting orgs, people and locations. Extract the entities from the follow sentence.&#39;<br><br>wandb.init(project=&#39;Snowflake-Cortex-LLM&#39;,<br>           entity=&#39;jsalasmoreira&#39;,<br>           config={<br>                &#39;system_prompt&#39;: system_prompt,<br>                &#39;template&#39;: template,<br>                &#39;model&#39;: model,<br>                &#39;temperature&#39;: temperature<br>            })<br>extracted, elapsed = inference(labelled_examples,<br>                                system_prompt, template, model, temperature)<br>overall_precision, overall_recall, overall_f1 = evaluate(extracted,<br>                                                         labelled_examples)<br>total_tokens_sum = sum([pred[&#39;total_tokens&#39;] for pred in extracted])<br>completion_tokens_sum = sum([pred[&#39;completion_tokens&#39;] for pred in extracted])<br>prompt_tokens_sum = sum([pred[&#39;prompt_tokens&#39;] for pred in extracted])<br>wandb.log({<br>    &#39;precision&#39;: overall_precision,<br>    &#39;recall&#39;: overall_recall,<br>    &#39;f1&#39;: overall_f1,<br>    &#39;time_elapsed_total&#39;: elapsed,<br>    &#39;prompt_tokens&#39;: prompt_tokens_sum,<br>    &#39;completion_tokens&#39;: completion_tokens_sum,<br>    &#39;total_tokens&#39;: total_tokens_sum<br>})<br>wandb.finish()</pre><p>You can see the following results:</p><figure><img alt="Run summary pipeline" src="https://cdn-images-1.medium.com/proxy/1*4spFz4bU8Oq3KDiKhxtBaw.png" /><figcaption>Run summary pipeline</figcaption></figure><h4>Step 7: <strong>Create a new experiment</strong></h4><p>In this step, I experimented by combining various prompts, models, and temperatures. This allowed me to determine the optimal combination of hyperparameters to achieve the best results. Additionally, I utilized the W&amp;B dashboard to interpret and analyze the results easily.</p><pre>template = &#39;&#39;&#39;<br>text: &lt;text&gt;<br>Return the entities as a list with a new line between each entity and the identificator --  for each entity.<br>&#39;&#39;&#39;<br>system_prompts = [&#39;Extract the entities from the following sentence. Separ&#39;,<br>                  &#39;You are an excellent entity extractor reading newspapers and extracting orgs, people, and locations. Extract the entities from the following sentence.&#39;,<br>                  &#39;You are an expert entity extractor. Please extract the following entities from the sentence.&#39;,<br>                  &#39;You are expert in english and entity extraction. Please extract the entities from the following sentence.&#39;<br>                  ]<br>for system_prompt in system_prompts:<br>    for temperature in [0.7, 0.9, 1.0]:<br>        for model in [&#39;gemma-7b&#39;, &#39;mistral-7b&#39;,&#39;mistral-large&#39;, &#39;llama2-70b-chat&#39; ]:<br>            wandb.init(project=&#39;Snowflake-Cortex-LLM&#39;,<br>                       entity=&#39;jsalasmoreira&#39;,<br>                       config={<br>                        &#39;system_prompt&#39;:system_prompt,<br>                        &#39;template&#39;: template,<br>                        &#39;model&#39;: model,<br>                        &#39;temperature&#39;: temperature<br>            })<br>            extracted, elapsed = inference(labelled_examples,<br>                                system_prompt, template, model, temperature)<br>            overall_precision, overall_recall, overall_f1 = evaluate(extracted,<br>                                                                     labelled_examples)<br>            total_tokens_sum = sum([pred[&#39;total_tokens&#39;] for pred in extracted])<br>            completion_tokens_sum = sum([pred[&#39;completion_tokens&#39;] for pred in extracted])<br>            prompt_tokens_sum = sum([pred[&#39;prompt_tokens&#39;] for pred in extracted])<br>            wandb.log({<br>                &#39;precision&#39;: overall_precision,<br>                &#39;recall&#39;: overall_recall,<br>                &#39;f1&#39;: overall_f1,<br>                &#39;time_elapsed_total&#39;: elapsed,<br>                &#39;prompt_tokens&#39;: prompt_tokens_sum,<br>                &#39;completion_tokens&#39;: completion_tokens_sum,<br>                &#39;total_tokens&#39;: total_tokens_sum<br>            })<br>            wandb.finish()</pre><p>Now, we can analyze the outcomes in W&amp;B and choose the top-performing runner.</p><figure><img alt="Results and best hyper parameters, model and prompt." src="https://cdn-images-1.medium.com/proxy/1*MKJ9B2_qWElg8hxNtWPsyw.png" /><figcaption>Results and best hyperparameters, model, and prompt.</figcaption></figure><h4>Conclusion</h4><p>We have created an experiment to evaluate several LLM models available in Snowflake Cortex. We tested multiple hyperparameters and prompts to identify the best solution for our application.</p><p>We quickly overview the Weights &amp; Biases (W&amp;B) Platform used for running, saving results, and comparing results in an experiment. This example can be applied to various scenarios using Snowflake Cortex, allowing us to select the most cost-effective model for our organization.</p><p>If you are curious, check out these two solutions offered by Infostrux <a href="https://www.infostrux.com/ai-ml/mlops-for-snowflake/">ML Ops solution</a> and <a href="https://www.infostrux.com/ai-ml/secure-ai-powered-chatbots">LLM solution</a>.</p><p>I’m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux’s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb9687b92a29" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/enhancing-llm-performance-prompt-engineering-in-snowflake-cortex-part-2-fb9687b92a29">Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 2</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AI in Snowflake: Transform Your DBT Workflow!]]></title>
            <link>https://blog.infostrux.com/mastering-ai-in-snowflake-transform-your-dbt-workflow-6dc8c4628126?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc8c4628126</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 07 May 2024 13:17:19 GMT</pubDate>
            <atom:updated>2024-05-07T13:17:19.946Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use LLMs in Snowflake, Integrate them into DBT, and Using them with your database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20-7TPgZJFBNYRH05vyjGg.png" /><figcaption>Photo by <a href="https://unsplash.com/@growtika">Growtika</a> on Unsplash</figcaption></figure><p>Large Language Models (LLMs) are revolutionizing the world. Nevertheless, using them effectively to address real-world problems within our organizations is often challenging and complex. However, Snowflake has developed an uncomplicated method, Snowflake Cortex, to optimize the utilization of LLMs within any field.</p><p>I will expand the project <a href="https://medium.com/infostrux-solutions/building-an-end-to-end-elt-solution-with-snowflake-and-dbt-187bae83a87b">End-to-End ELT Solution with Snowflake and DBT</a> using Snowflake Cortex and integrate them into different DBT transformations. Getting the most out of a data engineering and data science workflow.</p><h3>What is Snowflake Cortex</h3><p>Snowflake Cortex provides access to industry-leading LLMs from top companies like Mistral, Google, and Meta in just a few steps. All LLM models are fully hosted and managed by Snowflake and require no setup.</p><p>Let&#39;s take a look at the different functions available in Snowflake Cortex. For more details, refer to <a href="https://docs.snowflake.com/user-guide/snowflake-cortex/llm-functions">Snowflake&#39;s Documentation</a>.</p><ul><li><strong>COMPLETE:</strong> Responding to a prompt to fulfill the task&#39;s requirements by engaging in intricate reasoning.</li><li><strong>EXTRACT_ANSWER<em>:</em></strong> Skilled in retrieving insights from semi-structured or unstructured data.</li><li><strong>SENTIMENT:</strong> Utilized to ascertain the emotions conveyed within the text.</li><li><strong>SUMMARIZE:</strong> Utilized to get a summary of the provided text.</li><li><strong>TRANSLATE</strong> Utilized to convert text from one language to another.</li></ul><p>In this instance, I will employ the COMPLETE and SENTIMENT functions within the context of the DBT transformations.</p><h3>Walkthrough Example</h3><p>Let&#39;s discuss how AI can provide insights and drive transformations. For the purpose of this example, we&#39;ll assume that you have prior knowledge about Snowflake, DBT, and Airbnb datasets. However, if you&#39;re new to these concepts, you can look at my last <a href="https://medium.com/infostrux-solutions/building-an-end-to-end-elt-solution-with-snowflake-and-dbt-187bae83a87b">article</a>, which explains them in detail.</p><h4><strong>Step 1: Analysis of sentiments from comments</strong></h4><p>Initially, I will utilize the Sentiment function to assess the feedback, categorizing it into positive, negative, or neutral segments. The function returns a value between -1 and 1, where one is positive, and -1 is negative. Here is an example of the implementation of the function.</p><p>Please note that I only used some of the data for this example. Using the SAMPLE method in Snowflake.</p><pre>with demo_data as (<br>    SELECT <br>        REVIEWER_ID, <br>        SNOWFLAKE.CORTEX.SENTIMENT(<br>        COMMENTS) as SENTIMENT_INT<br>    FROM REVIEWS SAMPLE ROW(0.5)<br>)<br><br>SELECT <br>    REVIEWER_ID,<br>    CASE<br>        WHEN SENTIMENT_INT &gt; 0.5 THEN &#39;Positive&#39; <br>        WHEN SENTIMENT_INT &lt; -0.5 THEN &#39;Negative&#39;<br>        ELSE &#39;Neutral&#39;<br>        END AS SENTIMENT<br>FROM demo_data;</pre><figure><img alt="Result for analysis of sentiments from comments" src="https://cdn-images-1.medium.com/proxy/1*wmCd57bWv9E3doKxgTH0Qg.png" /><figcaption>Result for analysis of sentiments from comments</figcaption></figure><h4><strong>Step 2: Join the Sentiment with the Reviews</strong></h4><p>Right now, We have to add this sentiment to the reviews table. This is important to use this data for future analysis.</p><pre>SELECT t1.*, t2.SENTIMENT<br>FROM sentiment_table as t2 <br>inner join reviews as t1 <br>on t2.reviewer_id = t1.reviewer_id</pre><h4><strong>Step 3: Recommendation for Negative Reviews</strong></h4><p>As the next step, I will develop a recommendation strategy to address the various negative reviews identified in our analysis. This is a crucial step that leverages the full potential of LLMs in Snowflake, and we can use this approach in diverse use cases.</p><p>Snowflake enables us to use the following LLM models. You can compare their performance in the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gqsKtwteVhiwFemKVDOiEg.png" /></figure><p>A fundamental element of this procedure involves crafting a prompt that is impactful in eliciting the most optimal response. Tailoring the prompt to suit individual preferences can result in a more personalized and tailored response.</p><pre>SET prompt = <br>&#39;Give me the three main points to fix it from this comment; only give me the plan for doing it better. The comment is the following:&#39;;<br><br>SELECT <br>    REVIEWER_ID,<br>    SNOWFLAKE.CORTEX.COMPLETE(&#39;mixtral-8x7b&#39;, concat($prompt, COMMENTS)) as recommendation<br>FROM REVIEWS_WITH_SENTIMENT<br>WHERE SENTIMENT = &#39;Negative&#39;;</pre><p>The outcomes are stored in a table for various purposes, enabling swift analysis of the collected data or convenient sharing for further utilization.</p><figure><img alt="Result of recommendation action with LLM" src="https://cdn-images-1.medium.com/proxy/1*6xRJ5bLHwoTliHN35bVVIQ.png" /><figcaption>Result of recommendation action with LLM</figcaption></figure><h3>Conclusion</h3><p>Utilizing LLMs can significantly enhance our analytical capabilities and assist in developing analytical solutions for various projects. For instance, within a few minutes, we can swiftly analyze comments, classify sentiments, and formulate actionable recommendations to enhance business strategies.</p><p>Snowflake Cortex stands out as a user-friendly and highly effective platform for leveraging the full capabilities of LLMs within our warehouse facilities. This article can be used as an example for developing and integrating other projects, or you can reach out to <a href="https://www.infostrux.com/ai-ml/secure-ai-powered-chatbots">Infostrux</a> to help you with this problem.</p><p>At last, we are ushering in a new era propelled by Artificial Intelligence (AI) and Large Language Models (LLMs). Embracing these technologies to develop solutions enables us to secure a competitive edge in our endeavors.</p><p>I&#39;m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux&#39;s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc8c4628126" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/mastering-ai-in-snowflake-transform-your-dbt-workflow-6dc8c4628126">Mastering AI in Snowflake: Transform Your DBT Workflow!</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 1]]></title>
            <link>https://blog.infostrux.com/enhancing-llm-performance-prompt-engineering-in-snowflake-cortex-part-1-e8d438e7ddb2?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8d438e7ddb2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 13:11:06 GMT</pubDate>
            <atom:updated>2024-04-30T13:11:06.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 1</h3><h4>Prompt Engineering Best Practices — Create An Experiment Tracking with Snowflake Cortex, Snowpark, and W&amp;B</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClkePIM35iEJI-p2uTwW3Q.png" /><figcaption>Picture by <a href="https://unsplash.com/@coopery">Mohamed Nohassi</a> on Unsplash.</figcaption></figure><p>Snowflake Cortex is game-changing. It gives you access to one part of the best Large Language models (LLM) you can use now. The best part of this is a fully managed service, so you don’t need to worry about the servers, process, and more. Only use the functions for easy access and problem solutions. You can explore more in the <a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions">documentation</a>. However, we will explore in this article how to get better results using <strong>prompt engineering</strong> and how to compare different prompts, select which model is better for my application, and use the <strong>best hyperparameters</strong> to get the best results. You can find additional details in the <a href="https://www.promptingguide.ai/introduction/settings">Prompt Engineering Guide</a>. Let us examine the fundamental aspects of Prompt Engineering.</p><h3>Prompt Engineering (WISER Framework)</h3><p>The “WISER” framework is your key to unlocking the full LLM potential interactions. With this framework, you can create engaging, informative, and captivating conversations with AI. So let me explain to you the different possibilities of this journey.</p><p><strong>The WISER Formula:</strong> Who + Instructions + Sub Tasks + Examples + Review</p><ul><li><strong>Who:</strong> Assign a specific identity or role.</li><li><strong>Instructions:</strong> Instruct the model on the necessary actions to take.</li><li><strong>Sub Tasks:</strong> Break the task into smaller, more manageable steps.</li><li><strong>Example:</strong> Provide examples (if applicable)</li><li><strong>Review:</strong> Examine output and evaluation metrics, then make iterative improvements.</li></ul><figure><img alt="Example a typical prompt structure" src="https://cdn-images-1.medium.com/proxy/1*Ud4q3Jhx9yMYGXQ4SBnl4g.png" /><figcaption>A typical prompt structure</figcaption></figure><h4><strong>Prompt Templates</strong></h4><p>The prompt templates are valuable resources for implementing superior prompt engineering in our projects. Currently, numerous libraries and open-source project examples are available for various scenarios. Among the most renowned is Langchain, which you can delve deeper into through its <a href="https://www.pinecone.io/learn/series/langchain/langchain-prompt-templates/">documentation</a>.</p><p>In this article, I will use the WISER Framework to create different prompts for the practice example, compare their effectiveness, and select the best.</p><h4>Evaluating LLMs</h4><p>Evaluating the responses of LLMs can be difficult, and you may not know the best approach to do it. However, a strategy that can be employed involves assessing metrics for language models based on a valid response, a benchmark response, a prior response, or human input. Let’s explore the following recommendations.</p><ul><li>If there is a definitive answer, it is best to measure accuracy using metrics.</li><li>Utilize reference responses to apply reference matching metrics such as semantic similarity or factual consistency.</li><li>If there is an existing response, kindly consult another language model to determine the superior answer.</li><li>When human feedback is accessible, verify whether the response integrates the feedback.</li><li>If none of the options apply, ensure the output structure is correct or request the model grade the answer.</li><li>Automated evaluation is preferred for expedited experimentation, but manual inspections are crucial.</li></ul><p>Should you require additional information, The <a href="https://fullstackdeeplearning.com/llm-bootcamp/spring-2023/llmops/">LLM Bootcamp </a>serves as a valuable resource. The diagram below is based on the insights provided in its notes.</p><figure><img alt="Evaluation metrics for LLMs" src="https://cdn-images-1.medium.com/proxy/1*M6bVqjjjVKVR3cTNE6MGDA.png" /><figcaption>Evaluation metrics for LLMs</figcaption></figure><p>For this example, I will use a <a href="https://raw.githubusercontent.com/explosion/prodigy-recipes/master/example-datasets/annotated_news_headlines-ORG-PERSON-LOCATION-ner.jsonl">dataset</a> with reference answers. So, it’s possible to implement reference-matching metrics for this application. Furthermore, I will use an AI training platform, <a href="https://wandb.ai/site"><strong>Weights &amp; Biases (W&amp;B)</strong></a>, with different tools for training models, AI experiments, and more. Utilizing W&amp;B simplifies the process of tracking, comparing, and visualizing our ML models. Experiment logging can seamlessly integrate by incorporating a few additional lines into your script. From my point of view, this is the most efficient approach to achieving these tasks.</p><p>So, let’s get started with the practice example.</p><h3>Walkthrough Example</h3><p>We have deliberated on various Prompt Engineering and Evaluating LLM results concepts. We can move to apply these theories in a practical scenario. Specifically, I will experiment by employing diverse LLM Models and various configurations and prompts to extract entities from a text.</p><p>Like most AI initiatives, initiating a preliminary data engineering procedure is necessary, which will be explained in the following steps.</p><h4><strong>Step 1: Configure Snowflake Account</strong></h4><p>Initially, I will set up my Snowflake account with a new database, schema, and user to use with this example. I assume that you know the basic concepts of Snowflake and SQL.</p><pre>CREATE DATABASE LLM;<br>USE DATABASE LLM;<br>CREATE SCHEMA prompt_experiment;<br>CREATE OR REPLACE STAGE datasets ENCRYPTION = (TYPE = &#39;SNOWFLAKE_SSE&#39;) DIRECTORY = (ENABLE = true);<br>CREATE OR REPLACE table raw_json(<br>    raw VARIANT <br>);<br>CREATE OR REPLACE TABLE clean_json(<br>    Text string,<br>    Entities array <br>);</pre><h4><strong>Step 2: Ingest the dataset into Snowflake</strong></h4><p>Subsequently, I will upload the dataset to the internal stage established earlier, load the dataset into a raw JSON table within Snowflake, and conclude by executing a basic query on the JSON table to retrieve only two specific columns for this demonstration, Text, and Spans.</p><pre>CREATE OR REPLACE file format csv_fileformat<br>    type = csv<br>    field_delimiter = &#39;--&#39;<br>    null_if = (&#39;NULL&#39;, &#39;null&#39;)<br>    empty_field_as_null = TRUE;<br><br>COPY INTO raw_json <br>FROM @datasets <br>FILE_FORMAT = (FORMAT_NAME = &#39;csv_fileformat&#39;)<br>ON_ERROR = &#39;CONTINUE&#39;;<br><br>INSERT into clean_json<br>    SELECT RAW:text as Text, RAW:spans as Entities<br>    FROM raw_json;</pre><p>You can view the specifics of this stage in the following image.</p><figure><img alt="View of the clean json table" src="https://cdn-images-1.medium.com/proxy/1*tA2KYTF2nfFiPzJWqgLgeA.png" /><figcaption>View of the clean json table</figcaption></figure><p>Currently, I have included several processes in my dataset. When reviewing the table, it is necessary to extract entity details from the object entities. To achieve this conversion, I will leverage Snowpark. It offers an efficient way to leverage the combined functionalities of Snowflake and Python.</p><h4><strong>Step 3: Create a new User for use in the Snowpark integration</strong></h4><p>Creating a new user in Snowflake is necessary to connect with Snowpark. In my opinion, the most secure option is to use <strong>key pair authentication</strong>.</p><p>I couldn’t find a detailed guide on creating a user and using key pair authentication in Snowpark with Python. So, I will explain it in the next step. Feel free to skip ahead if you are already familiar with this process.</p><p>First, I will create a key pair authentication on my laptop. I am using macOS. Note that commands may differ for Windows.</p><pre>cd ~/.ssh<br>openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out snowflake_key.p8<br>openssl rsa -in snowflake_key.p8 -pubout -out snowflake_key.pub</pre><p>Next, create the new snowflake user and set the snowflake_key.pub for this user.</p><pre>CREATE USER &quot;snowpark&quot; RSA_PUBLIC_KEY=&#39;RSA_PUBLIC_KEY_HERE&#39; DEFAULT_ROLE=PUBLIC MUST_CHANGE_PASSWORD=FALSE;<br>GRANT ROLE SYSADMIN TO USER &quot;snowpark&quot;;</pre><p>Now, you will be able to use this user in Snowpark. The following code is an example of creating a session with a key pair authentication.</p><pre>import os<br>from cryptography.hazmat.backends import default_backend<br>from cryptography.hazmat.primitives import serialization<br>with open(&quot;&lt;your_key_path&gt;&quot;, &quot;rb&quot;) as key:<br>    p_key= serialization.load_pem_private_key(<br>        key.read(),<br>     password=os.enviroment[&#39;KEY_PASSWORD&#39;].encode(),<br>        backend=default_backend()<br>    )<br>pkb = p_key.private_bytes(<br>    encoding=serialization.Encoding.DER,<br>    format=serialization.PrivateFormat.PKCS8,<br>    encryption_algorithm=serialization.NoEncryption())<br>connection_parameters = {<br>    &quot;ACCOUNT&quot;: &quot;&lt;YOUR_ACCOUNT_NAME&gt;&quot;,<br>    &quot;USER&quot;: &quot;snowpark&quot;,<br>    &quot;ROLE&quot;: &quot;SYSADMIN&quot;,<br>    &quot;PRIVATE_KEY&quot;: pkb,<br>    &quot;WAREHOUSE&quot;: &quot;&lt;YOUR_WAREHOUSE_NAME&gt;&quot;,<br>    &quot;DATABASE&quot;: &quot;LLM&quot;,<br>    &quot;SCHEMA&quot;: &quot;PROMPT_EXPERIMENT&quot;<br>}<br>session = snowpark.Session.builder.configs(connection_parameters).create()</pre><h4><strong>Step 4: Data Transformation using Snowpark</strong></h4><p>In this step, I will extract the entities from an object that gives me the coordinates for each entity. The next script using Snowpark resolves the problem by connecting to my table “CLEAN_JSON”, transforming the dataset, and saving the result in a new table, “TRANSFORM_JSON.”</p><pre>from snowflake.snowpark.functions import col, udf<br>def main(session: session): <br>    @udf(name= &quot;extract_entites&quot;, replace=True)<br>    def extract_entites(text:str, entities: list) -&gt; list:<br>        extracted_entities = []<br>        if entities :<br>            for entity in entities:<br>                start = entity[&#39;start&#39;]<br>                end = entity[&#39;end&#39;]<br>                extracted_entities.append(text[start:end])<br>            return extracted_entities <br>    #Load the data from the table<br>    input_data = &#39;clean_json&#39;<br>    output_table = &#39;transform_json&#39;<br>    df = session.table(input_data)<br>    # Apply the UDF to extract entities<br>    df_transformed = df.select(col(&quot;TEXT&quot;),<br>                       extract_entites(col(&quot;TEXT&quot;), col(&quot;ENTITIES&quot;)).as_(&quot;Entities&quot;)).collect()<br>    df_final = session.create_dataframe(df_transformed)<br>    df_final.write.mode(&#39;overwrite&#39;).save_as_table(output_table)<br>    df_result = session.table(output_table)<br>    return df_result</pre><p>This is a look at the new table when the process is finished.</p><figure><img alt="View of the TRANSFORMJSON TABLE" src="https://cdn-images-1.medium.com/proxy/1*DmLx7JxoI5haO80SM30XIQ.png" /><figcaption>TRANSFORM_<em>JSON</em> TABLE</figcaption></figure><p>We are now prepared to execute a new experiment using this table. Further details on this will be elaborated in the subsequent section of this article, where I will create the experiment step by step.</p><h3>Conclusion</h3><p>We have examined the fundamental principles of Prompt Engineering and Evaluating LLMs. Understanding these principles will enable us to establish precise experiment tracking in the subsequent section of this article and achieve improved outcomes in our project.</p><p>We quickly overview the tools for creating experiments, tracking, comparing, and visualizing our ML models.</p><p>We explored creating a new user and using key pair authentication on Snowpark, and created a completed data transformation using all the power of Snowflake and Python using Snowpark.</p><p>If you are curious, check out these two solutions offered by Infostrux <a href="https://www.infostrux.com/ai-ml/mlops-for-snowflake/">ML Ops solution</a> and <a href="https://www.infostrux.com/ai-ml/secure-ai-powered-chatbots">LLM solution</a>.</p><p>I’m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux’s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8d438e7ddb2" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/enhancing-llm-performance-prompt-engineering-in-snowflake-cortex-part-1-e8d438e7ddb2">Enhancing LLM Performance: Prompt Engineering in Snowflake Cortex — Part 1</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake GitHub Actions — Extract Information and Automate]]></title>
            <link>https://blog.infostrux.com/snowflake-github-actions-extract-information-and-automate-12920fc2a708?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/12920fc2a708</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 13:51:29 GMT</pubDate>
            <atom:updated>2024-04-23T13:51:29.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Snowflake GitHub Actions — Extract Information and Automate</h3><h4>Take your GitHub Actions to the next level! Extract information about your repositories and Pull Requests to create complete CI/CD pipelines on Snowflake.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KwWMtIvjuPkm6vAxZWbDEA.png" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alina Grubnyak</a> on <a href="https://unsplash.com/s/photos/data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Have you ever tried to create different layers in your project before taking it to production? This is a common approach in various projects. For example, using the layers Dev, QA, and Production.</p><p>In this article, I will explain a methodology for integrating GitHub Actions within our warehouse environment, focusing on Snowflake.</p><p>To begin, let&#39;s review the steps involved in this process. The workflow for this solution is shown in the picture below. If you make any changes to the code and create a pull request, we must first test the changes, test the models, and ensure that everything is working correctly.</p><figure><img alt="Workflow CI/CD with GitHub Actions" src="https://cdn-images-1.medium.com/proxy/1*8v_MYvCXBhZwNDiZcvSObw.png" /><figcaption>Workflow CI/CD with GitHub Actions</figcaption></figure><h3>Walkthrough Example</h3><p>Let&#39;s walk through the different layers and steps using GitHub Actions and Snowflake. For this example, we&#39;ll assume you already have a Github Account and a Snowflake account.</p><h4><strong>Step 1: Key Pair Authentication</strong></h4><p>To start, you need to create a new Snowflake user. However, before doing that, you must create an RSA key for authentication in Github. Open your terminal or command prompt and execute the following commands. Please note that the commands may differ if you are using Windows instead of macOS.</p><pre>cd ~/.ssh<br>openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out snowflake_key.p8<br>openssl rsa -in snowflake_key.p8 -pubout -out snowflake_key.pub</pre><h4><strong>Step 2: Snowflake User</strong></h4><p>For this step, creating a new user in Snowflake is necessary. We&#39;ll execute all the steps in our GitHub action using this user.</p><pre>CREATE OR REPLACE USER &quot;testing-github&quot; RSA_PUBLIC_KEY = &#39;&lt;Put the key information, that is in snowflake_key.pub file&gt;&#39; DEFAULT_ROLE=PUBLIC MUST_CHANGE_PASSWORD=FALSE;<br>GRANT ROLE SYSADMIN TO USER &quot;testing-github&quot;</pre><h4><strong>Step 3: Repository secrets</strong></h4><p>Next, we must set the secrets in our repository before creating our GitHub Actions. It&#39;s a good practice to keep all sensible data by using secrets.</p><figure><img alt="Setting of new secret in our repository " src="https://cdn-images-1.medium.com/proxy/1*WrVAOLTzO5nPCX5GhcwZKQ.png" /><figcaption>Setting of new secret in our repository</figcaption></figure><p>Now, put the information like the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*ieKHIYfygFUyjynFSt9oBA.png" /><figcaption>Creating a new Secret in GitHub for this specific repository.</figcaption></figure><p>To ensure our repository is configured correctly, it is ideal that you create the specified secrets.</p><figure><img alt="Repository secrets for Snowflake configuration " src="https://cdn-images-1.medium.com/proxy/1*PQAHoJcFCntbTxLcUH7ABw.png" /><figcaption>Repository secrets for Snowflake configuration</figcaption></figure><p>As a tip, it is easy to find your account information. You can use the following SQL query in Snowflake.</p><pre>SELECT current_account() as YOUR_ACCOUNT_LOCATOR;</pre><h4><strong>Step 4: GitHub Action for Pull Request</strong></h4><p>In this case, we need to create a new Github Action that extracts the PR number and uses this number to identify a new Schema. The following code resolves this approach.</p><pre>name : PR Testing Schema<br>on :<br>    pull_request:<br>        branches:<br>            - main<br>jobs:<br>    build:<br>        runs-on: ubuntu-latest<br>        env:<br>            SNOWSQL_PRIVATE_KEY : ${{ secrets.SNOWSQL_PRIVATE_KEY }}<br>            SNOWSQL_ACCOUNT : ${{ secrets.SNOWSQL_ACCOUNT }}<br>            SNOWSQL_USER : ${{ secrets.SNOWSQL_USER }}<br>            SNOWSQL_DATABASE : ${{ secrets.SNOWSQL_DATABASE }}<br>            SNOWSQL_SCHEMA : ${{ secrets.SNOWSQL_SCHEMA }}<br>            SNOWSQL_WAREHOUSE : ${{ secrets.SNOWSQL_WAREHOUSE }}<br>            SNOWSQL_ROLE : ${{ secrets.SNOWSQL_ROLE }}<br>            SNOWSQL_PRIVATE_KEY_PATH : /tmp/snowflake_rsa_key.p8<br>            SNOWSQL_PRIVATE_KEY_PASSPHRASE : ${{ secrets.SNOWSQL_PRIVATE_KEY_PASSPHRASE }}<br><br>        steps:<br>          - uses: actions/checkout@v4<br>          - name: Setup SSH Key<br>            run: |<br>              printf &#39;%s\n&#39; &quot;${SNOWSQL_PRIVATE_KEY}&quot; &gt; &quot;${SNOWSQL_PRIVATE_KEY_PATH}&quot;<br>          - name: Install SnowSQL<br>            run: |<br>              curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.9-linux_x86_64.bash<br>              SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.9-linux_x86_64.bash<br>          - name: Run SnowSQL<br>            run: |<br>              ~/bin/snowsql --private-key-path $SNOWSQL_PRIVATE_KEY_PATH -q &quot;CREATE SCHEMA IF NOT EXISTS $SNOWSQL_DATABASE.PR_${{ github.event.number}}_schema;&quot;</pre><h4><strong>Step 5: Github Action After Merging PR</strong></h4><p>We have developed a new schema to conduct quality tests on our project.</p><p>Once all the required tests in Snowflake have been passed, we can accept the Pull Request. After that, we may run a GitHub Action to delete the unnecessary schema. It&#39;s worth noting that, in this scenario, we&#39;ll be using the GitHub API to extract the essential information from our repository. We can gather many more details if needed, but for this example, we only need to extract the Pull Request number before the merge. We can use a select statement to obtain the event information before the merge is executed.</p><pre>name : Push testing number PR<br>on :<br>  push :<br>    branches :<br>      - main<br>jobs :<br>    build :<br>        runs-on : ubuntu-latest<br>        env:<br>          SNOWSQL_PRIVATE_KEY : ${{ secrets.SNOWSQL_PRIVATE_KEY }}<br>          SNOWSQL_ACCOUNT : ${{ secrets.SNOWSQL_ACCOUNT }}<br>          SNOWSQL_USER : ${{ secrets.SNOWSQL_USER }}<br>          SNOWSQL_DATABASE : ${{ secrets.SNOWSQL_DATABASE }}<br>          SNOWSQL_SCHEMA : ${{ secrets.SNOWSQL_SCHEMA }}<br>          SNOWSQL_WAREHOUSE : ${{ secrets.SNOWSQL_WAREHOUSE }}<br>          SNOWSQL_ROLE : ${{ secrets.SNOWSQL_ROLE }}<br>          SNOWSQL_PRIVATE_KEY_PATH : /tmp/snowflake_rsa_key.p8<br>          SNOWSQL_PRIVATE_KEY_PASSPHRASE : ${{ secrets.SNOWSQL_PRIVATE_KEY_PASSPHRASE }}<br>        steps :<br>            - name : Checkout repository<br>              uses : actions/checkout@v4<br>            - name: Setup SSH Key<br>              run: |<br>                printf &#39;%s\n&#39; &quot;${SNOWSQL_PRIVATE_KEY}&quot; &gt; &quot;${SNOWSQL_PRIVATE_KEY_PATH}&quot;<br>            - name: Install jq<br>              run: sudo apt-get install -y jq<br>            - name : Get PR number using GH API<br>              id : pr_number<br>              ru : | <br>                RESPONSE=$(curl -s -H &quot;Authorization: token ${{ secrets.TOKEN_SECRET }}&quot; \<br>                    &quot;https://api.github.com/repos/${{ github.repository }}/pulls?state=closed&amp;per_page=10&quot; | sed &#39;s/[[:cntrl:]]//g&#39;)<br>                PR_NUMBER=$(echo &quot;$RESPONSE&quot; | jq -r &#39;.[] | select(.merge_commit_sha == &quot;${{ github.event.after }}&quot; ) | .number&#39;)<br>                echo &quot;PR number is $PR_NUMBER&quot;<br>                echo &quot;PR_NUMBER=$PR_NUMBER&quot; &gt;&gt; $GITHUB_OUTPUT<br>            - name: Install SnowSQL<br>              run: |<br>                curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.9-linux_x86_64.bash<br>                SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.9-linux_x86_64.bash<br>            - name: Run SnowSQL DROP SCHEMA<br>              run: |<br>                 ~/bin/snowsql --private-key-path $SNOWSQL_PRIVATE_KEY_PATH -q &quot;DROP SCHEMA IF EXISTS $SNOWSQL_DATABASE.PR_${{ steps.pr_number.outputs.PR_NUMBER }}_SCHEMA&quot;</pre><h3>Conclusion</h3><p>As a developer, I find the multi-layered testing approach in our warehouse development highly advantageous. This methodology enables us to include a variety of testing procedures, improve the accuracy of the data in our projects, and make the replication process more accessible by adding additional layers customized to each project&#39;s specific needs.</p><p>Moreover, we explored how to integrate GitHub Actions with Snowflake using SnowSQL and extract information from our repositories using the GitHub API.</p><p>Finally, projects with multiple repositories and layers like DEV, QA, and PROD can use this example and improve it with simple changes.</p><p>I&#39;m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux&#39;s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12920fc2a708" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/snowflake-github-actions-extract-information-and-automate-12920fc2a708">Snowflake GitHub Actions — Extract Information and Automate</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an end-to-end ELT solution with Snowflake and DBT]]></title>
            <link>https://blog.infostrux.com/building-an-end-to-end-elt-solution-with-snowflake-and-dbt-187bae83a87b?source=rss-dfe37d6c325------2</link>
            <guid isPermaLink="false">https://medium.com/p/187bae83a87b</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Jaime Andres Salas]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 15:02:30 GMT</pubDate>
            <atom:updated>2024-03-15T17:53:15.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to create an ETL Solution using Snowflake, Amazon S3, DBT, and Tableau</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03gdlXz7EGwRXulxWn0q3Q.png" /></figure><p>This is an end-to-end project with three main goals.</p><ol><li>To Extract, Load, and Transform (ELT) files from source through Amazon AWS S3 Storage and load them into Snowflake.</li><li>Create a DBT project using our Data Warehouse(Snowflake) to transform the data.</li><li>Create an integration of Snowflake and Tableau Desktop.</li></ol><p>So, let&#39;s get started.</p><h3>Amazon S3 Configuration</h3><p><strong>Creating S3 Bucket in AWS</strong></p><p>Create an S3 Bucket; the name must be unique, and all our files will be stored in AWS. The following link you can reach out to Airbnb Data: <a href="http://insideairbnb.com/get-the-data/">Airbnb Datasets</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GWjjwtlM3n0Q5i_4hF1fRQ.png" /><figcaption><em>Creating a new S3 Bucket</em></figcaption></figure><p><strong>Loading Data in S3</strong></p><p>For this step, it is necessary to download the different files from the city of interest. In my case, I&#39;d use Vancouver. I created the following structure in S3. This structure facilitates the best practices and gets all in order.</p><pre>snowflake-airbnb-elt<br>├── raw<br>│   ├── listings<br>│   ├── reviews</pre><p><strong>Creating a Connection between Snowflake and AWS</strong></p><p>To securely grant access to AWS services from Snowflake, we will utilize the Identity and Access Management (IAM) feature in AWS to create a specific role called “snowflake-airbnb-access.” We need to copy the ARN value for the next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*SiL14Pu5rwMFBFlPDd8kyA.png" /><figcaption><em>Creating a New Role in AWS</em></figcaption></figure><h3>Snowflake Configuration</h3><h4>Configuration initial in Snowflake</h4><p>At this point, we need to configure the workspace in Snowflake.</p><p>Let&#39;s create a new role, warehouse, database, and schemas.</p><pre>--Use an admin role <br>USE ROLE SYSADMIN;<br><br>--Create the dbt_transform role <br>CREATE OR REPLACE ROLE dbt_transform;<br>GRANT ROLE dbt_transform TO ROLE SYSADMIN;<br><br>--Create a new warehouse for development <br>CREATE OR REPLACE WAREHOUSE dbt_airbnb<br>WITH <br>WAREHOUSE_SIZE=XSMALL<br>MAX_CLUSTER_COUNT=3<br>AUTO_SUSPEND = 300 //Seconds<br>COMMENT = &#39;This is warehouse for development and testing&#39;;<br><br>--Create the dbt_user and assign to role<br>CREATE USER IF NOT EXISTS dbt_user<br>    PASSWORD = &#39;DBTpassword593&#39; &lt;your_snowflake_password&gt;<br>    LOGIN_NAME = &#39;dbt_user&#39;<br>    MUST_CHANGE_PASSWORD = FALSE<br>    DEFAULT_WAREHOUSE = &#39;DBT_AIRBNB&#39;<br>    DEFAULT_ROLE = &#39;dbt_transform&#39;<br>    DEFAULT_NAMESPACE = &#39;AIRBNB.RAW&#39;<br>    COMMENT = &#39;dbt user for operations and data transformation&#39;;<br>GRANT ROLE dbt_transform to USER dbt_user;<br><br>-- Create a new database and schema<br>CREATE OR REPLACE DATABASE AIRBNB;<br>CREATE OR REPLACE SCHEMA AIRBNB.RAW;<br><br>-- Set up permissions to role &#39;dbt_transform&#39;<br>GRANT ALL ON WAREHOUSE DBT_AIRBNB TO ROLE dbt_transform;<br>GRANT ALL ON DATABASE AIRBNB TO ROLE dbt_transform;<br>GRANT ALL ON ALL SCHEMAS IN DATABASE AIRBNB TO ROLE dbt_transform;<br>GRANT ALL ON FUTURE SCHEMAS IN DATABASE AIRBNB TO ROLE dbt_transform;<br>GRANT ALL ON ALL TABLES IN SCHEMA AIRBNB.RAW TO ROLE dbt_transform;</pre><h4>Creating Integration Object</h4><p>Now, we need to generate a <em>Storage Integration Object</em> that will allow us to fetch data from our S3 bucket into Snowflake. The code is provided below:</p><pre>-- Create a storage integration object<br>create or replace storage integration s3_airbnb_integration<br>  TYPE = EXTERNAL_STAGE<br>  STORAGE_PROVIDER = S3<br>  ENABLED = TRUE <br>  STORAGE_AWS_ROLE_ARN = &#39;&#39; -- Put your arn data from AWS.<br>  STORAGE_ALLOWED_LOCATIONS = (&#39;s3:&#39;) --Put your S3 Location<br>  COMMENT = &#39;Please note that access was only given to the CSV files&#39; ;<br>-- Using the DESC command to show the options in the new storage integration<br>DESC s3_airbnb_integration;</pre><h4>Loading and Transforming Data from S3</h4><p>The first step to load data into Snowflake from AWS S3 Storage is to create a table (raw table) where the data will be stored.</p><pre>-- Create Raw table reviews <br>USE DATABASE AIRBNB;<br>USE SCHEMA RAW;<br>CREATE TABLE IF NOT EXISTS reviews(<br>	listing_id int,<br>	id int,<br>	date varchar(30),<br>	reviewer_id int,<br>	reviewer_name varchar(60),<br>	comments string<br>	<br>);</pre><p>I am using only the following columns for the listings table; you can use more columns if needed.</p><pre>-- Create Raw table listings<br>CREATE TABLE IF NOT EXISTS listings(<br>	id int,<br>	listing_url string,<br>	last_scraped varchar(30),<br>	name string,<br>	neighborhood_overview string,<br>	picture_url string,<br>	host_id int,<br>	host_url string,<br>	host_name string,<br>	host_since varchar(30),<br>	host_location varchar(90),<br>	host_response_time varchar(45),<br>	host_response_rate varchar(30),<br>	host_acceptance_rate varchar(30),<br>	host_is_superhost varchar(10),<br>	host_neighbourhood varchar(70),<br>	host_listings_count int,<br>	host_total_listings_count int,<br>	host_identity_verified varchar(10),<br>	neighbourhood_cleansed varchar(45),<br>	property_type varchar(45),<br>	room_type varchar(30),<br>	accommodates int, <br>	bathrooms_text varchar(45),<br>	beds int,<br>	price varchar(20),<br>	minimum_nights int,<br>	maximum_nights int<br>);</pre><h4>Creating file format objects and external stages</h4><p>To load data files from an S3 bucket into a table, it is necessary to describe the file format and specify the desired interpretation and processing of the data within the file. To maintain organization and accommodate personal preference, I have established a separate schema called “files<em>formats” to store all my file formats and created another schema called” external</em>stages” for all my stages.</p><pre>/* Create a file format and stage for the reviews table*/  <br>CREATE SCHEMA IF NOT EXISTS AIRBNB.FILE_FORMATS;<br>CREATE SCHEMA IF NOT EXISTS AIRBNB.EXTERNAL_STAGES;<br>CREATE OR REPLACE file format airbnb.file_formats.csv_fileformat<br>	type = csv<br>	field_delimiter = &#39;,&#39;<br>	skip_header = 1<br>	null_if = (&#39;NULL&#39;, &#39;null&#39;)<br>	empty_field_as_null = TRUE<br>	FIELD_OPTIONALLY_ENCLOSED_BY = &#39;&quot;&#39;;<br><br>CREATE OR REPLACE stage airbnb.external_stages.reviews_folder<br>	URL = &#39;s3://snowflake-airbnb-elt/raw/reviews/&#39;<br>	STORAGE_INTEGRATION = s3_airbnb_integration<br>	FILE_FORMAT = airbnb.file_formats.csv_fileformat;<br><br>LIST @airbnb.external_stages.reviews_folder; -- See the files in S3 connection<br><br>/* Create a file format and stage for the listings table*/  <br>CREATE OR REPLACE file format airbnb.file_formats.csv_file_other<br>	type = csv<br>	field_delimiter = &#39;;&#39;<br>	skip_header = 1<br>	null_if = (&#39;NULL&#39;, &#39;null&#39;)<br>	empty_field_as_null = TRUE<br>	FIELD_OPTIONALLY_ENCLOSED_BY = &#39;&quot;&#39;;<br><br>CREATE OR REPLACE stage airbnb.external_stages.listings_folder<br>	URL = &#39;s3://snowflake-airbnb-elt/raw/listings/&#39;<br>	STORAGE_INTEGRATION = s3_airbnb_integration<br>	FILE_FORMAT = airbnb.file_formats.csv_file_other;<br><br>LIST @airbnb.external_stages.listings_folder;</pre><h4>Loading the data from the stage files:</h4><pre>-- Load data from Stage files into the reviews table<br>COPY INTO airbnb.raw.reviews<br>FROM @airbnb.external_stages.reviews_folder;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ETtTK_8dow4Z8LBeJkX3nQ.png" /><figcaption>The result of the Copy command</figcaption></figure><pre>-- Load data from Stage files into the listings table<br>COPY INTO airbnb.raw.listings<br>FROM @airbnb.external_stages.listings_folder;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qtmsHZ-Fp_m4roM8kyyDWg.png" /></figure><h4>Setting up our Snowpipes</h4><p>Snowpipe is an automated tool that fetches data from an Amazon Web Services (AWS) S3 Bucket as soon as it becomes available. Once you set up an event notification in AWS S3, Snowpipe is automatically triggered to load data from files into a stage in Snowflake. This means you don&#39;t have to load data into Snowflake manually — Snowpipe takes care of it for you as soon as new data is available in AWS S3.</p><pre>-- Create a new schema for storing all pipes<br>CREATE OR REPLACE schema airbnb.pipes;<br><br>-- Defining Snowpipe for reviews<br>CREATE OR REPLACE pipe airbnb.pipes.reviews<br>auto_ingest = TRUE <br>AS <br>COPY INTO airbnb.raw.reviews<br>FROM @airbnb.external_stages.reviews_folder; <br>desc pipe airbnb.pipes.reviews;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uRZ0i8JjDrJ0Hh_gF4LOIg.png" /><figcaption><em>A snow pipe notification channel for event notification in S3 AWS</em></figcaption></figure><p>We repeat the same step for listing data.</p><pre>-- Defining Snowpipe for listings<br>CREATE OR REPLACE pipe airbnb.pipes.listings<br>auto_ingest = TRUE <br>AS <br>COPY INTO airbnb.raw.listings<br>FROM @airbnb.external_stages.listings_folder; <br>desc pipe airbnb.pipes.airbnb.pipes.listings;</pre><h3>Transformations using DBT</h3><h4>Infostrux&#39;s Layered Modeling</h4><p>At Infostrux, we take data transformation seriously. That&#39;s why we use a sophisticated approach known as layered modeling. This approach not only ensures better data organization but also guarantees superior results.</p><p>If you want to learn about the different layers and transformations, you can look at <a href="https://blog.infostrux.com/utilizing-dbt-to-create-snowflake-data-pipelines-2112cc91f7fa%20">Eylon&#39;s Post</a>. Following this is an illustration of Layered modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GFKFoVX8XtvHZAVKo0KeWQ.png" /></figure><h4>Walkthrough Example: Snowflake with DBT models</h4><p>Let&#39;s walk through the different layers and transformations using dbt in Snowflake. For this example, we&#39;ll assume you have dbt installed.</p><p><strong>Step 1: Create a dbt project</strong></p><p>Commence by initiating a new dbt project. Access the preferred directory in your terminal and execute the subsequent command:</p><pre>dbt init my_dbt_project</pre><p>This action will establish a new dbt project with the required directory layout. This process may guide you through subsequent stages.</p><p><strong>Step 2: Configure your Snowflake profile</strong></p><p>In the “profiles.yml” file inside the project directory, add the details of your Snowflake connections created in the previous step (Configuration initial in Snowflake).</p><pre>dbtsnow:<br>	outputs:<br>		dev:<br>			account : &lt;snowflake_account_name&gt;<br>			database: &lt;your_dev_snowflake_database&gt;<br>			user: &lt;your_snowflake_user&gt;<br>			password: &lt;your_snowflake_password&gt;<br>			role: &lt;your_snowflake_role&gt;<br>			warehouse: &lt;your_dbt_snowflake_warehouse&gt;<br>			schema : &lt;your_dbt_snowflake_schema&gt;</pre><p>Substitute the placeholders (e.g., ‘&lt;snowflake-role&gt;’) with your specific Snowflake connection information.</p><p><strong>Step 3: Create the folder structure in the dbt project</strong></p><p>At this point, it is essential to create a solid folder structure to facilitate the creation of dbt transformations using SQL files. In Infostrux, we use the following structure in the models folder.</p><pre>dbt_project<br>├── models<br>│   ├── ingest<br>│   ├── clean<br>│   ├── normalize<br>│   ├── integrate<br>│   ├── analyze<br>│   ├── report</pre><p><strong>Step 4: Define Ingest data models</strong></p><p>The ingest subfolder contains files that are organized according to different data sources. We create a YAML file that describes the available tables and columns. Defining tests on the sources specified in the YAML file is also possible. In this case, we created a YAML file describing two data sources — listings and reviews.</p><pre>version: 2<br><br>sources:<br>  - name: airbnb<br>    schema: raw<br>    tables:<br>      - name: listings<br>      - name: reviews</pre><p><strong>Step 5: Define Clean data models</strong></p><p>This subfolder contains files arranged based on their data sources and needs simple cleaning tasks such as type casting, deduplication, and basic renaming to snowflake identifiers to avoid quoting. For this example, we demonstrate how to transform the listing source. However, you can create the other transformations for the review source.</p><pre>SELECT <br>    ID,<br>    LISTING_URL,<br>    LAST_SCRAPED::DATE AS LAST_SCRAPED, --TRANSFORM A DATE<br>    NAME,<br>    NEIGHBORHOOD_OVERVIEW,<br>    PICTURE_URL,<br>    HOST_ID,<br>    HOST_URL,<br>    HOST_NAME,<br>    HOST_SINCE::DATE AS HOST_SINCE, --TRANSFORM A DATE<br>    HOST_LOCATION,<br>    HOST_RESPONSE_TIME,<br>    CASE WHEN HOST_RESPONSE_RATE = &#39;N/A&#39; THEN NULL ELSE CAST( TRIM(HOST_RESPONSE_RATE,&#39;%&#39;) AS INT) END AS HOST_RESPONSE_RATE, --TRANSFORM A STRING TO INT<br>    CASE WHEN HOST_ACCEPTANCE_RATE = &#39;N/A&#39; THEN NULL ELSE CAST( TRIM(HOST_ACCEPTANCE_RATE,&#39;%&#39;) AS INT) END AS HOST_ACCEPTANCE_RATE, <br>    CASE WHEN HOST_IS_SUPERHOST = &#39;t&#39; THEN TRUE ELSE FALSE END AS HOST_IS_SUPERHOST, --TRANSFORM A STRING TO BOOLEAN<br>    HOST_NEIGHBOURHOOD,<br>    HOST_LISTINGS_COUNT,<br>    HOST_TOTAL_LISTINGS_COUNT,<br>    CASE WHEN HOST_IDENTITY_VERIFIED = &#39;t&#39; THEN TRUE ELSE FALSE END AS HOST_IDENTITY_VERIFIED, --TRANSFORM A STRING TO BOOLEAN<br>    NEIGHBOURHOOD_CLEANSED,<br>    PROPERTY_TYPE,<br>    ROOM_TYPE,<br>    ACCOMMODATES,<br>    BATHROOMS_TEXT,<br>    BEDS,<br>    CASE WHEN PRICE = &#39;null&#39; THEN NULL ELSE CAST( REPLACE(TRIM(PRICE,&#39;$&#39;),&#39;,&#39;,&#39;&#39;) AS FLOAT) END AS PRICE, --TRANSFORM A STRING TO FLOAT<br>    MINIMUM_NIGHTS,<br>    MAXIMUM_NIGHTS<br>FROM {{source(&#39;airbnb&#39;, &#39;listings&#39;)}}</pre><p><strong>Step 6: Define Normalize models</strong></p><p>The next step is applying business logic to transform data sources into structured tables and columns that align with the business domain&#39;s conceptual framework. For instance, column names should be according to BAM.</p><pre>SELECT <br>    ID,<br>    LISTING_URL,<br>    NAME,<br>    NEIGHBORHOOD_OVERVIEW,<br>    PICTURE_URL,<br>    HOST_ID,<br>    HOST_URL,<br>    HOST_NAME,<br>    HOST_SINCE,<br>    HOST_LOCATION,<br>    HOST_RESPONSE_TIME,<br>    HOST_RESPONSE_RATE,<br>    HOST_ACCEPTANCE_RATE,<br>    HOST_IS_SUPERHOST,<br>    HOST_NEIGHBOURHOOD,<br>    HOST_LISTINGS_COUNT,<br>    HOST_TOTAL_LISTINGS_COUNT,<br>    HOST_IDENTITY_VERIFIED,<br>    NEIGHBOURHOOD_CLEANSED,<br>    PROPERTY_TYPE,<br>    ROOM_TYPE,<br>    ACCOMMODATES,<br>    BATHROOMS_TEXT as BATHROOMS,<br>    BEDS,<br>    PRICE,<br>    MINIMUM_NIGHTS,<br>    MAXIMUM_NIGHTS,<br>    LAST_SCRAPED as _loaded_ts_utc<br>FROM<br>    {{ref(&#39;listings__clean&#39;)}}</pre><p><strong>Step 7: Define Integrate models</strong></p><p>We are currently integrating various data sources into our business models. In this example, we have established two tables — ‘listings’ and ‘host.’ We employ an incremental model to ensure that only new data is added. Below, you can find the code for the listings and host tables.</p><pre>--Listings__integrate table<br>{{<br>    config(<br>        materialized= &#39;incremental&#39;,<br>        on_schema_change=&#39;fail&#39;<br>        )<br>}}<br>SELECT <br>    ID,<br>    LISTING_URL as URL,<br>    NAME,<br>    NEIGHBORHOOD_OVERVIEW,<br>    PICTURE_URL,<br>    NEIGHBOURHOOD_CLEANSED,<br>    PROPERTY_TYPE,<br>    ROOM_TYPE,<br>    ACCOMMODATES,<br>    BATHROOMS,<br>    BEDS,<br>    PRICE,<br>    MINIMUM_NIGHTS,<br>    MAXIMUM_NIGHTS,<br>    HOST_ID,<br>    _loaded_ts_utc<br>FROM<br>    {{ref(&#39;listings__normalize&#39;)}}<br>WHERE ID IS NOT NULL<br>    {% if is_incremental() %}<br>        AND _loaded_ts_utc &gt; (select max(_loaded_ts_utc) from {{ this }})<br>    {% endif %}</pre><pre>--Host__integrate table<br>{{<br>    config(<br>        materialized= &#39;incremental&#39;,<br>        on_schema_change=&#39;fail&#39;<br>        )<br>}}<br>SELECT<br>    HOST_ID as ID,<br>    HOST_URL as url,<br>    HOST_NAME as name,<br>    HOST_SINCE as date_of_registration,<br>    HOST_LOCATION as location,<br>    HOST_RESPONSE_TIME as response_time,<br>    HOST_RESPONSE_RATE as response_rate,<br>    HOST_ACCEPTANCE_RATE as acceptance_rate,<br>    HOST_IS_SUPERHOST as is_superhost,<br>    HOST_NEIGHBOURHOOD as neighbourhood,<br>    HOST_LISTINGS_COUNT as listings_count,<br>    HOST_TOTAL_LISTINGS_COUNT as total_listings_count,<br>    HOST_IDENTITY_VERIFIED as identity_verified,<br>    _loaded_ts_utc<br>FROM<br>    {{ref(&#39;listings__normalize&#39;)}}<br>WHERE HOST_ID IS NOT NULL<br>    {% if is_incremental()%}<br>        AND _loaded_ts_utc &gt; (select max(_loaded_ts_utc) from {{this}})<br>    {% endif %}</pre><p><strong>Step 8: Define Analyze models</strong></p><p>The purpose of this layer is to denormalize the data into dimensions and facts. It is capable of producing fully denormalized wide tables. The star schema is a common feature in most engagements. Use cases and visualization tooling to drive wide tables. For this instance, we developed a denormalized table to analyze hosts and their listings, including beds and prices. The code for this is as follows:</p><pre>SELECT<br>    h.id,<br>    l.id as id_listing,<br>    l.beds,<br>    l.price<br>from {{ref(&quot;host__integrate&quot;)}} as h <br>inner join {{ref(&quot;listings__integrate&quot;)}} as l <br>on h.ID = l.host_id</pre><p><strong>Step 9: Define Report models</strong></p><p>This layer is not mandatory but can be utilized for data aggregation, calculations for business intelligence tools, or analysis purposes. The following example is created for analysis purposes.</p><pre>--- host_beds_prices__analyze<br>SELECT <br>    ID,<br>    AVG(BEDS) as AVG_BEDS,<br>    AVG(PRICE) as AVG_PRICE<br>FROM<br>    {{ref(&quot;host_beds_prices__analyze&quot;)}}<br>GROUP BY ID</pre><p><strong>Step 10: Run dbt</strong></p><p>To transform the data, please run the following command in your terminal:</p><pre>dbt run -- profile snowflake_dev_profile</pre><p>dbt will connect to Snowflake using the specified profile, execute the SQL defined in the data model, and create tables in the specified schema.</p><p><strong>Step 11: View the transformed data</strong></p><p>After completing the dbt run, the transformed data can be accessed in Snowflake. For instance, using a worksheet, you can query the “host_avg_bed_price__report” table in Snowflake.</p><pre>SELECT * FROM AIRBNB.DEV.HOST_AVG_BED_PRICE__REPORT;</pre><h4>Visualization with Tableau Powered by Snowflake</h4><p>Let&#39;s start with integration. First, Tableau Desktop must be installed. Next, connect to data using connectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KWfPSxtr_hQuQjF4GqA-6w.png" /></figure><p>Provide your Snowflake account URL, username, and password. Then, click on the sign-in button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*aKa7JpThhUnTafDmpwaHFw.png" /></figure><p>Select <strong>Warehouse, Database, Schema,</strong> and <strong>Table</strong> on the left-hand side of the page. Then, drag and drop the table onto Tableau for further analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*QNS7HUaiLEQ13WUPU_xMDg.png" /></figure><p><strong>The integration of Snowflake with Tableau has been accomplished successfully.</strong></p><p>It is now possible to effortlessly analyze different tables and datasets available in Snowflake.</p><h3>Conclusion</h3><p>As a developer, I understand the significance of ELT pipelines in handling data and utilizing Snowflake. Snowflake is a warehouse design for ELT solutions. In this blog post, we explored the best technologies used to create an end-to-end ELT solution, which includes ingesting data and analyzing it with AWS S3, Snowflake, DBT, and Tableau.</p><p>Moreover, we explored the various layers and transformations within the initiative by utilizing dbt, which can run Snowflake&#39;s SQL scripts and provide exceptional adaptability. By leveraging dbt, you can maximize the potential of Snowflake while maintaining comprehensive authority over your data adjustments and monitoring alterations effortlessly.</p><p>Finally, projects with multiple data sources can follow the same methodology using this example.</p><p>I&#39;m Jaime Salas, Senior Data Engineer for <a href="https://www.infostrux.com/">Infostrux Solutions</a>. You can follow me on <a href="https://www.linkedin.com/in/jaimeandresalas/">LinkedIn</a>.</p><p>Subscribe to Infostrux Medium Blog at <a href="https://blog.infostrux.com/">https://blog.infostrux.com</a> for the most interesting Data Engineering and Snowflake news. Follow Infostrux&#39;s open-source efforts through <a href="https://github.com/Infostrux-Solutions">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=187bae83a87b" width="1" height="1" alt=""><hr><p><a href="https://blog.infostrux.com/building-an-end-to-end-elt-solution-with-snowflake-and-dbt-187bae83a87b">Building an end-to-end ELT solution with Snowflake and DBT</a> was originally published in <a href="https://blog.infostrux.com/">Infostrux Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>