<?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 Manish Shrivastava on Medium]]></title>
        <description><![CDATA[Stories by Manish Shrivastava on Medium]]></description>
        <link>https://medium.com/@manishshrivastava26?source=rss-25c37688b91c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_sBrHsO24AB8dRAW.jpg</url>
            <title>Stories by Manish Shrivastava on Medium</title>
            <link>https://medium.com/@manishshrivastava26?source=rss-25c37688b91c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:40:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manishshrivastava26/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[The Hidden Cost of Enterprise RAG: Retrieval Debt]]></title>
            <link>https://medium.com/@manishshrivastava26/the-hidden-cost-of-enterprise-rag-retrieval-debt-dc39a99a7361?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc39a99a7361</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 05:01:15 GMT</pubDate>
            <atom:updated>2026-07-23T05:01:15.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Why your AI assistant got worse the more you fed it — and what to do about it</p><p>Most RAG systems don’t fail because of the model.<br>They fail because of something quieter, slower, and much harder to spot on a dashboard. I call it Retrieval Debt.<br>If you’ve ever watched an internal AI assistant launch to genuine excitement and then, six months later, quietly stop being used — this article is about what happened in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7u06YE1dZHews0ybIEJ5Fw.png" /><figcaption>Document Corpus vs Answer Quality</figcaption></figure><h3>What Retrieval Debt actually is</h3><p>Retrieval Debt accumulates when teams keep adding documents, knowledge sources, and embeddings to a RAG system without actively managing retrieval quality.<br>It behaves exactly like technical debt. Every shortcut is individually reasonable. Nobody makes a bad decision. And yet the system gets worse over time, and by the time it’s obvious, the cause is buried under eighteen months of well-intentioned contributions.<br>The mechanism is simple:</p><h4>Adding content increases what your system can find. It does nothing to improve what it should return.</h4><p>Those are different problems. Most teams only invest in the first one.</p><h3>A quick primer, if RAG is new to you</h3><p>Retrieval-Augmented Generation works in two steps. First, a retrieval step searches your knowledge base and pulls back the chunks of text most likely to answer the user’s question. Second, a generation step hands those chunks to a language model, which writes an answer using them as source material.<br>The critical thing to understand: the model can only work with what retrieval hands it. If retrieval returns five contradictory documents, no model on earth can reliably pick the right one. Garbage in, confidently-worded garbage out.<br>That’s why Retrieval Debt is so dangerous. It degrades the input layer, but every symptom shows up in the output layer — where everyone blames the model.</p><h3>The lifecycle: how good systems go bad</h3><h4>Phase 1 — The honeymoon (0-6 months)</h4><p>You start with a curated corpus. Maybe two hundred documents, hand-picked by someone who understood the domain. Results are strong. Users are genuinely impressed. Leadership asks how fast you can expand it.<br>Accuracy looks great because the corpus is small and clean, not because your architecture is sound. This distinction matters enormously later.</p><h4>Phase 2 — The expansion (6-12 months)</h4><p>Success creates demand. More teams want in. The corpus grows from hundreds of documents to tens of thousands. Onboarding new sources becomes a self-service pipeline, because manually reviewing everything doesn’t scale.<br>Quality is still acceptable. Slightly noisier, but nobody’s alarmed.</p><h4>Phase 3 — The drift (12-18 months)</h4><p>Documentation versions multiply — v1, v2, &quot;v2 FINAL&quot;, and the Confluence page someone wrote instead of updating v2. Business terminology evolves, but old documents keep the old vocabulary. The same policy exists in three repositories, each subtly different.<br>Retrieval starts pulling back near-duplicates. The model receives conflicting instructions. Answers become inconsistent — right on Monday, wrong on Thursday, for the same question.</p><h4>Phase 4 — The abandonment (18+ months)</h4><p>Users don’t file bug reports. They just stop trusting it. They go back to asking a colleague on Slack.<br>This is the part that catches teams off guard: there is no incident. No outage, no alert, no failed deployment. Just a slow decline in usage that shows up in a quarterly review as &quot;low adoption.&quot;</p><h3>The pain points, and how to recognize them</h3><p>Retrieval Debt announces itself through symptoms that all look like model problems. Here’s how to tell them apart.</p><h4>1. Contradictory answers to the same question</h4><p>What you see: A user asks about the refund policy and gets one answer. A colleague asks the same thing an hour later and gets a different one.<br>What’s happening: Multiple versions of the same source document exist. Retrieval returns whichever scored marginally higher this time. Semantic similarity can’t tell you which version is current — that information isn’t in the text.<br>Why the model isn’t at fault: It faithfully summarized what it was given. It was given two conflicting truths.</p><h4>2. Confidently wrong answers citing real documents</h4><p>What you see: The answer is well-written, cites an internal document by name, and is completely out of date.<br>What’s happening: A deprecated document was never removed from the index. Nothing in your pipeline knows it’s deprecated, because &quot;deprecated&quot; is a governance fact, not a semantic one.<br>Why this is the most dangerous symptom: A visibly wrong answer gets corrected. A plausible, well-sourced, wrong answer gets acted upon.</p><h4>3. Token costs climbing without accuracy improving</h4><p>What you see: Your monthly spend rises steadily. Answer quality doesn’t.<br>What’s happening: As the corpus grows, retrieved chunks get less precise, so someone increased top_k to compensate. Now you’re paying to send more marginally-relevant context to the model — which often reduces accuracy, because the signal gets diluted.<br>The trap: Increasing retrieved context feels like it should help. Past a certain point, it reliably hurts.</p><h4>4. Rising latency nobody can explain</h4><p>What you see: Response times creep from two seconds to eight.<br>What’s happening: Larger indexes, larger payloads, more re-ranking work. Individually small; cumulatively, the difference between a tool people use and a tool people don’t.</p><h4>5. Nobody can explain why a specific answer was wrong</h4><p>What you see: A user reports a bad answer. Your team can’t reproduce it or trace which documents produced it.<br>What’s happening: No retrieval logging. This is the symptom that guarantees the others go unfixed, because you’re debugging blind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruRwF7kobzTTc_kX3qAN3Q.png" /><figcaption>Diagnostic Checklist</figcaption></figure><h3>Why the standard fixes don’t work</h3><p>When quality drops, three responses are nearly universal. All three are reasonable. None address the cause.<br>&quot;Let’s switch to a better model.&quot; A stronger model reasons better over the context it receives. It does not know that document three is superseded by document five. You’ve upgraded the chef; the ingredients are still spoiled.<br>&quot;Let’s expand the context window.&quot; Now all five conflicting versions fit comfortably. You’ve made the contradiction more complete, not less. There’s also solid evidence that models handle information in the middle of long contexts less reliably than at the edges — so more context can actively mask the right answer.<br>&quot;Let’s improve the prompt.&quot; Prompt engineering can help the model handle ambiguity gracefully. It cannot manufacture the metadata needed to resolve the ambiguity. You can ask for the most recent version, but if recency isn’t in your index, the model is guessing.<br>The uncomfortable pattern underneath all three: RAG performance degrades because knowledge management practices fail to evolve alongside the AI system. Teams treat the AI as the product and the corpus as a resource to fill it. It’s the other way around.</p><h3>A framework: RAG = Retrieval + Relevance + Governance</h3><p>Three questions, in order. Most teams only ever answer the first.</p><h4>Retrieval — Can the right information be found?</h4><p>This is the plumbing: chunking strategy, embedding model, index configuration, hybrid search, re-ranking. It’s where nearly all engineering attention goes, because it’s the part that looks like engineering.</p><p>Necessary. Nowhere near sufficient.</p><h4>Relevance — Is what’s retrieved actually useful for this question?</h4><p>Semantic similarity is not the same as usefulness. A document can be topically perfect and practically useless — because it’s for a different region, a different customer tier, or a different fiscal year.<br>Relevance is where retrieval meets the user’s actual situation. It’s typically solved with metadata filtering, re-ranking on business signals, and query understanding — not with a better embedding model.</p><h4>Governance — Is this information current, trusted, and owned?</h4><p>The question almost nobody asks at design time.Who owns this document?</p><ul><li>When was it last reviewed?</li><li>What supersedes it?</li><li>Who is allowed to see it?</li><li>How does it leave the index</li><li>when it’s retired?</li></ul><p>None of this is discoverable from the text. It has to be attached deliberately, maintained continuously, and enforced at retrieval time.<br>This is the layer where Retrieval Debt accumulates, precisely because it isn’t anyone’s job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1sHRRMyuH82-EBjuxH8Og.png" /><figcaption>The Three Layer</figcaption></figure><h3>A worked example</h3><p>Consider an enterprise knowledge platform containing five versions of the same operational procedure:</p><ol><li>The original, from 2021</li><li>A 2022 revision</li><li>A regional variant for a different market</li><li>A slide deck summarizing the procedure</li><li>A wiki page someone wrote instead of updating the source</li></ol><p>A user asks how to handle a specific exception case.<br>The vector database retrieves all five. They’re semantically near-identical — that’s exactly what the embedding model is designed to notice. The model receives five sets of instructions that disagree on the specifics, and produces an answer that blends them.<br>The output is fluent, confident, and wrong.<br>Nothing in this pipeline malfunctioned. The embeddings worked. The vector search worked. The model worked. The system correctly executed a process that was never designed to answer the question &quot;which of these is authoritative?&quot;<br>That question isn’t a modeling problem. It’s a governance problem wearing a modeling problem’s clothes.</p><h3>What to actually measure</h3><p>&quot;Response accuracy&quot; is a lagging indicator that aggregates away everything useful. Here’s what to instrument instead, roughly in order of implementation difficulty.<br>Retrieval precision @ k — Of the chunks you retrieved, what proportion were genuinely relevant? Requires a labeled evaluation set. Build one; it’s the single highest-leverage thing on this list.<br>Retrieval recall — When the right answer exists in your corpus, how often does retrieval surface it? Catches the failures users never report, because they can’t know what they didn’t get.<br>Source concentration — How many distinct source documents contribute to a typical answer? A sudden rise often means near-duplicates are crowding the results.<br>Content freshness distribution — What’s the age profile of documents actually being retrieved? If your median retrieved document is three years old, you have a problem regardless of what accuracy scores say.<br>Duplicate density — Run pairwise similarity across your corpus. Clusters above a high threshold are Retrieval Debt you can see and quantify.<br>Answer consistency — Ask the same question repeatedly across a period. Variance in the substance of answers, not the wording, is a strong signal of conflicting sources.<br>Coverage gaps — Which queries consistently retrieve low-scoring context? These tell you what your corpus is missing, which is usually more actionable than what it gets wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntqx_RFO_2V2ZX3v2mOaKA.png" /><figcaption>Knowledge Quality Metrics</figcaption></figure><h3>A learning path</h3><p>If this is a gap you want to close — whether you’re an engineer building these systems or someone moving into the space — here’s a sequence that builds in a sensible order. Each stage is useful on its own.</p><h4>Stage 1 — Understand the mechanics (start here)</h4><p>Build a small RAG system end to end. Two hundred documents is plenty. Do it manually enough that you see every step: chunking, embedding, storing, retrieving, generating.<br>What you should be able to explain afterward: what an embedding is, why chunk size changes results, what top_k does, and why semantic similarity is not the same as relevance.<br>Do this before touching a framework. Frameworks hide exactly the mechanics you need to understand.</p><h4>Stage 2 — Learn to evaluate retrieval in isolation</h4><p>Before improving anything, learn to measure it. Build a small evaluation set: fifty real questions with the documents that should be retrieved for each.<br>Then measure retrieval quality on its own, with no model in the loop. This is the skill that separates people who tune RAG systems from people who guess at them.<br>What you should be able to explain afterward: precision and recall in a retrieval context, why offline evaluation and user-reported accuracy diverge, and how to build an evaluation set that doesn’t just confirm what you already believe.</p><h4>Stage 3 — Master the retrieval toolkit</h4><p>Now the techniques mean something, because you can measure whether they help.<br>Hybrid search (combining keyword and semantic)<br>Re-ranking with a cross-encoder<br>Query rewriting and expansion<br>Chunking strategies beyond fixed-size splits<br>Metadata filtering<br>The habit to build: change one thing, measure it against your evaluation set, keep it only if the numbers move. Most retrieval &quot;best practices&quot; are context-dependent, and yours may be the context where they don’t apply.</p><h4>Stage 4 — Learn the governance layer</h4><p>This is where most curricula stop and most real systems fail.<br>Document lifecycle: ingestion, review, supersession, retirement<br>Metadata schema design — what needs to travel with every document<br>Ownership models: who is accountable for a source staying accurate<br>Access control at retrieval time, not just at the application layer<br>Deduplication and canonical-source designation<br>Where to learn it: honestly, mostly from data governance practice rather than AI material. The problems were solved for analytics platforms a decade ago; the discipline transfers almost directly.</p><h4>Stage 5 — Build the operational layer</h4><ul><li>Retrieval logging: for every answer, which chunks, which scores, which documents</li><li>Regression testing on your evaluation set, in CI</li><li>Freshness and duplicate monitoring as scheduled jobs</li><li>User feedback capture that ties back to specific retrievals<br>The test of whether you’ve succeeded: a user reports a bad answer and you can identify, within minutes, exactly which documents produced it.</li></ul><h4>Stage 6 — Treat knowledge as a product</h4><p>The final shift is organizational rather than technical. Someone owns the corpus. It has a roadmap, quality standards, deprecation policies, and a defined review cycle.<br>This is the stage that prevents the debt from re-accumulating. Everything before it is remediation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYt3QSxKc85rMGqUoyhEPg.png" /><figcaption>RAG Mastery Learning path</figcaption></figure><h3>Where this is heading</h3><p>As GenAI adoption moves from pilots to systems people depend on, retrieval governance will become as important as data governance became for analytics platforms.<br>The parallel is close. Analytics went through this exact arc: an initial phase of enthusiastic data collection, a middle phase where nobody trusted the numbers because six dashboards gave six answers, and an eventual maturity where lineage, ownership, and quality standards became non-negotiable.<br>RAG is somewhere in the middle phase right now.<br>The organizations that treat knowledge as a managed product — not a collection of documents to be indexed — will get substantially better AI outcomes than those with better models and worse corpora. That gap is going to widen, because model capability is converging and corpus quality isn’t.</p><h3>The short version</h3><ul><li>Retrieval Debt accumulates silently as you add content without managing quality</li><li>It presents as model failure, which sends teams to fix the wrong layer</li><li>More data is not more knowledge — past a point, it’s actively less</li><li>Retrieval, relevance, and governance are three separate problems, and only the first looks like engineering</li><li>If you can’t trace which documents produced an answer, you can’t fix anything else on this list</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjMqVuTL_AGUgZ2Umq3mFw.png" /></figure><p>How is your team measuring retrieval quality today, beyond response accuracy? I’d genuinely like to know what’s working — this is a problem where the practices are still being figured out in public.</p><p>#GenAI #RAG #DataEngineering #EnterpriseAI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc39a99a7361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Your Trade Journaling with AI: An n8n + Gemini Workflow]]></title>
            <link>https://medium.com/@manishshrivastava26/automate-your-trade-journaling-with-ai-an-n8n-gemini-workflow-30e408abcf5f?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e408abcf5f</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 10:09:15 GMT</pubDate>
            <atom:updated>2026-01-10T08:17:41.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pp6Aj61WlGWVO8zXY5QgQ.png" /></figure><p><em>Send a screenshot to Telegram, and watch AI extract your trades into a Google Sheet</em></p><p>If you’re a trader, you know the importance of maintaining a trade journal. But let’s be honest — manually logging every trade is tedious, error-prone, and something we often skip “just this once.”</p><p>What if you could simply send a screenshot of your trade execution to Telegram, and have AI automatically extract all the details and log them to a Google Sheet?</p><p>That’s exactly what I built using <strong>n8n</strong> and <strong>Google Gemini Vision AI</strong>.</p><p>Complete Workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9eI_r_V8c4yWZEN7DHrSw.png" /><figcaption>n8n Workflow</figcaption></figure><h3>The Problem</h3><p>As a trader, I was struggling with:</p><ul><li><strong>Forgetting to log trades</strong> in the heat of the moment</li><li><strong>Manual data entry errors</strong> when copying numbers</li><li><strong>Inconsistent journaling</strong> — some days I’d log everything, others nothing</li><li><strong>No real-time notifications</strong> when trades were logged</li></ul><h3>The Solution: AI-Powered Trade Journaling</h3><p>I created an n8n workflow that:</p><ol><li><strong>Receives screenshots</strong> via a Telegram bot</li><li><strong>Extracts trade details</strong> using Google’s Gemini Vision AI</li><li><strong>Logs everything</strong> to a Google Sheet automatically</li><li><strong>Sends email confirmation</strong> with a link to the journal</li></ol><p>The best part? It handles <strong>multiple trades in a single screenshot</strong> — perfect for those busy trading sessions.</p><h3>How It Works</h3><h3>Step 1: Telegram Trigger</h3><p>The workflow starts when you send a screenshot to your personal Telegram bot. n8n’s Telegram trigger receives the message and downloads the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*dXkFlxD3RF3Nc3dH47p9VQ.png" /><figcaption>Telegram Trigger</figcaption></figure><h3>Step 2: Convert to Base64</h3><p>A Code node converts the binary image data to base64 format, which is required by the Gemini Vision API:</p><pre>// Get the binary buffer properly<br>const binaryPropertyName = &#39;data&#39;;<br>const binaryData = await <br>this.helpers.getBinaryDataBuffer(0, binaryPropertyName);<br><br>// Convert buffer to base64<br>const base64Image = binaryData.toString(&#39;base64&#39;);<br><br>// Get mime type from binary metadata<br>const mimeType = $input.first().binary[binaryPropertyName].mimeType;<br><br>return {<br>  base64_image: base64Image,<br>  mime_type: mimeType || &#39;image/jpeg&#39;<br>};</pre><h3>Step 3: Gemini Vision Analysis</h3><p>The image is sent to Google’s Gemini 2.5 Flash model with a prompt to extract trade details:</p><pre>Extract trade details from this screenshot as JSON: <br>symbol, trade_type (BUY/SELL), entry_price, quantity, broker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHh9qseKD8waH8WZm9JOmQ.png" /></figure><p>The AI returns structured JSON with all the trades it found — even if there are multiple trades in one screenshot!</p><pre>[<br>  {<br>    &quot;symbol&quot;: &quot;ANANTRAJ&quot;,<br>    &quot;trade_type&quot;: &quot;SELL&quot;,<br>    &quot;entry_price&quot;: 704.61,<br>    &quot;quantity&quot;: 25,<br>    &quot;broker&quot;: &quot;Zerodha&quot;<br>  },<br>  {<br>    &quot;symbol&quot;: &quot;GMDCLTD&quot;,<br>    &quot;trade_type&quot;: &quot;BUY&quot;,<br>    &quot;entry_price&quot;: 609.60,<br>    &quot;quantity&quot;: 20,<br>    &quot;broker&quot;: &quot;Zerodha&quot;<br>  }<br>]</pre><h3>Step 4: Parse and Log to Sheets</h3><p>Another Code node parses the response and creates an entry for each trade. The Google Sheets node then appends each trade as a separate row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH6QF3vFkg44qSI3e1w8Fw.png" /></figure><h3>Step 5: Email Notification</h3><p>Finally, Gmail sends you a confirmation email with a link to your trade journal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnSxgBYWHCahx7PXM0ToVQ.png" /></figure><h3>Hosting Options</h3><p>Since Telegram webhooks require a publicly accessible URL, you have a few options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*HUJRV9vEidkju5iBPp-hgw.png" /></figure><h3>API Free Tiers</h3><p>ServiceFree Limit<strong>Gemini API</strong>60 requests/minute<strong>Google Sheets</strong>Unlimited<strong>Gmail</strong>500 emails/day<strong>Telegram Bot</strong>Unlimited</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*L_3zsT6TK2XJ3uiLOPMICg.png" /></figure><h3>Setting It Up</h3><h3>Prerequisites</h3><ol><li><strong>n8n</strong> — <a href="https://n8n.cloud/">n8n.cloud</a> (easiest) or self-hosted with public URL</li><li><strong>Telegram Bot</strong> — Create via @BotFather (takes 2 minutes)</li><li><strong>Gemini API Key</strong> — Get free from <a href="https://aistudio.google.com/">aistudio.google.com</a></li><li><strong>Google Account</strong> — For Sheets and Gmail</li></ol><h3>Quick Start</h3><ol><li>Clone the repository:</li></ol><pre>git clone https://github.com/manish6007/trading_journal_automation_n8n.git</pre><ol><li>Import workflow.json into n8n</li><li>Configure your credentials:</li></ol><ul><li>Telegram Bot Token</li><li>Gemini API Key</li><li>Google Sheets OAuth</li><li>Gmail OAuth</li></ul><p>3. Create a Google Sheet with columns:</p><p>Date | Symbol | Buy/Sell | Trade Price | Quantity | Broker | Logged At</p><p>4. Activate the workflow and send a test screenshot!</p><h3>Key Learnings</h3><p>Building this workflow taught me a few things:</p><ol><li><strong>n8n’s binary handling</strong> — Binary data in newer n8n versions is stored in the filesystem. You need this.helpers.getBinaryDataBuffer() to read it.</li><li><strong>Gemini’s Vision capabilities</strong> — The free tier is surprisingly powerful and handles messy trading screenshots well.</li><li><strong>Handling multiple items</strong> — When Gemini returns an array of trades, the Code node can return multiple items that flow through subsequent nodes.</li></ol><h3>What’s Next?</h3><p>I’m planning to extend this with:</p><ul><li><strong>Exit price tracking</strong> — Send another screenshot when closing the trade</li><li><strong>P&amp;L calculation</strong> — Automatic profit/loss based on entry and exit</li><li><strong>Weekly summary emails</strong> — Digest of the week’s trades</li><li><strong>Slack/Discord integration</strong> — For team trading groups</li></ul><h3>Get the Code</h3><p>The complete workflow is open-source and available on GitHub:</p><p>🔗 <a href="https://github.com/manish6007/trading_journal_automation_n8n"><strong>github.com/manish6007/trading_journal_automation_n8n</strong></a></p><p>Feel free to fork, customize, and make it your own!</p><h3>Conclusion</h3><p>Trade journaling doesn’t have to be a chore. With AI and automation, you can build a system that works for you — not the other way around.</p><p>Send a screenshot, get a journal entry. It’s that simple.</p><p>Happy trading! 📈</p><p><em>If you found this useful, give it a clap and follow for more automation tutorials!</em></p><p>Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=manish-shrivastava-1657b423">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=manish-shrivastava-1657b423</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e408abcf5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Agents with MCP and Amazon Bedrock: From Basics to Real-World Apps]]></title>
            <link>https://medium.com/@manishshrivastava26/building-ai-agents-with-mcp-and-amazon-bedrock-from-basics-to-real-world-apps-42aa562af2d7?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/42aa562af2d7</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 08:49:28 GMT</pubDate>
            <atom:updated>2025-09-28T09:18:13.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZk-Su8QL39AtT44one7Iw.png" /></figure><h3>🚀 Introduction</h3><p>In modern AI development, <strong>monolithic agents</strong> — those tightly coupled with their tools — quickly become brittle and hard to scale. Every time you add or change a dependency, the agent’s code must change. That’s where the <strong>Model Context Protocol (MCP)</strong> comes in.</p><p>MCP, introduced by Anthropic, decouples agents from the tools they use. Instead of hardcoding tool logic inside an agent, you connect to standardized <strong>MCP servers</strong>. At runtime, your agent can discover the tools, their descriptions, and how to use them.</p><p>This article walks you through building powerful, modular agents with <strong>MCP</strong> and <strong>Amazon Bedrock</strong> — step by step. All code is available here: <a href="https://github.com/manish6007/ai-agents-with-mcp">AI-Agents-with-MCP</a></p><p>By the end, you’ll see:</p><ul><li>A baseline agent using Claude on Amazon Bedrock</li><li>Enhancing it with local tools</li><li>Connecting to AWS Documentation MCP server</li><li>Orchestrating multiple MCP servers (Docs + Pricing)</li><li>Building your own MCP server (Calculator)</li><li>A real-world demo: <strong>Kite MCP + Streamlit UI</strong></li></ul><h3>🔹 What is MCP &amp; Why it Matters</h3><p>The <strong>Model Context Protocol (MCP)</strong> is like an API contract between AI agents and external tools. MCP servers expose tools with schemas and docstrings, while agents dynamically discover and use them.</p><p>Think of MCP as <strong>microservices for AI agents</strong>. Each MCP server encapsulates a specific business capability (docs, pricing, databases, etc.), and your agent can plug into them without being rewritten.</p><p>Benefits:</p><ul><li>🔌 <strong>Decoupling</strong> — no hardcoding tools in agent code</li><li>📦 <strong>Modularity</strong> — reuse servers across projects</li><li>🏗️ <strong>Scalability</strong> — compose multiple servers to solve complex problems</li><li>🤝 <strong>Collaboration</strong> — share MCP servers across teams</li></ul><h3>🛠️ Environment Setup</h3><h3>Prerequisites</h3><ul><li>Python <strong>3.12+</strong></li><li>uv (fast Python package/environment manager)</li></ul><p>Install uv:</p><pre>pip install uv</pre><p>Create a new project environment:</p><pre>uv venv --python 3.12</pre><p>Activate it:</p><pre>source .venv/bin/activate # Linux/macOS<br>.venv\Scripts\activate # Windows PowerShell</pre><p>Install dependencies:</p><pre>uv pip install -r requirements.txt</pre><p>Repo: <a href="https://github.com/manish6007/ai-agents-with-mcp">AI-Agents-with-MCP</a></p><h3>📖 Scenario 1: Baseline Agent &amp; Single MCP Server</h3><h3>Baseline Agent</h3><p>A simple agent powered by Amazon Bedrock (Claude 3 Sonnet):</p><pre>from strands import Agent<br><br><br>model = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br>task = &quot;write Python code to differentiate an equation&quot;<br><br><br>agent = Agent(model=model, system_prompt=&quot;You are a helpful coding assistant&quot;)<br>response = agent(task)<br>print(response)</pre><p>It writes code but cannot execute it.</p><p><strong>Adding a Local Tool</strong></p><p>We add a tool like file_writter and code interpreter to let the agent execute and save code:</p><pre>from strands import Agent<br>from strands_tools import file_write, code_interpreter  # note: python_repl (not Python_ripple)<br><br># Clear task and filename<br>task = &quot;Write Python code that symbolically differentiates y = x**2 + 3*x + 5 and save it to diff.py&quot;<br><br>model = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br><br># In the example the tools are provided as callables (decorated with @tool),<br># so pass them directly (no instantiation) unless your local API requires otherwise.<br>tools = [ code_interpreter, file_write]<br><br>agent = Agent(model=model, tools=tools)<br><br>try:<br>    result = agent(task)<br>except Exception as e:<br>    print(&quot;Agent.run failed:&quot;, e)<br>else:<br>    print(&quot;Agent result:&quot;)<br>    print(result)</pre><p><strong>Connecting to AWS Documentation MCP Server</strong></p><p>Instead of relying only on the LLM’s internal knowledge, connect to <strong>AWS Documentation MCP Server</strong>:</p><pre>from strands import Agent<br>from strands.tools.mcp import MCPClient<br>from mcp import stdio_client, StdioServerParameters<br><br><br>stdio_mcp_client = MCPClient(lambda: stdio_client(<br>StdioServerParameters(<br>command=&quot;uvx&quot;,<br>args=[&quot;--from&quot;, &quot;awslabs.aws-documentation-mcp-server@latest&quot;, &quot;awslabs.aws-documentation-mcp-server.exe&quot;]<br>)<br>))<br><br><br>model = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br>with stdio_mcp_client:<br>tools = stdio_mcp_client.list_tools_sync()<br>agent = Agent(model=model, tools=tools)<br>print(agent(&quot;What is AWS Lambda?&quot;))</pre><p>Now the agent answers with <strong>real AWS documentation</strong>, not hallucinations.</p><p>📖<strong> Scenario 2: Multi-MCP Orchestration</strong></p><p>Real power comes from combining multiple MCP servers. Example: generating a report on fine-tuning Llama in SageMaker — requiring <strong>Docs + Pricing</strong>.</p><pre>from strands import Agent<br>from strands.tools.mcp import MCPClient<br>from mcp import stdio_client, StdioServerParameters<br><br><br>def create_mcp_client(command, args):<br>return MCPClient(lambda: stdio_client(StdioServerParameters(command=command, args=args)))<br><br><br>model = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br>task = &quot;&quot;&quot;<br>What is SageMaker&#39;s fine-tuning ability?<br>How can I fine-tune the Llama model?<br>What type of SageMaker instances will I need? How much do they cost?<br>Which region should I use?<br>Write the report.<br>&quot;&quot;&quot;<br><br><br>doc_client = create_mcp_client(&quot;uvx&quot;, [&quot;--from&quot;, &quot;awslabs.aws-documentation-mcp-server@latest&quot;, &quot;awslabs.aws-documentation-mcp-server.exe&quot;])<br>pricing_client = create_mcp_client(&quot;uvx&quot;, [&quot;--from&quot;, &quot;awslabs.aws-pricing-mcp-server@latest&quot;, &quot;awslabs.aws-pricing-mcp-server.exe&quot;])<br><br><br>with doc_client, pricing_client:<br>tools = doc_client.list_tools_sync() + pricing_client.list_tools_sync()<br>agent = Agent(model=model, tools=tools)<br>print(agent(task))</pre><p>The agent dynamically queries both servers and synthesizes a comprehensive answer.</p><p>📖 <strong>Scenario 3: Custom MCP Server</strong></p><p>Enterprises can expose proprietary logic securely using MCP. Example: a Calculator MCP server.</p><p><strong>Server</strong></p><pre>from mcp.server import FastMCP<br><br><br>mcp = FastMCP(&quot;Calculator Server&quot;)<br><br><br>@mcp.tool(description=&quot;Add two numbers&quot;)<br>def add(x: int, y: int) -&gt; int:<br>return x + y<br><br><br>@mcp.tool()<br>def subtract(a: float, b: float) -&gt; float:<br>return a - b<br><br><br>mcp.run(transport=&quot;streamable-http&quot;)</pre><p><strong>Client</strong></p><pre>from mcp.client.streamable_http import streamablehttp_client<br>from strands import Agent<br>from strands.tools.mcp import MCPClient<br><br><br>def create_transport():<br>return streamablehttp_client(&quot;http://127.0.0.1:8000/mcp/&quot;)<br><br><br>client = MCPClient(create_transport)<br>model = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br><br><br>with client:<br>tools = client.list_tools_sync()<br>agent = Agent(model=model, tools=tools)<br>print(agent(&quot;add 2 and 3 subtract from 100&quot;))</pre><p>📖 <strong>Real-World Demo: Kite MCP + Streamlit</strong></p><p>We integrated <strong>Kite MCP</strong> with a <strong>Streamlit UI</strong> for portfolio Q&amp;A. Enter your OpenAI API key, log in to Kite, and query holdings.</p><p>Run:</p><pre>streamlit run kite_streamlit_app/streamlit_app.py</pre><p>📸 Example UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67czk-dvztDEjKMC4fHLVg.png" /><figcaption>UI for kite-MCP</figcaption></figure><h3>🔑 Key Takeaways</h3><ul><li>MCP <strong>decouples agents from tools</strong> → scalable, modular design.</li><li>Pre-built MCP servers save time (Docs, Pricing, DynamoDB).</li><li>Multi-server orchestration enables complex workflows.</li><li>Custom MCP servers let enterprises safely expose internal APIs.</li><li>Streamlit makes agent interactions user-friendly.</li></ul><h3>📂 GitHub Repo</h3><p>👉 <a href="https://github.com/manish6007/ai-agents-with-mcp">AI-Agents-with-MCP</a></p><p>Star ⭐ the repo, try the examples, and adapt them for your use case!</p><h3>✍️ Author</h3><p><strong><em>Manish Shrivastava</em></strong><br>Follow me for more posts on <strong>AI Agents, Bedrock, MCP, and Applied GenAI</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42aa562af2d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Ten PhD Theses in 20 Minutes: My Experiment with GPT-5]]></title>
            <link>https://medium.com/@manishshrivastava26/from-zero-to-ten-phd-theses-in-20-minutes-my-experiment-with-gpt-5-d86551809215?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86551809215</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 07:53:28 GMT</pubDate>
            <atom:updated>2025-08-16T07:53:28.419Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>The Day I Decided to Push AI to Its Limits</strong></h4><p>A few days ago, I sat at my desk with a curious question:</p><p><em>Could AI create something as rigorous as a PhD thesis — not a blog post, not a summary, but a full academic-style analysis — on the world’s most successful business minds?</em></p><p>The answer, it turned out, was yes. And it happened in <strong>under 20 minutes</strong>.</p><p>What made the difference wasn’t “better prompting.” It was something called <strong>Meta prompting</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdoDdQg87x62ymUHb4jy6w.png" /></figure><h3>What on Earth Is Meta Prompting?</h3><p>If normal prompting is asking a chef to cook dinner…<br> Metaprompting is asking the chef to first <strong>design the perfect recipe</strong> — and <em>then</em> cook it.</p><p>It’s a two-step dance:</p><ol><li><strong>Step 1 (Meta prompt):</strong> Ask the AI to write the <em>best possible prompt</em> for your goal.</li><li><strong>Step 2 (Execution):</strong> Run that “mega prompt” to generate the actual output.</li></ol><blockquote>“Don’t ask AI for the meal. Ask it for the recipe first.”</blockquote><p>Here’s the <strong>meta prompt</strong> I used 👇</p><pre>You are a prompt engineer.  <br>You write tailored, detailed and concise prompts.  <br>Create the most effective prompt to analyze 10 successful business owners, their decision-making frameworks, resilience strategies, and lessons that can be compared across industries in an academic style.  <br>The output should resemble a PhD thesis.  <br>Format: Output in codeblock  <br>Instructions: Use markdown</pre><h3>The Mega Prompt: The “Recipe”</h3><p>What came back wasn’t the thesis.<br> It was something better: a <strong>research-advisor-level prompt</strong> that looked like a doctoral supervisor had written it.</p><p>Here’s a condensed version:</p><pre>You are a world-class research advisor in organizational psychology, business strategy, and academic writing.  <br>Task: Analyze and synthesize the success of 10 highly successful business owners.  <br><br>Guidelines:  <br>1. Structure like a PhD thesis (abstract, intro, lit review, methodology, analysis, discussion, conclusion).  <br>2. Examine decision-making frameworks (rational, intuitive, data-driven, hybrid).  <br>3. Identify resilience strategies (adaptability, crisis management, psychological resilience, financial risk).  <br>4. Compare lessons across industries.  <br>5. Include strengths, weaknesses, limitations.  <br>6. Derive overarching theories future entrepreneurs can adopt.  <br>7. Maintain academic rigor, reference parallels to existing theories.  <br><br>Output:  <br>- PhD-style thesis  <br>- Comparative analysis table  <br>- Theoretical contributions &amp; practical implications</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d87OW_sK7TCJK_zmUWIPQQ.png" /></figure><h3>The Results</h3><p>When I fed this mega prompt into GPT-5 <strong>agent mode</strong>, something magical happened:</p><ul><li>It generated <strong>ten full theses</strong>, each 20–50 pages long.</li><li>Every thesis was structured with <strong>abstracts, methodologies, discussions, and conclusions</strong>.</li><li>Instead of just biographies, they unpacked frameworks, resilience strategies, and <strong>cross-industry insights</strong>.</li></ul><p>For example:</p><ul><li><a href="https://chatgpt.com/s/68a0215598648191ae74e906ea94b9d4">Alex Hormozi Thesis</a></li><li><a href="https://chatgpt.com/s/68a021824924819197818e9504cbacea">Tony Robbins Thesis</a></li><li><a href="https://chatgpt.com/s/68a021a0daa08191aacef83f40b5e7ed">Jim Rohn Thesis</a></li></ul><p>Reading them felt like browsing a university research archive, not an AI output.</p><h3>Why This Blew My Mind</h3><ol><li><strong>Speed</strong> — Work that might take months of research was compressed into minutes.</li><li><strong>Rigor</strong> — The AI didn’t just describe — it analyzed, critiqued, and synthesized.</li><li><strong>Scalability</strong> — The same method can be applied to finance, medicine, education… anything.</li></ol><blockquote>“The real power isn’t in what AI answers — it’s in teaching AI how to ask itself better questions.”</blockquote><h3>Lessons You Can Apply Today</h3><ul><li><strong>Think in meta layers.</strong> Don’t stop at “write me X.” Ask: “What’s the best way to prompt for X?”</li><li><strong>Leverage structure.</strong> Academic frameworks (intro → lit review → analysis → conclusion) help AI think clearly.</li><li><strong>Combine with agents.</strong> Agent mode breaks big goals into steps, like a researcher following a thesis outline.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*xu2Q76rLNzzw___r3n1QDw.png" /></figure><h3>What This Means for the Future</h3><p>This little late-night experiment gave me a glimpse into something bigger:</p><ul><li><strong>AI isn’t just for getting answers — it can design the questions.</strong></li><li><strong>Metaprompting unlocks a second layer of intelligence</strong> — AI as a <em>prompt engineer</em> before being a <em>researcher</em>.</li><li>With <strong>Agent Mode</strong>, AI doesn’t just write — it <strong>thinks, structures, and synthesizes</strong> knowledge like a scholar.</li></ul><p>The shift here is subtle but huge: <em>the quality of what you get depends not just on the AI model, but on the quality of the prompt you let it design for itself.</em></p><h3>Final Reflection</h3><p>This wasn’t just about AI writing reports.<br> It was about glimpsing a new way of working with knowledge itself.</p><p>Metaprompting + agent mode showed me that <strong>AI isn’t replacing curiosity — it’s amplifying it</strong>.</p><p>In the time it took to drink my coffee, I had ten PhD-style theses that could inspire entrepreneurs, scholars, and curious minds alike.</p><p>🔥 <em>If you’ve ever felt stuck with AI spitting shallow answers, try metaprompting. You might just get something that feels like it belongs in a dissertation defense.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRCqJWf0n6NEcFYmlEGUuQ.png" /></figure><p>👉 If you found this experiment useful, follow along — I’ll be sharing more real-world applications of <strong>AI, finance, and productivity</strong> that show how curiosity + the right techniques can change the game.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86551809215" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text-to-Speech Converter using Tkinter and gTTS]]></title>
            <link>https://medium.com/@manishshrivastava26/text-to-speech-converter-using-tkinter-and-gtts-dc33728abbb?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc33728abbb</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 14:43:27 GMT</pubDate>
            <atom:updated>2023-07-24T14:43:27.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*69H_As90rw0fqEDbnYIm9g.gif" /></figure><p>In this article, we will explain the code for a simple Text-to-Speech Converter using Tkinter and the Google Text-to-Speech (gTTS) library. This Python application allows users to select a text file, convert its contents to speech in the Hindi language, and save it as an MP3 file. We’ll go through the code step by step and discuss each part’s purpose and functionality.</p><h3>Introduction</h3><p>The code utilizes the Tkinter library to create a graphical user interface (GUI) for the application. Tkinter provides a simple way to build windows, dialogs, buttons, and other GUI elements. The gTTS library is used to convert the text into speech in the Hindi language.</p><h3>The Code Explanation</h3><h4>Importing Libraries</h4><pre>import tkinter as tk<br>from tkinter import filedialog<br>from gtts import gTTS<br>import time</pre><p>In the first part of the code, we import the required libraries:</p><ul><li>tkinter: The main library for creating the GUI.</li><li>filedialog: A module from tkinter to handle file dialog windows for file selection and saving.</li><li>gtts.gTTS: The gTTS class from the gtts library, which is used for text-to-speech conversion.</li><li>time: The built-in time module for time-related operations.</li></ul><h4>Global Variables</h4><pre>conversion_in_progress = False<br>start_time = 0</pre><p>Two global variables are defined:</p><ul><li>conversion_in_progress: A boolean flag to keep track of whether the conversion process is currently running or not.</li><li>start_time: A timestamp variable to keep track of the start time when the conversion begins.</li></ul><h4>Reading File into Variable</h4><pre>def read_file_into_variable(file_path):<br>    # Code to read the contents of a file and return them as a string</pre><p>The read_file_into_variable function is used to read the contents of a given text file and return them as a string. It takes the file_path as an argument and attempts to read the file using the open function in read mode (&#39;r&#39;) with UTF-8 encoding. If the file is found and read successfully, its contents are returned. If there is any issue (e.g., file not found or an error occurred during reading), an appropriate message is printed, and None is returned.</p><h4>Text-to-Speech in Hindi</h4><pre>def text_to_speech_hindi(input_text, output_file):<br>    # Code to convert the input_text to speech in Hindi and save it to the output_file</pre><p>The text_to_speech_hindi function is responsible for converting the input text to speech in the Hindi language and saving it to an MP3 file. It takes two arguments: input_text (the text to be converted) and output_file (the name of the MP3 file where the speech will be saved).</p><p>Inside the function, the Hindi language is specified, and a gTTS object is created with the input text and the specified language. The gTTS object converts the text to speech.</p><p>The start_time global variable is used to store the current time when the conversion starts. The speech is then saved to the specified output file using the save method of the gTTS object.</p><p>After the conversion, the elapsed time is calculated and returned along with a boolean value indicating whether the conversion was successful or not.</p><h4>Selecting a File</h4><pre>def select_file():<br>    # Code to open a file dialog to select a text file and update the input_text_entry widget</pre><p>The select_file function is triggered when the &quot;Select Text File&quot; button is clicked. It opens a file dialog window that allows the user to select a text file with the extension &quot;.txt&quot;. If a file is selected, the file&#39;s contents are read into a variable using the read_file_into_variable function.</p><p>If the file is successfully read, the contents are displayed in the input_text_entry widget (a text box) where users can view and edit the text. The name of the selected file is also displayed in the status_label widget.</p><h4>Converting Text to MP3</h4><pre>def convert_to_mp3_button_clicked():<br>    # Code to trigger text-to-speech conversion and save the speech as an MP3 file</pre><p>The convert_to_mp3_button_clicked function is executed when the &quot;Convert to MP3&quot; button is clicked. It converts the text in the input_text_entry widget to speech and saves it as an MP3 file.</p><p>If the conversion process is not already in progress, the input text is extracted from the input_text_entry widget. If there is some text to convert, a file dialog window is opened to ask the user to specify the location and name of the output MP3 file. If the user provides a valid output file name, the conversion process starts.</p><p>During the conversion, the conversion_in_progress flag is set to True to prevent starting a new conversion while one is already ongoing. If the conversion is successful, the status_label widget is updated to display the name of the saved MP3 file, and the update_counter function is called to continuously update the time taken for the conversion.</p><h4>Updating Conversion Time</h4><pre>def update_counter(seconds):<br>    # Code to continuously update the counter_label with the elapsed seconds</pre><p>The update_counter function is called during the conversion process to continuously update the counter_label widget with the elapsed time. It takes the seconds elapsed since the conversion started as an argument and updates the label to display the time taken for the conversion.</p><p>The after method is used to schedule the function to be called again after a delay of 1000 milliseconds (1 second). This creates a loop that keeps updating the time label while the conversion is in progress.</p><h3>Creating the Tkinter GUI</h3><p>The code then proceeds to create the main Tkinter window and various GUI elements, including buttons, text entry widgets, and labels. The GUI elements are packed in the window using the pack method, and their functionality is associated with the respective functions defined earlier.</p><p>Finally, the Tkinter main loop is started using app.mainloop(), which keeps the application running and responsive to user interactions.</p><h3>Conclusion</h3><p>In this article, we explored a Python application that converts text to speech in the Hindi language using the gTTS library and a simple Tkinter-based GUI. Users can select a text file, view its content, convert the text to speech, and save it as an MP3 file. The application provides user-friendly file dialogs and status updates during the conversion process, making it easy for users to interact with and utilize the functionality.</p><p>The complete code for this application can be found on GitHub at the following link: <a href="https://github.com/manish6007/python_applications/tree/master">Text-to-Speech Hindi Converter GitHub Repository</a>.</p><p>If you wish to use this code, make sure you have installed the required libraries, Tkinter, and gTTS, to run the application successfully.</p><h3>Reference:</h3><ol><li>Tkinter module: Official Python documentation for Tkinter. <a href="https://docs.python.org/3/library/tkinter.html">Link</a></li><li>filedialog module: Official Python documentation for the filedialog module in Tkinter. <a href="https://docs.python.org/3/library/dialog.html">Link</a></li><li>gtts module: Official documentation for the Google Text-to-Speech (gTTS) library. <a href="https://cloud.google.com/text-to-speech/docs/libraries">Link</a></li><li>time module: Official Python documentation for the time module. <a href="https://docs.python.org/3/library/time.html">Link</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc33728abbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Dimensional Data with Delta Lake: Implementing SCD2 on Databricks]]></title>
            <link>https://medium.com/@manishshrivastava26/mastering-dimensional-data-with-delta-lake-implementing-scd2-on-databricks-4d56a6f636b5?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d56a6f636b5</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 11:57:48 GMT</pubDate>
            <atom:updated>2023-04-15T11:57:48.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*fjCZrDCgDk0llEHNn32E7w.png" /></figure><p><strong>Introduction to Slowly Changing Dimensions</strong></p><p>Slowly Changing Dimensions (SCDs) are a concept used in data warehousing to maintain historical data over time, while tracking changes in data. SCDs are important for analysis and reporting purposes, and there are different types of SCDs to choose from depending on the specific requirements of the data warehouse. By utilizing SCDs, organizations can gain valuable insights into their data and make informed decisions based on its historical context. For a comprehensive explanation on Slowly Changing Dimensions (SCDs), please refer to this <a href="https://medium.com/@manishshrivastava26/slowly-changing-dimensions-maintaining-historical-data-in-data-warehousing-2533269210fc">resource</a>.</p><h3><strong>Advantages of Using Delta Lake on Databricks for SCD2 Implementation</strong></h3><ol><li>ACID Transactions: Delta Lake on Databricks provides full support for ACID transactions, which means that data changes are atomic, consistent, isolated, and durable. This guarantees that SCD2 updates are executed in a way that preserves the integrity and consistency of the data.</li><li>Optimized Performance: Delta Lake on Databricks is optimized for performance, allowing for fast read and write operations. This means that even as the size of your data grows over time, your SCD2 updates can be executed quickly and efficiently.</li><li>Schema Enforcement: Delta Lake on Databricks provides built-in schema enforcement, which ensures that SCD2 updates adhere to the schema defined for the data. This helps to prevent errors and inconsistencies that can arise from data type mismatches or missing fields.</li><li>Time Travel: Delta Lake on Databricks provides time travel capabilities, allowing you to access the full history of changes to your SCD2 data. This means that you can easily view and audit changes over time, or even revert to a previous version of the data if necessary. Time travel also enables the creation of data-driven reports and dashboards that can provide insights into trends and patterns over time.</li></ol><h3>SCD2 Implementation on databricks using deltalake</h3><p><strong>Creating customer_history target table:</strong></p><ul><li>cust_id: An integer representing the unique identifier of the customer.</li><li>first_name: A string representing the first name of the customer.</li><li>last_name: A string representing the last name of the customer.</li><li>state: A string representing the state where the customer resides.</li><li>city: A string representing the city where the customer resides.</li><li>address: A string representing the address of the customer.</li><li>eff_start_date: A timestamp representing the effective start date for the record.</li><li>eff_end_date: A timestamp representing the effective end date for the record.</li><li>is_active: A string indicating whether the customer is currently active or not.</li></ul><p>These columns define the structure and attributes of the customer_history table, which is stored in Delta Lake format at the location specified in the LOCATION clause.</p><pre>spark.sql(&quot;&quot;&quot;<br>CREATE OR REpLACE TABLE customer_history (<br>  cust_id INTEGER,<br>  first_name STRING,<br>  last_name STRING,<br>  state STRING,<br>  city STRING,<br>  address STRING,<br>  eff_start_date TIMESTAMP,<br>  eff_end_date TIMESTAMP,<br>  is_active string<br>)<br>USING DELTA<br>LOCATION &#39;/FileStore/tables/customer_history/&#39;&quot;&quot;&quot;)</pre><p>This table is empty.</p><p><strong>Initialize the Spark Session:</strong></p><pre>spark = SparkSession.builder \<br>    .appName(&quot;SCD2 for Customer Table with Delta Lake&quot;) \<br>    .getOrCreate()</pre><p><strong>Read Source Data:</strong></p><pre>source_data = spark.read.csv(&quot;/FileStore/tables/customer_source_data-1.csv&quot;, header=True,inferSchema=True)<br>source_data.display()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h9qmiNG9ZCKgk51rdWYj4A.jpeg" /></figure><p>In the given code, the source_data variable is used to read the source data from a CSV file stored in source location. It is created using the spark.read.csv() method which takes the path of the CSV file as input and returns a DataFrame containing the data. The CSV file is assumed to have a header row which is used to infer the schema of the data. This DataFrame is then used to determine which records need to be inserted, updated or deleted in the target Delta Lake table.</p><p><strong>Read the target data (Delta Lake table):</strong></p><pre>target_data_path = &quot;/FileStore/tables/customer_history/&quot;<br>target_delta_table = DeltaTable.forPath(spark, target_data_path)</pre><p>In the above code, target_delta_table is a variable that represents the Delta table where the target data is stored. It is created using the DeltaTable.forPath() method, which takes the SparkSession object and the path to the Delta table as parameters.</p><p><strong>Define high_date and is_active flag:</strong></p><pre>high_date = &quot;9999-12-31&quot;<br>is_active = &quot;Y&quot;</pre><p>In the given code, high_date and is_active are variables used to define the end date and active status for records in the customer table.</p><p>high_date is used to represent the maximum possible date in the future and is used to indicate the end date for records that are currently active. For records that are closed, the eff_end_date column in the Delta Lake table will be set to the date when the record was closed.</p><p>is_active is used to indicate whether a record is currently active or not.</p><p><strong>Perform a full outer join between the source and target data on the ‘cust_id’ column:</strong></p><pre>source_data_alias = source_data.alias(&quot;src&quot;)<br>target_delta_table_alias = target_delta_table.toDF().alias(&quot;tgt&quot;)<br><br>joined_data = source_data_alias \<br>    .join(target_delta_table_alias, col(&quot;src.cust_id&quot;) == col(&quot;tgt.cust_id&quot;), &quot;full_outer&quot;) \<br>    .select(&quot;src.*&quot;, <br>            *[col(&quot;tgt.&quot; + c).alias(&quot;tgt_&quot; + c) for c in target_delta_table_alias.columns])</pre><p>A full outer join is here to ensure that all rows from both the source and target data are included in the resulting joined data set. This is important because we need to identify rows in the target table that need to be updated or deleted, as well as rows in the source table that need to be inserted. A full outer join ensures that we do not miss any rows that may exist in one table but not the other. Additionally, since the SCD2 implementation requires comparing values from both the source and target data, a full outer join helps us compare all the rows and determine which ones have changed.</p><p><strong>Determine rows to insert and update:</strong></p><pre>insert_data = joined_data.filter(col(&quot;tgt_cust_id&quot;).isNull())\<br>              .withColumn(&quot;eff_start_date&quot;,current_date())\<br>              .withColumn(&quot;eff_end_date&quot;,lit(high_date))\<br>              .withColumn(&quot;is_active&quot;,lit(&quot;Y&quot;))</pre><p>insert_data is a DataFrame variable created by filtering the joined_data DataFrame to select only the rows that have a null value for the tgt_cust_id column. These are the rows that are in the source data but not in the target data. The insert_data DataFrame is then used to insert new records into the target Delta Lake table. Additionally, eff_start_date, eff_end_date, and is_active columns are added to insert_data using the withColumn method before merging it with the target Delta Lake table.</p><pre>update_data = joined_data.filter(<br>    col(&quot;src.cust_id&quot;).isNotNull() &amp; col(&quot;tgt_cust_id&quot;).isNotNull() &amp;<br>    (<br>        (col(&quot;src.first_name&quot;) != col(&quot;tgt_first_name&quot;)) |<br>        (col(&quot;src.last_name&quot;) != col(&quot;tgt_last_name&quot;)) |<br>        (col(&quot;src.state&quot;) != col(&quot;tgt_state&quot;)) |<br>        (col(&quot;src.city&quot;) != col(&quot;tgt_city&quot;)) |<br>        (col(&quot;src.address&quot;) != col(&quot;tgt_address&quot;))<br>    )<br>)</pre><p>The update_data variable in the given code represents the records from the joined data where the cust_id is present in both the source and target tables, and where there is at least one attribute that has changed. This is determined by checking if any of the following attributes in the source data are different from their corresponding attributes in the target data: first_name, last_name, state, city, and address.</p><p>The purpose of this variable is to identify the records that need to be updated in the Delta Lake table. The subsequent operations performed on this data, such as closing old records and inserting new records with updated values, ensure that the table is updated with the latest information.</p><p><strong>Apply the changes to the target Delta Lake table:</strong></p><pre>if insert_data.count() &gt; 0:<br>    target_delta_table.alias(&quot;tgt&quot;) \<br>        .merge(insert_data.alias(&quot;src&quot;), &quot;tgt.cust_id = src.cust_id&quot;) \<br>        .whenNotMatchedInsertAll() \<br>        .execute()</pre><p>This statement checks if there are any records to be inserted, and if so, it uses the merge() function to merge the insert data with the target Delta Lake table. This is done using a merge condition and specifying whenNotMatchedInsertAll(), which inserts all the records from the source that don&#39;t match the merge condition.</p><pre>if update_data.count() &gt; 0:<br>    # Close old records by setting eff_end_date and is_active<br>    target_delta_table.alias(&quot;tgt&quot;) \<br>        .merge(update_data.alias(&quot;src&quot;), &quot;tgt.cust_id = src.cust_id&quot;) \<br>        .whenMatchedUpdate(<br>            condition=&quot;tgt.is_active = &#39;Y&#39;&quot;,<br>            set={<br>                &quot;eff_end_date&quot;: lit(current_date()),<br>                &quot;tgt.is_active&quot;: lit(&quot;N&quot;)<br>            }<br>        ) \<br>        .execute()</pre><p>This statement checks if there are any records to be updated. If so, it first updates the old records by setting the end date and is_active flag. Then, it inserts the new records with updated values, with eff_start_date set as current date, eff_end_date set as high_date, and is_active flag set to ‘Y’. Finally, it saves the updated Delta Lake table using the write() function with the overwrite mode and overwriteSchema option.</p><pre>new_records = update_data.select(<br>        col(&quot;src.cust_id&quot;),<br>        col(&quot;src.first_name&quot;),<br>        col(&quot;src.last_name&quot;),<br>        col(&quot;src.state&quot;),<br>        col(&quot;src.city&quot;),<br>        col(&quot;src.address&quot;),<br>        current_date().alias(&quot;eff_start_date&quot;),<br>        lit(high_date).alias(&quot;eff_end_date&quot;),<br>        lit(is_active).alias(&quot;is_active&quot;)<br>    )</pre><p>the new_records variable is created to hold the new records to be inserted into the Delta table as part of the SCD2 process. It is created using the update_data DataFrame, which contains the rows that need to be updated in the Delta table. The select() function is used to select the columns from the update_data DataFrame that need to be inserted as new records.</p><p>The alias() and lit() functions are used to create column aliases and literal values, respectively, for the new records. The current_date() and high_date variables are used to set the effective start and end dates for the new records.</p><pre>target_delta_table \<br>        .toDF() \<br>        .union(new_records) \<br>        .write \<br>        .format(&quot;delta&quot;) \<br>        .mode(&quot;overwrite&quot;) \<br>        .option(&quot;overwriteSchema&quot;, &quot;true&quot;) \<br>        .save(target_data_path)</pre><p>The new_records DataFrame is unioned with the existing Delta Lake table data and written to the Delta Lake table location using the write() method of the DataFrameWriter object. The mode() method is set to “overwrite” to replace the existing data, and the option() method is set to “overwriteSchema” to overwrite the schema of the table if it already exists.</p><p><em>The notebook and sample data files can be accessed from </em><a href="https://github.com/manish6007/Pyspark"><em>github location</em></a><em> under SCD2 folder.</em></p><h3><strong>Visualizing SCD2 Changes in Delta Lake on Databricks:</strong></h3><p>State of customer_history table after load:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Skc_PuEqcpwi8V6rSZXJBw.jpeg" /></figure><p>Let’s load new file customer_source_data-2.csv which has a new record along with an updated one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hEry6NruOz0p3wZ1-hGPA.jpeg" /><figcaption>Source data with updated, new and unchanged record</figcaption></figure><p>After executing the code above the final state of customer_history table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cf9ROgwoxIna7kGOKcWxqw.jpeg" /></figure><p>A new version of the record with cust_id 1002 has been created as the state has been changed from California to Mexico. The previous version of that record is now marked as &quot;N&quot; with eff_end_date set to the current date. Additionally, a new record has been created for cust_id 1004 with is_active set to &quot;Y&quot; and eff_end_date set to &quot;9999–12–31&quot;.</p><h3><strong>Best Practices for Implementing SCD2 Using Delta Lake on Databricks:</strong></h3><p>Slowly Changing Dimensions (SCD) are a fundamental part of data warehousing, which require efficient implementation techniques to handle historical and current data. Delta Lake on Databricks provides a robust platform for SCD2 implementation with several features to ensure high performance, scalability, and reliability. Here are some best practices for implementing SCD2 using Delta Lake on Databricks:</p><ol><li>Use Delta Lake’s Time Travel feature for historical data querying and auditing.</li><li>Use Delta Lake’s Merge operation for handling inserts, updates, and deletes.</li><li>Use Delta Lake’s partitioning feature to improve query performance and reduce data skew.</li><li>Define appropriate schema and data types to ensure efficient storage and processing.</li><li>Use Databricks Delta Lake’s automatic file management feature to improve query performance and reduce storage costs.</li><li>Implement an efficient SCD2 update strategy to handle high volumes of data efficiently.</li></ol><p>By following these best practices, one can efficiently implement SCD2 using Delta Lake on Databricks and leverage its benefits to achieve high performance, scalability, and reliability.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, mastering dimensional data with Delta Lake is crucial for businesses that require fast and reliable access to their data. Implementing SCD2 on Databricks with Delta Lake is a powerful way to ensure that the data is accurate and up-to-date, which is critical for making informed decisions. By following best practices and leveraging the capabilities of Delta Lake, organizations can build a robust and scalable data pipeline that can keep up with the changing needs of the business.</p><h3>References</h3><ol><li>Delta Lake Documentation: <a href="https://docs.delta.io/latest/index.html">https://docs.delta.io/latest/index.html</a></li><li>Databricks Documentation: <a href="https://docs.databricks.com/index.html">https://docs.databricks.com/index.html</a></li><li>Kimball Group: <a href="https://www.kimballgroup.com/">https://www.kimballgroup.com/</a></li><li>“Slowly Changing Dimensions in Data Warehousing” by Ralph Kimball: <a href="https://www.kimballgroup.com/1998/12/slowly-changing-dimensions/">https://www.kimballgroup.com/1998/12/slowly-changing-dimensions/</a></li><li>“The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling” by Ralph Kimball and Margy Ross: <a href="https://www.amazon.com/Data-Warehouse-Toolkit-Definitive-Dimensional/dp/1118530802/">https://www.amazon.com/Data-Warehouse-Toolkit-Definitive-Dimensional/dp/1118530802/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d56a6f636b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slowly Changing Dimensions: Maintaining Historical Data in Data Warehousing]]></title>
            <link>https://medium.com/@manishshrivastava26/slowly-changing-dimensions-maintaining-historical-data-in-data-warehousing-2533269210fc?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2533269210fc</guid>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 10:06:57 GMT</pubDate>
            <atom:updated>2023-04-15T10:06:57.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*JmGfX9wjkxXL_-j8Az9zpg.png" /></figure><p><strong>Introduction</strong></p><p>Slowly Changing Dimension(SCD) is a concept used in data warehousing to track changes in data over time. SCDs are used to maintain historical data and are important for analysis and reporting purposes.</p><p><strong>Types of Slowly Changing Dimensions:</strong></p><p><strong>Type 1 SCD:</strong> In a Type 1 SCD, the old data is simply overwritten with new data. This means that historical data is not maintained, and any analysis done on the data will only reflect the current state. This method is useful when historical data is not important. For example, if you are tracking the current address of a customer, you may use a Type 1 SCD, as the old address is no longer relevant once it has been updated.</p><p><strong>Example:</strong></p><p>Let’s say you have a customer dimension table that includes the customer name, address, and phone number. If a customer changes their phone number, you may choose to simply overwrite the existing phone number with the new one. This means that the old phone number is lost, and any analysis done on the data will only reflect the current state.</p><p><strong>Type 2 SCD: </strong>In a Type 2 SCD, a new record is added to the table to reflect the changes in the data, while the old record is kept in the table with a new key or version number. This method is useful when you want to maintain a history of changes over time. For example, if you are tracking the salary changes of employees, you would use a Type 2 SCD to maintain the historical record of salaries for each employee.</p><p><strong>Example:</strong></p><p>Continuing with the customer dimension table example, if a customer moves to a new address, you may want to create a new record in the customer dimension table to reflect the change, while keeping the old record with the original address. This allows you to maintain a historical record of changes over time.</p><p><strong>Type 3 SCD: </strong>In a Type 3 SCD, only the most recent changes are stored in the table, with previous changes being overwritten. This method is useful when you want to track changes, but historical data is not important. For example, if you are tracking the marital status of a customer, you may use a Type 3 SCD, as only the most recent marital status is relevant.</p><p><strong>Example:</strong></p><p>For this example, let’s say you have a product dimension table that includes the product name, price, and discount percentage. If the discount percentage changes frequently and you are only interested in the most recent discount, you may choose to create an additional column in the product dimension table to store the most recent discount percentage. This means that historical data is not important, as you are only interested in the current state of the data.</p><p><strong>Conclusion:</strong></p><p>Slowly Changing Dimensions (SCDs) are a vital concept in data warehousing that enable the maintenance of historical data over time. By understanding the different types of SCDs and their applications, organizations can effectively track changes in data, while preserving its historical context. Whether it’s Type 1, Type 2, or Type 3 SCDs, choosing the right approach depends on the specific requirements of the data warehouse and the type of data being tracked. By utilizing SCDs, organizations can gain valuable insights into their data, and make informed decisions based on its historical context.</p><p><strong>References:</strong></p><ol><li>Kimball, R., Ross, M., &amp; Thornthwaite, W. (2011). The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling (3rd ed.). Wiley.</li><li>Inmon, W. H., &amp; Hackathorn, R. D. (1994). Using the data warehouse. John Wiley &amp; Sons.</li><li>Slowly Changing Dimensions (SCD) — A Comprehensive Guide. (2021, January 11). Data Science Central. <a href="https://www.datasciencecentral.com/profiles/blogs/slowly-changing-dimensions-scd-a-comprehensive-guide">https://www.datasciencecentral.com/profiles/blogs/slowly-changing-dimensions-scd-a-comprehensive-guide</a></li><li>Slowly Changing Dimensions. (n.d.). Oracle. <a href="https://docs.oracle.com/cd/B28359_01/server.111/b28298/dwh_concepts002.htm">https://docs.oracle.com/cd/B28359_01/server.111/b28298/dwh_concepts002.htm</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2533269210fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Mastering Common Table Expressions (CTEs) in SQL: Examples and Applications”]]></title>
            <link>https://medium.com/@manishshrivastava26/mastering-common-table-expressions-ctes-in-sql-examples-and-applications-a29a3a560574?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a29a3a560574</guid>
            <category><![CDATA[cte]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 18:14:36 GMT</pubDate>
            <atom:updated>2023-03-16T18:14:36.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*yzu_ebYHhiITYuAau2HGew.png" /></figure><h3><strong>Introduction:</strong></h3><p>CTE, or Common Table Expressions, is a powerful tool in SQL that allows you to define temporary result sets that can be referenced within a single query. CTEs are useful for simplifying complex queries, breaking down large queries into smaller, more manageable pieces, and improving query performance.</p><p>In this article, we’ll take a closer look at what CTEs are and how they work, along with several examples of how they can be used.</p><p><strong>What is a CTE?</strong></p><p>A CTE, or Common Table Expression, is a temporary named result set that you can reference within a single SQL statement. CTEs are created using the WITH clause, which defines the CTE name, followed by the SELECT statement that generates the result set.</p><p>CTEs are often used as a way to simplify complex SQL queries, making it easier to read and understand the code. They can also be used to improve query performance by breaking a large query into smaller, more manageable pieces.</p><p>The syntax for creating a CTE is as follows:</p><pre>WITH cte_name AS (<br>   SELECT column1, column2, ...<br>   FROM table_name<br>   WHERE condition<br>)<br>SELECT column1, column2, ...<br>FROM cte_name<br>WHERE condition;</pre><p>In the example above, the CTE named cte_name is created using a SELECT statement that generates the result set. The CTE can then be referenced in the main SELECT statement using the CTE name.</p><h3><strong>Examples of CTEs:</strong></h3><p>Let’s take a look at several examples of how CTEs can be used.</p><p><strong>Example 1: Simple CTE</strong></p><p>In this example, we’ll create a simple CTE that retrieves data from a table and then references the CTE in a SELECT statement:</p><pre>WITH cte_sales AS (<br>   SELECT product_name, SUM(quantity) as total_quantity<br>   FROM sales<br>   GROUP BY product_name<br>)<br>SELECT product_name, total_quantity<br>FROM cte_sales<br>WHERE total_quantity &gt; 1000;</pre><p>In this example, we’re creating a CTE named cte_sales that retrieves data from the sales table and calculates the total quantity of each product sold. We’re then referencing the CTE in a SELECT statement that retrieves only the product names and total quantities where the total quantity is greater than 1000.</p><p><strong>Example 2: Recursive CTE</strong></p><p>Recursive CTEs are a powerful tool in SQL that allow you to perform recursive operations on data. In this example, we’ll create a recursive CTE that calculates the factorial of a given number:</p><pre>WITH RECURSIVE cte_factorial(n, result) AS (<br>   SELECT 1, 1<br>   UNION ALL<br>   SELECT n + 1, (n + 1) * result<br>   FROM cte_factorial<br>   WHERE n &lt; 10<br>)<br>SELECT *<br>FROM cte_factorial;</pre><p>In this example, we’re creating a recursive CTE named cte_factorial that calculates the factorial of a number up to 10. The CTE starts with an initial value of n=1 and result=1 and then performs a recursive operation to calculate the factorial of the next number. The WHERE clause limits the recursion to stop at n=10.</p><p><strong>Example 3: Multiple CTEs</strong></p><p>In this example, we’ll create multiple CTEs that are then referenced in a single SELECT statement:</p><pre>WITH cte_sales AS (<br>   SELECT product_name, SUM(quantity) as total_quantity<br>   FROM sales<br>   GROUP BY product_name<br>),<br>cte_products AS (<br>   SELECT product_name, category, price<br>   FROM products<br>)<br>SELECT s.product_name, s.total_quantity, p.category, p.price<br>FROM cte_sales s<br>JOIN cte_products p ON s.product_name = p.product_name<br>WHERE p.category = &#39;Electronics&#39;;</pre><p>In this example, we’re creating two CTEs — `cte_sales` and `cte_products` — that retrieve data from the `sales` and `products` tables, respectively. We’re then referencing both CTEs in a single SELECT statement that joins the two result sets on the `product_name` column and retrieves only the products that belong to the ‘Electronics’ category.</p><p><strong>Example 4: CTEs with Window Functions</strong></p><p>CTEs can also be used with window functions to perform complex calculations on a result set.</p><p>Suppose we have a table called “sales” that contains the sales data of a company. The table has columns “year”, “quarter”, “month”, “product”, and “sales_amount”. We want to calculate the total sales amount for each product for each quarter, as well as the running total of sales amount for each product across all quarters.</p><p>We can use a CTE with a window function to achieve this. Here’s the SQL query:</p><pre>WITH quarterly_sales AS (<br>  SELECT<br>    year,<br>    quarter,<br>    product,<br>    SUM(sales_amount) AS quarterly_sales_amount,<br>    SUM(SUM(sales_amount)) OVER (PARTITION BY product ORDER BY year, quarter) AS cumulative_sales_amount<br>  FROM<br>    sales<br>  GROUP BY<br>    year,<br>    quarter,<br>    product<br>)<br>SELECT *<br>FROM quarterly_sales<br>ORDER BY product, year, quarter;</pre><p>In this query, we first define a CTE called “quarterly_sales” that aggregates the sales data by year, quarter, and product to calculate the total sales amount for each product for each quarter. We also use the window function SUM(SUM(sales_amount)) OVER (PARTITION BY product ORDER BY year, quarter) to calculate the cumulative sales amount for each product across all quarters. This window function partitions the data by product and orders it by year and quarter, and then calculates the running total of sales amount for each product.</p><p>After defining the CTE, we select all columns from it and order the results by product, year, and quarter. This gives us the total sales amount and cumulative sales amount for each product for each quarter, as well as the running total of sales amount for each product across all quarters.</p><h3>Conclusion:</h3><p>Common Table Expressions (CTEs) are a valuable tool for SQL developers, enabling them to create temporary, named result sets that can be used in subsequent queries. CTEs can simplify complex queries, make queries easier to read and understand, and help optimize query performance. With the examples provided in this article, we hope to have given you a better understanding of how CTEs work and how they can be used in a variety of scenarios. By incorporating CTEs into your SQL queries, you can write more efficient and effective code and take your database skills to the next level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a29a3a560574" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Skew Problem and different ways to resolve it in Pyspark]]></title>
            <link>https://medium.com/@manishshrivastava26/data-skew-problem-and-different-ways-to-resolve-it-in-pyspark-bfb3a9183af?source=rss-25c37688b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb3a9183af</guid>
            <category><![CDATA[salting]]></category>
            <category><![CDATA[data-skew]]></category>
            <category><![CDATA[broadcasting]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Manish Shrivastava]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 17:31:50 GMT</pubDate>
            <atom:updated>2023-03-06T17:31:50.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cftG745eyrzFyKG01uFhA.png" /><figcaption>Data Skew Problem in spark</figcaption></figure><p><strong>Introduction:</strong></p><p>Data skew is a common problem in big data processing, which occurs when the data is unevenly distributed across partitions. This can cause some partitions to be heavily loaded with data, while others have very little data to process. This can lead to a significant increase in processing time and resource usage, and can ultimately result in job failures. In this article, we will discuss the data skew problem in PySpark and various ways to resolve it.</p><p><strong>Data Skew Problem in PySpark:</strong></p><p>PySpark works on the principle of distributed computing, where data is divided into partitions and processed in parallel across a cluster of nodes. In some cases, the data can be unevenly distributed across partitions, which can cause some partitions to process significantly more data than others. This is known as the data skew problem.</p><p><strong>Causes of Data skew problem:</strong></p><p>The data skew problem can occur due to a variety of reasons, such as:</p><p>Skewed Data Distribution: Skewed data distribution can occur when some values appear much more frequently than others in a particular column.</p><p>Join Operations: Join operations can also cause data skew, as the join key values may be unevenly distributed across partitions.</p><p>Poor Partitioning: Poor partitioning of data can also cause data skew, where data is not evenly distributed across partitions.</p><p><strong>Ways to Resolve Data Skew Problem in PySpark:</strong></p><p>Here are some ways to resolve the data skew problem in PySpark:</p><p><strong>Re-Partitioning:</strong> One of the simplest ways to resolve data skew is by repartitioning the data to balance the distribution of data across partitions. PySpark provides a repartition() method that can be used to increase or decrease the number of partitions in a RDD/DataFrame.</p><p>For example, if we have a DataFrame df with 100 partitions and some of them are skewed, we can use the following code to repartition the data into a new DataFrame with 200 partitions:</p><pre>df_repartitioned = df.repartition(200)</pre><p>Repartitioning the data can be a computationally expensive operation, so it is important to choose an appropriate number of partitions that balances the data distribution and minimizes the number of shuffles required.</p><p><strong>Bucketing:</strong> Bucketing is a technique that can be used to group similar data into buckets based on a user-defined criterion. By bucketing the data, we can ensure that similar data is processed together in a partition, reducing the chance of data skew.</p><p>In PySpark, we can use the bucketBy() method to create a bucketed DataFrame. For example, if we have a DataFrame df with a column category, and we want to bucket the data based on the category column into 10 buckets, we can use the following code:</p><pre>df_bucketed = df.bucketBy(10, &quot;category&quot;).sortBy(&quot;category&quot;)</pre><p>Once the data is bucketed, we can use the repartition() method to further balance the data distribution across partitions.</p><p><strong>Salting:</strong> Salting involves adding a random prefix to the join key value to distribute the data more evenly across partitions.<br>Example:</p><pre>from pyspark.sql.functions import rand, concat<br><br>df = df.withColumn(&quot;salt&quot;, rand())<br>df = df.withColumn(&quot;key_with_salt&quot;, concat(&quot;salt&quot;, &quot;key&quot;))<br>df = df.groupBy(&quot;key_with_salt&quot;).agg(sum(&quot;value&quot;))</pre><p>Broadcasting: Broadcasting is a technique that can be used to alleviate data skew by reducing the amount of data that needs to be shuffled across the network. In PySpark, we can use the broadcast() function to broadcast a small DataFrame or variable to all nodes in the cluster, reducing the amount of data that needs to be sent over the network.</p><p>Broadcasting is particularly useful when we have a small DataFrame or variable that is frequently accessed during processing. By broadcasting this data, we can avoid data skew and reduce network traffic.</p><p>Here’s an example of how to use broadcasting to alleviate data skew:</p><pre># Load a large DataFrame<br>df = spark.read.csv(&quot;data.csv&quot;, header=True, inferSchema=True)<br><br># Compute the average value of a column<br>mean_value = df.selectExpr(&quot;avg(col_name)&quot;).collect()[0][0]<br><br># Broadcast the mean value to all nodes in the cluster<br>mean_broadcast = spark.sparkContext.broadcast(mean_value)<br><br># Define a UDF to adjust the column values based on the mean value<br>def adjust_value(value):<br>    if value &gt; mean_broadcast.value:<br>        return value - mean_broadcast.value<br>    else:<br>        return value<br><br># Apply the UDF to the column<br>df_adjusted = df.withColumn(&quot;col_name&quot;, adjust_value(df.col_name))</pre><p>In this example, we load a large DataFrame and compute the mean value of a column. We then broadcast the mean value to all nodes in the cluster using the broadcast() function. Finally, we define a UDF to adjust the column values based on the mean value and apply the UDF to the column.</p><p>By broadcasting the mean value, we avoid data skew and reduce network traffic, as each node can access the mean value locally. This results in faster processing times and better resource utilization.</p><p><strong>Conclusion:</strong></p><p>Data skew is a common problem in distributed computing that can result in slow processing times and resource contention. However, PySpark provides several techniques that can be used to resolve data skew and improve processing efficiency, such as repartitioning, bucketing and broadcasting.</p><p>By understanding the nature of data skew and applying these techniques appropriately, we can optimize our PySpark applications and achieve better resource utilization. As big data continues to grow and become more complex, it is crucial to understand these techniques and use them effectively to ensure efficient and reliable processing of large datasets.</p><p>So, don’t let data skew slow down your PySpark processing! Implement these techniques in your PySpark applications and optimize your big data processing workflows for better performance and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb3a9183af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>