<?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 Sandipan Ghosh on Medium]]></title>
        <description><![CDATA[Stories by Sandipan Ghosh on Medium]]></description>
        <link>https://medium.com/@ghoshm21?source=rss-db159899ba8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gDTmovGM0fzTM4gH9ERV3g.jpeg</url>
            <title>Stories by Sandipan Ghosh on Medium</title>
            <link>https://medium.com/@ghoshm21?source=rss-db159899ba8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:10:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ghoshm21/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[Lauschter: An Offline, Private Audiobook Player]]></title>
            <link>https://ghoshm21.medium.com/lauschter-an-offline-private-audiobook-player-e24d64e942ac?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24d64e942ac</guid>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 16:09:48 GMT</pubDate>
            <atom:updated>2026-11-28T16:09:48.472Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a radio-drama fan with no Android experience shipped an offline player that remembers where you paused every story</em></p><p>I had never built an Android app. Two days later, one was running on my music player, and anyone could download it for free.</p><p>I didn’t learn Kotlin. I didn’t open Android Studio. I did what I know how to do: decide exactly what I wanted, say it in plain words, and check the result. Claude did the rest.</p><p><strong>What Lauschter does:</strong></p><p>- A bookmark in every story, to the second. Pause one drama, play another, and come back exactly where you left off.<br>- Resume, Restart part or Restart story, and it asks before restarting.<br>- Library → category → story → parts, with covers, and a “Continue listening” card on the home screen.<br>- Skip back 15 s or forward 30 s, speed from 0.75× to 2×, and a sleep timer from 10 to 90 minutes.<br>- Background playback that works with the player’s hardware buttons.<br>- Search across all stories, in English or Bengali.<br>- Fully offline and private: no internet permission, no account, no analytics.</p><p>Here’s the story.</p><p>I grew up with radio drama.</p><p>When I was a child, radio was a big part of everyday life, and every Saturday and Sunday meant a radio play. That habit never left me. I bought radio dramas on cassette, then on CD, and kept listening through college and into my working life. Over the years I collected a shelf full of CDs: Bengali radio drama from Indian radio stations, and a lot of British and American radio drama too: Sherlock Holmes, Miss Marple and Agatha Christie, H. G. Wells, Charles Dickens.</p><p>For a long time a CD player was my best friend. Then came the iPod, and with it something I didn’t know I’d love so much: audiobooks in M4B format, with proper chapter markers, that picked up exactly where I had stopped.</p><p>Then Apple stopped selling the iPod. My library kept growing, to many gigabytes. Today I listen on a mix of players from Sony and FiiO. All of them play audiobook files, M4B or MP3, but none of them gave me back that one feature.</p><p>Here is what I mean. I’m halfway through <em>The Sign of Four</em>. I pause. The next day I’m in the mood for <em>The War of the Worlds</em>, so I listen to that for a while. A few days later I want to go back to Sherlock Holmes, and I want to start exactly where I left him. On a music player, that’s gone. It treats every story as a pile of songs, and it only remembers the last thing you played.</p><p>I always wanted to build my own audiobook player: offline, simple, and with a bookmark in every story. Both my players run Android, so in theory I could. In practice, time and the learning curve always stopped me. I’m not an Android developer.</p><p>So I took a Claude subscription and asked Claude to build it with me.</p><h3>Lauschter</h3><p>The name. <em>Lauschter</em> comes from the Luxembourgish word <em>lauschteren</em>, “to listen”. I didn’t start there. “Just Listen” was already taken by about seven apps. “Storycast” belonged to an audiobook app. One shortlisted name turned out to mean “gambling” in Bengali and Hindi, which is not what you want for a radio-drama player. So I asked for something in Luxembourgish, and <em>Lauschter</em> was free.</p><p>Me in the driver’s seat, Claude as developer and tester. The split was clear from the first message. I decided what the app should do, how my library is organised and what “done” meant. Claude Code did the engineering: setting up the tools, writing the code, writing and running the tests, and checking the app in an emulator before it reached my player.</p><p>My first message was a list of eight requirements in plain words. Each category is a folder, like <em>Sherlock Holmes</em> or <em>Sunday Suspense</em>. Inside it, one folder per story. Inside that, the parts, numbered 01, 02 and so on. A bookmark in every story, a Resume button, and two kinds of restart: the whole story, or just the current part. Covers. A scrollable library.</p><p>Claude reviewed that list before writing any code. It kept everything, suggested a few things I hadn’t asked for (a “Continue listening” card, a sleep timer, speed control, background playback with the player’s hardware buttons), and warned me that Android usually can’t play WMA files, so the app should say so clearly instead of failing silently. Every one of those was my call to accept or not.</p><p>I stayed in charge of anything that touched my files or the outside world. Claude showed me a plan, then a dry run, and waited for my “go”. It asked before every deletion. When it was time to publish, I created the app’s signing key and password myself; Claude deliberately didn’t choose or handle them.</p><p>How it was developed. The first evening started from almost nothing. My Linux PC had no compiler, no Android tools, and installing system software needed an admin password I didn’t want to use. So Claude installed everything into my home folder: Java, the Android command-line tools, Gradle. No Android Studio at all. By the end of that evening, version 0.1 was running: a library from a folder, resume, background playback, skip buttons, speed and a sleep timer.</p><p>Next came design. Claude drew six clickable mockups of the screens (first run, library, category, story, player, restart confirmation) and I reviewed them before the app was rewritten around my category → story → parts structure.</p><p>Then came my real library. The app expects one folder per story, with the parts inside. But decades of collecting had left my library messy. Many dramas were loose files piled together in one big folder, and the same story often existed two or three times, copied from different CDs and downloads over the years.</p><p>Rather than make the app clever enough to untangle all that, we cleaned up the library first.</p><ol><li>Find the duplicates. Exact copies were found by comparing the files’ contents, not just their names or sizes. Near-copies, like the same drama from two different sources, were compared by length and quality, and the best one was kept.</li><li>Give every story its own folder, with a clean, readable name.</li></ol><p>Every step started with a dry run that showed me what would change, and came with an undo script in case I didn’t like the result. The library went from about 90 GB in 52 mixed folders to about 73 GB in 18 clean categories and roughly 1,400 stories. Nothing was deleted automatically. The duplicates and junk went to a review folder, and I deleted about 17 GB myself after checking.</p><p>Search followed in version 0.3, working in English and Bengali. On 21 November, version 0.4.0 went public as <em>Lauschter</em>.</p><h3>I was the product owner. Claude was the developer and tester.</h3><p>This is the part I think matters beyond audiobooks.</p><p>I never acted like a programmer on this project. I acted like a product owner. I knew the problem better than anyone, because I’ve lived with it since I was a child. I wrote the requirements, chose between options, said “go” or “not yet”, and tested on my real player. Claude set up the tools, wrote the code, wrote and ran the tests, found its own bugs in an emulator, and documented everything.</p><p>Many of us already work this way with human teams. The difference now is that a team of one, with a clear idea, can do it in two days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*ovX8QQq9PkPdJp0NyFG6WA.png" /><figcaption>Library tab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*xiKHDEnuH3CXbSYXFik8Jg.png" /><figcaption>Story page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*xAcF5zVrC8oKS0uhgoJTdg.png" /><figcaption>Currently playing page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*ag77CT4KSUMfUmdPCa5OEw.png" /><figcaption>Search function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*n1AjvxtdBZkWra6qSPTKUg.png" /><figcaption>Main play page</figcaption></figure><p>It’s free to download from <a href="https://github.com/ghoshm21/lauschter">github.com/ghoshm21/lauschter</a> : no internet permission, no account, no analytics. It needs Android 5.0 or newer and plays MP3, M4A, M4B, AAC, FLAC, OGG, Opus and WAV.</p><h3>Three things I’d tell anyone building with AI</h3><ol><li>Know exactly what you want, and say it plainly. Eight plain-language requirements got me a working app on the first evening. Clarity beat technical skill.</li><li>Stay in the driver’s seat. Let the AI write the code, but keep every decision that matters: what gets deleted, what goes public, and who holds the keys.</li><li>Check everything, including the AI. Tests, an emulator, three reviews and a byte-for-byte check of the download. Once, I was the one who noticed a test run was incomplete.</li></ol><h3>What’s next</h3><p>Lauschter could go on Google Play one day. That would mean updating it for the newest Android version, changing how it reads folders, writing a privacy policy and running a 14-day closed test with at least 12 testers. For now it’s free on GitHub.</p><p>And Lauschter wasn’t the only thing I built. My music library had its own problem: too many copies of the same album, and no easy way to tell which one actually sounds best. That became my next project, and it’s the story of my next article.</p><p>What app would you build if code wasn’t the barrier? Tell me in the comments. I’d love to hear the idea you’ve been carrying around for years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24d64e942ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architecture of Meaning: A Deep Dive into Knowledge Graphs]]></title>
            <link>https://ghoshm21.medium.com/the-architecture-of-meaning-a-deep-dive-into-knowledge-graphs-bf397cde5817?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf397cde5817</guid>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[semanticweb]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Sun, 03 May 2026 09:05:29 GMT</pubDate>
            <atom:updated>2026-05-03T09:11:08.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Why LLMs need a “Ground Truth” and how we build a web of knowledge that actually understands data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMl2iWht-gKv3ow9yzXa8w.gif" /><figcaption>A KG generated using concepts from this article. Green arrows — multisource validated facts</figcaption></figure><p>GPT-4 confidently told a lawyer that six real legal cases supported its argument. None of them existed.</p><p>This is the fundamental problem with today’s AI: Large Language Models are extraordinary at sounding right, but they have no mechanism for <em>being</em> right. They predict the next plausible word — they do not look up facts. The result is a system that hallucinates with complete confidence.</p><p><strong>How will Knowledge Graphs help to fix this?</strong></p><p>While an LLM stores knowledge as statistical weights distributed across billions of parameters, a Knowledge Graph stores it as explicit, verifiable facts — structured triples such as <em>(Einstein, won, Nobel Prize in Physics)</em>. You can audit them, query them, and trust them. When you wire a Knowledge Graph to an LLM, you turn a fluent guesser into a reliable expert.</p><p>This is not a future vision. Google has used a Knowledge Graph since 2012. Every time you see a fact panel in a search result, that is a KG. Amazon’s product recommendations, Spotify’s artist connections, the FDA’s drug interaction database — all Knowledge Graphs at their core.</p><p>This article breaks down how they work: from the three-word building block at the core, to the query language that powers global data, to the embedding that lets AI predict missing knowledge.</p><h3>1. The Core Primitive: The Semantic Triple</h3><h3>What is a Triple?</h3><p>At the heart of every Knowledge Graph is one deceptively simple structure: the <strong>Triple</strong>. Every single fact is expressed as three parts:</p><blockquote><strong><em>Subject → Predicate → Object</em></strong></blockquote><p>Think of it as the smallest possible sentence. The subject is the thing you are talking about. A predicate is the relationship. An object is what it connects to.</p><pre>[Albert Einstein] — won → [Nobel Prize in Physics]<br>[Albert Einstein] — bornIn → [Ulm, Germany]<br>[Nobel Prize] — field → [Physics]</pre><p>Each of these lines is one triple. A Knowledge Graph is simply a large collection of these triples layered on top of each other, which is why it looks like a web rather than a table.</p><p>There are two types of objects a triple can point to:</p><ul><li><strong>Entities</strong> — real-world things that have their own identity, like a person, a city, or an award. These become nodes in the graph and can have their own outgoing triples.</li><li><strong>Literals</strong> — raw data values like a date, a number, or a string (e.g., &quot;1879-03-14&quot; as Einstein&#39;s birth date). Literals are leaf nodes — they don&#39;t connect further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrZGKG5wYOl7itwYFwsmGw.png" /><figcaption>An RDF graph isn’t just data; it’s a web of meaning where every edge defines a relationship.</figcaption></figure><h3>Why This Simple Structure Allows Infinite Extensibility</h3><p>This is where triples outshine every traditional data structure.</p><p>In a <strong>relational database</strong>, knowledge is locked into a fixed schema. If you have a Person table with columns name, birthDate, and nationality, and you later want to add occupation, You must alter the table schema — a potentially costly migration that touches every row.</p><p>In a <strong>Knowledge Graph</strong>, there is no schema to alter. You add a new triple:</p><pre>[Albert Einstein]  --occupation--&gt;  [Theoretical Physicist]</pre><p>That’s it. No migration. No null values for everyone else who doesn’t have that property. The graph grows organically — each new fact is just a new edge.</p><p>This has three powerful consequences:</p><p><strong>1. Heterogeneous data live side by side.</strong><br> A person node can have a birthDate. A company node can have a foundedYear. A film node can have a runtime. None of these needs to be defined in the same table or even the same schema. They coexist naturally in the same graph.</p><p><strong>2. Merging two graphs requires no restructuring.</strong><br> If your company’s internal KG describes Einstein and DBpedia&#39;s public KG also describesEinstein, you can merge them by simply pointing both to the same URI identifier. The triple stack. No ETL pipeline needed to reconcile schemas.</p><p><strong>3. The graph can represent the same fact at multiple levels of detail.</strong><br> A simple graph might have just:</p><pre>[Einstein]  --won--&gt;  [Nobel Prize]</pre><p>A richer graph can extend this without touching the original triple:</p><pre>[Einstein]  --won--&gt;    [Nobel Prize]<br>[Nobel Prize]  --year--&gt;    [1921]<br>[Nobel Prize]  --field--&gt;   [Physics]<br>[Nobel Prize]  --reason--&gt;  [Discovery of the photoelectric effect]</pre><p>Each addition is additive, never destructive.</p><p>This is fundamentally different from how software engineers are trained to think. There is no “right schema” defined upfront. The graph evolves as your knowledge evolves.</p><h3>The Identification Problem (URIs)</h3><p>As soon as your Knowledge Graph grows beyond a single organisation, you hit a fundamental problem: <strong>the same word means different things to different people.</strong></p><p>Consider the string &quot;Apple&quot;. It could refer to:</p><ul><li>🍎 The fruit — a botanical genus, subject of nutrition research</li><li>💻 Apple Inc. — the trillion-dollar technology company</li><li>🎵 Apple Records — the record label founded by The Beatles in 1968</li></ul><p>Now, imagine two teams independently building Knowledge Graphs. Team A stores triples about the company’s products. Team B stores triples about the fruit’s nutritional content. Both use the label &quot;Apple&quot; as their subject node. When you try to merge their graphs, you get a disaster — suddenly the iPhone is a food product, and Apple has a market capitalisation.</p><p>This is not a hypothetical edge case. It is the default state of any real-world data integration project. A hospital database uses &quot;John Smith&quot;. A pharmacy database uses &quot;John Smith&quot;. A billing system uses &quot;John Smith&quot;. Are they the same person? The string alone cannot tell you.</p><p><strong>The solution: stop using strings as identifiers. Use URIs instead.</strong></p><p>A <strong>URI (Uniform Resource Identifier)</strong> is a globally unique address that points to exactly one thing — not a label that humans interpret, but a permanent ID that machines resolve:</p><ul><li>http://dbpedia.org/resource/Apple_Inc. → The company, unambiguously</li><li>http://dbpedia.org/resource/Apple → The fruit, unambiguously</li><li>http://dbpedia.org/resource/Apple_Records → The record label, unambiguously</li></ul><p>These are not just labels with a URL prefix. They are <strong>dereferenceable</strong> — you can look them up and get back a structured description of exactly what that entity is. The URI is the identity; the label &quot;Apple&quot; is just a human-readable nickname attached to it.</p><p>Now the merge problem disappears. Team A’s triple point to dbpedia:Apple_Inc. Team B&#39;s triple point to dbpedia:Apple. No collision, no confusion — even though both teams wrote the word &quot;Apple&quot; in their notes.</p><p>And if two organisations happen to use <em>different</em> URIs for the same real-world entity, they can declare them equivalent with a single triple:</p><pre>&lt;dbpedia:Apple_Inc&gt;  owl:sameAs  &lt;wikidata:Q312&gt;</pre><p>This one line tells every reasoner and query engine: <em>these two identifiers refer to the same thing — treat all their facts as facts about the same entity.</em> No data migration. No schema alignment. Just one triple.</p><p>This is the foundation of <strong>Linked Data</strong> — a web where facts from different sources, different organizations, and different countries connect to each other through shared identifiers, forming one giant, decentralized, queryable knowledge base.</p><h3>2. The Semantic Tech Stack: RDF, RDFS, and OWL</h3><p>To make a graph “intelligent,” we need a hierarchy of languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*Gg1cuqZpdqvwo7RmFqTUwQ.png" /><figcaption>The Semantic Tech Stack: Building intelligence layer by layer.</figcaption></figure><h3>RDF (Resource Description Framework)</h3><p>RDF is the <strong>data model</strong> — the standardised way of writing down facts as triples. Think of it as the grammar rules that every Knowledge Graph follows. On its own, RDF makes no assumptions about meaning; it simply says: <em>every statement must be a Subject–Predicate–Object triple, and every term must be identified by a URI.</em></p><p>RDF is not a file format — it is a model. That model can be serialised (written to disk) in several formats. The most human-readable is <strong>Turtle (.ttl)</strong>:</p><pre>:Einstein a :Scientist ;<br>          :bornIn :Ulm ;<br>          :won :NobelPrize .</pre><p>Reading this: Einstein <em>is a</em> Scientist, Einstein <em>was born in</em> Ulm, Einstein <em>won</em> the Nobel Prize. The semicolons let you chain multiple predicates about the same subject without repeating :Einstein each time. The dot ends the statement.</p><p>RDF alone gives you a graph of facts. But it gives you no way to say what a Scientist <em>is</em>, or whether won should only connect a Person to an Award. For that, you need the next layer.</p><h3>RDFS (RDF Schema)</h3><p>RDFS is the <strong>vocabulary layer</strong> — it lets you describe the structure and meaning of your data, not just the data itself. It gives you two fundamental tools:</p><p><strong>Classes</strong> — grouping things that share a type:</p><pre>:Scientist  rdfs:subClassOf  :Person .<br>:Award      a  rdfs:Class .</pre><p>This tells any system reading the graph: a Scientist is a kind of Person. Now, without writing it explicitly, the system knows Einstein is also a Person.</p><p><strong>Properties with rules</strong> — constraining how predicates can be used:</p><pre>:won  rdfs:domain  :Person .<br>:won  rdfs:range   :Award .</pre><p>This says: the subject of :won must be a Person, and the object must be an Award. If something :won a prize, the system can automatically infer it must be a Person — even if you never stated that explicitly.</p><p>However, RDFS is still limited — it can’t express complex logic, like “a person can only have one birthdate” or “if X is married to Y, then Y is married to X.” For that level of intelligence, we move to the final layer: OWL.</p><h3>OWL (Web Ontology Language)</h3><p>OWL is the <strong>logic layer</strong> — the full ontology language built on top of RDF and RDFS. It is grounded in a branch of formal logic called <strong>Description Logics</strong>, which guarantees that a computer can automatically reason over your definitions and draw provably correct conclusions.</p><p>Where RDFS says <em>“A is a type of B”</em>, OWL lets you express far richer constraints:</p><p><strong>Inverse Properties</strong> — define bidirectional relationships automatically:</p><pre>:isParentOf  owl:inverseOf  :isChildOf .</pre><p>State that Einstein :isParentOf Hans Albert, and OWL automatically infers Hans Albert :isChildOf Einstein. You never have to write the second triple.</p><p><strong>Transitive Properties</strong> — chain relationships across hops:</p><pre>:isPartOf  a  owl:TransitiveProperty .</pre><p>If Wheel isPartOf Car and Car isPartOf Fleet, OWL concludes Wheel isPartOf Fleet. Useful for geography, biology, organisational charts — any hierarchy.</p><p><strong>Disjoint Classes</strong> — declare that two categories can never overlap:</p><pre>:LivingPerson  owl:disjointWith  :DeceasedPerson .</pre><p>Now, if your graph accidentally contains a triple placing someone in both classes, a reasoner will flag it as a logical contradiction — catching data quality errors automatically.</p><p><strong>Cardinality Constraints</strong> — enforce how many values a property can take:</p><pre>:Person  owl:maxCardinality  1  :hasBirthDate .</pre><p>Every person can have <em>at most one</em> birth date. Violations are detectable by the reasoner.</p><p>The key insight is that OWL does not just <em>store</em> these rules — a reasoner engine <em>executes</em> them, deriving new facts and catching inconsistencies across the entire graph automatically. This is what separates a Knowledge Graph from a labelled database.</p><h3>3. Querying the World with SPARQL</h3><p>If you have a massive graph, how do you find what you need? <strong>SPARQL</strong> is the standard query language. Unlike SQL, which joins tables, SPARQL performs <strong>Graph Pattern Matching</strong>.</p><p><strong>Example:</strong> <em>“Find all scientists born in Germany who won a Nobel Prize.”</em></p><pre>SELECT ?name WHERE {<br>  ?person a :Scientist ;<br>          :bornIn :Germany ;<br>          :won :NobelPrize ;<br>          rdfs:label ?name .<br>}</pre><p>This query can even be <strong>Federated</strong>, meaning your local database can “reach out” to Wikidata or DBpedia in real-time to pull in external facts during the query execution.</p><h3>4. Logical Inference: Beyond the Explicit</h3><p>The most significant advantage of a KG over a standard database is <strong>Inference</strong>. Using a <strong>Reasoner</strong>, the system can deduce facts that were never explicitly stored.</p><p><strong>The Logic:</strong></p><ol><li>(Explicit) Socrates is a Man.</li><li>(Ontology) All Man are Mortal.</li><li>(Inferred) Socrates is Mortal.</li></ol><p>In a KG, the third fact is generated automatically. This is why KGs are “smarter” — they understand the implications of the data they hold. For even more complex logic (like “If a person has a brother and that brother has a child, then that child is their nephew”), we use <strong>SWRL (Semantic Web Rule Language)</strong>.</p><h3>5. The Modern Bridge: Embeddings &amp; LLMs</h3><p>The latest breakthrough in Knowledge Graphs is <strong>Knowledge Graph Completion</strong> using <a href="https://en.wikipedia.org/wiki/Knowledge_graph_embedding"><strong>Embeddings</strong></a><strong> (like TransE or RotatE)</strong>.</p><p>We take the entities and relations in a graph and project them into a high-dimensional <strong>Vector Space</strong>.</p><ul><li>Entities that are “similar” in the graph (e.g., <em>Physics</em> and <em>Quantum Mechanics</em>) will be close together in the vector space.</li><li>We can then use these vectors to <strong>predict missing links</strong>. If the graph is missing a fact, the math can tell us: <em>“There is a 95% probability that Node A is connected to Node B via Relation C.”</em></li></ul><h4>Why this matters for LLMs (The “Fact-Check” layer)</h4><p>LLMs are excellent at <em>explaining</em> things, but they are “stochastic parrots.” Knowledge Graphs act as a <strong>Deterministic Ground Truth</strong>.<br> By using <strong>Retrieval-Augmented Generation (RAG)</strong> with a Knowledge Graph, we can force an LLM to only answer based on the facts stored in the graph, effectively eliminating hallucinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y_00OZn7oE_Zh38HBoluw.png" /><figcaption>Using Knowledge Graphs as a deterministic anchor for Large Language Models.</figcaption></figure><h3>6. How to Build Your Own</h3><p>Most tutorials jump straight to tools and code. Before you touch a single line, you need to answer three questions: <em>What do I need to represent? Where does the data come from? How do I know it is correct?</em> The build process maps directly to those three questions.</p><blockquote><strong><em>Note:</em></strong><em> This section gives you the full conceptual pipeline. Part 2(upcoming) of this series walks through each step hands-on with real code, tools, and examples.</em></blockquote><h3>Step 1 — Ontology Engineering: Define Your World First</h3><p>Before any data enters your graph, you need a blueprint — a formal description of what kinds of things exist in your domain and how they relate to each other. This is your <strong>ontology</strong>.</p><p>Think of it as writing the rules of your world before populating it. A film database ontology might say:</p><ul><li>There is a class Film</li><li>There is a class Person</li><li>There is a subclass Director That is a type of Person</li><li>A Film has exactly one releaseYear (a literal, type integer)</li><li>A Film can have one or more actors (range: Person)</li><li>A Director directed at least one Film</li></ul><p>These rules are written in OWL and stored as part of the graph itself — not in a separate schema file. This means the rules travel with the data.</p><p><strong>The key decisions at this stage:</strong></p><p>Decision: Why it matters. What are your classes? Defines the types of nodes in your graph. What are your properties? Defines the edges — how nodes connect. Which properties are mandatory? Drives your quality rules later. Do you reuse existing ontologies? Schema.org, FOAF, and Dublin Core cover common domains — reusing them makes your graph interoperable with millions of others</p><p><strong>Reusing existing ontologies</strong> is the most underrated practice in KG engineering. If you are building a graph about people, import foaf:Person from the FOAF ontology(<a href="https://medium.com/@jolalf/foaf-friend-of-a-friend-rdf-based-social-network-ontology-case-study-539a6a950bce">link1</a>, <a href="https://www.researchgate.net/post/How_to_integrate_Foaf_ontology_in_my_project">link2</a>)instead of defining your own :Person class. Any system that understands FOAF will instantly understand your data. Reinventing common concepts is how graphs become isolated silos.</p><p>A popular tool for designing ontologies visually is <a href="https://protege.stanford.edu/"><strong>Protégé</strong></a> (free, open source) — it lets you define classes, properties, and constraints with a GUI and export valid OWL files directly.</p><h3>Step 2 — KG Construction: Populating the Graph</h3><p>Once you have an ontology, you need to fill it with facts. Data comes from two fundamentally different sources, and each requires a different approach.</p><h4>From Structured Data (Databases, CSV, Spreadsheets)</h4><p>Most organisations already have data locked in relational databases or spreadsheets. The challenge is converting that row-and-column structure into triples without losing meaning.</p><p>The W3C standard for this is <a href="https://rml.io/specs/rml/"><strong>R2RML</strong></a> (RDB to RDF Mapping Language). You write a mapping file that says: <em>“Column </em><em>first_name in table </em><em>employees maps to property </em><em>foaf:firstName on a node of type </em><em>foaf:Person, identified by the URI </em><em>hr:employee/{id}.&quot;</em></p><p>A simpler entry point is <a href="https://openrefine.org/"><strong>OpenRefine</strong></a> — an open-source tool where you can load a CSV, clean the data, and export it directly as RDF triples with no code required. For a first Knowledge Graph, this is the fastest path from a spreadsheet to a queryable graph.</p><p>The core transformation rule is always the same:</p><pre>Table Row     →   Entity (Subject node with a URI)<br>Column Name   →   Property (Predicate)<br>Cell Value    →   Literal or linked Entity (Object)<br>Foreign Key   →   Edge to another Entity</pre><h4>From Unstructured Data (Text, Documents, Web Pages)</h4><p>Most of the world’s knowledge is locked in plain text — research papers, news articles, contracts, emails. Extracting triples from text requires NLP, and it breaks down into two tasks:</p><p><strong>Named Entity Recognition (NER)</strong> — identify the <em>things</em> mentioned in the text and classify them:</p><pre>&quot;Marie Curie won the Nobel Prize in Chemistry in 1911.&quot;<br> └── Person      └── Award              └── Literal (year)</pre><p><strong>Relation Extraction (RE)</strong> — identify <em>how</em> those entities relate to each other:</p><pre>(Marie Curie)  --won--&gt;  (Nobel Prize in Chemistry)<br>(Nobel Prize in Chemistry)  --year--&gt;  (1911)</pre><p>Modern pipelines use transformer-based NLP models (spaCy, BERT fine-tuned for RE) to do this at scale. The output is a stream of candidate triples that get loaded into the graph. The word “candidate” matters — NLP extraction is probabilistic and always produces some noise, which is why Step 3 exists. You might be tempted to let an LLM define your graph for you. But be careful: in my experience, a ‘pure AI’ approach often fails in ways that are hard to fix. I’ll be breaking down exactly why — and how to do it better — in my next article.</p><h3>Step 3 — Quality Assurance: Trust but Verify</h3><p>A Knowledge Graph is only as useful as it is trustworthy. Bad data in a KG is worse than bad data in a database — because the reasoner will <em>propagate</em> that bad data through inference, multiplying errors silently across the graph.</p><p>The W3C standard for KG validation is <a href="https://www.w3.org/TR/shacl/"><strong>SHACL</strong></a><strong> (Shapes Constraint Language)</strong>. You define <strong>shapes</strong> — sets of rules that describe what valid data looks like — and run a validator against your graph. Violations are reported with the exact node, property, and rule that was broken.</p><p>A SHACL shape for a Person node might look like:</p><pre>:PersonShape<br>    a sh:NodeShape ;<br>    sh:targetClass :Person ;<br>    sh:property [<br>        sh:path :birthDate ;<br>        sh:minCount 1 ;<br>        sh:maxCount 1 ;<br>        sh:datatype xsd:date ;<br>    ] ;<br>    sh:property [<br>        sh:path :name ;<br>        sh:minCount 1 ;<br>        sh:datatype xsd:string ;<br>    ] .</pre><p>This shape says: every The Person node <strong>must</strong> have exactly one birthDate (typed as a date) and at least one name (typed as a string). Run the validator, and it will flag every node that violates these rules — before the data is ever queried or reasoned over.</p><p><strong>Common quality rules to enforce:</strong></p><p>Rule: What it catches Mandatory properties Nodes missing critical fields Datatype constraints A birthDate stored as a string instead of xsd:date Cardinality limits: A person with two birth dates (duplicate ingestion). Value range constraints A releaseYear of 1823 for a digital streaming service, Class membership A Director node missing its Person superclass</p><h3>The Full Pipeline at a Glance</h3><pre>Domain knowledge<br>      ↓<br> [Ontology Design]  ←  Protégé, OWL, existing vocabularies (FOAF, Schema.org)<br>      ↓<br> [Data Ingestion]<br>   ├── Structured  ←  R2RML, OpenRefine, direct RDF serialisation<br>   └── Unstructured  ←  NLP pipeline (NER + Relation Extraction)<br>      ↓<br> [Quality Assurance]  ←  SHACL validation, reasoner consistency checks<br>      ↓<br> [Graph Store]  ←  Triplestore (Apache Jena, Amazon Neptune, <br>                                Stardog, GraphDB, Wikibase, <br>                                Neo4j with Neosemantics.)<br>      ↓<br> [Query &amp; Application]  ←  SPARQL endpoint, RAG pipeline, semantic search</pre><p>Each arrow is a place where decisions compound. A weak ontology makes construction harder. Noisy construction makes QA expensive. Skipped QA makes downstream applications untrustworthy. The pipeline is only as strong as its weakest stage.</p><p><strong>Part 2 of this series covers each stage with working code and real datasets.</strong></p><h3>Can an LLM Build the Knowledge Graph For You?</h3><p>The short answer: <strong>not alone — and teams that try pay for it later.</strong></p><p><strong>The “Silent Failure” Example:</strong> <br> Imagine an LLM reads a news report stating: “Acme Corp partnered with Globex.”</p><p>LLM incorrectly extracts this triple: <br> [Acme Corp] — acquired → [Globex] <br> <br>Suddenly, your “Ground Truth” graph officially records a multi-billion dollar merger that never happened. Because it is in a Knowledge Graph, your software treats it as an absolute fact, drawing “logical” conclusions based on a lie. You’ve given the AI’s hallucinations the authority of a database.</p><p>The teams building reliable KGs in production today use <strong>three tools together</strong>, each doing what it is actually suited for:</p><ol><li><strong>Deterministic code</strong> — for facts that can be derived with certainty</li><li><strong>LLMs</strong> — for facts buried in unstructured language</li><li><strong>Formal logic (OWL + SHACL)</strong> — for validation, consistency, and inference</li></ol><h4>The Three-Pillar Model</h4><p>The solution is not to avoid LLMs — it is to use each tool only where it is reliable.</p><p>Pillar 1: Deterministic Code — for known structure</p><p>If your data has structure, extract it with code. A deterministic parser is always right for the cases it covers, never hallucinates, and runs in milliseconds.</p><ul><li>Dates, IDs, numeric values from databases → SQL queries or pandas</li><li>Known patterns in text → regex</li><li>Structured formats (JSON, CSV, XML) → direct parsers</li><li>Authoritative external sources → API calls (Wikidata lookup API, DBpedia Spotlight)</li></ul><p><strong>Pillar 2: NLP Pipeline + LLM — for unstructured language</strong></p><p>Once deterministic extraction is exhausted, you move to unstructured text. The instinct here is to send the raw text directly to an LLM and ask it to extract everything. <strong>This is the most common mistake.</strong></p><p>Raw text is a wide-open input. The LLM must simultaneously identify entities, classify them, find relationships, resolve ambiguity, and map everything to your ontology — all in one pass. The wider the task, the more opportunity for hallucination.</p><p>The better approach is a <strong>two-stage pipeline</strong>: let an NLP model do the coarse extraction first, then hand the pre-structured output to the LLM for the harder semantic work.</p><p><strong>Stage A — NLP Pipeline: Entity and Relation Detection</strong></p><p>A traditional NLP pipeline (spaCy, a fine-tuned BERT model, or a specialised model like REBEL) runs over the raw text and produces:</p><ul><li><strong>Named Entity Recognition (NER)</strong>: every entity in the text, labelled by type</li><li><strong>Dependency Parsing</strong>: the grammatical structure — which words modify which</li><li><strong>Relation Extraction (RE)</strong>: coarse relationships between identified entities</li></ul><p>For example, given the sentence:</p><pre>&quot;Marie Curie won the Nobel Prize in Chemistry in 1911.&quot;</pre><p>The NLP pipeline outputs:</p><pre>Entities:<br>  &quot;Marie Curie&quot;       → type: PERSON<br>  &quot;Nobel Prize&quot;       → type: AWARD<br>  &quot;Chemistry&quot;         → type: FIELD<br>  &quot;1911&quot;              → type: DATE</pre><pre>Relations (coarse):<br>  (Marie Curie)  --[won]--&gt;  (Nobel Prize)<br>  (Nobel Prize)  --[in]--&gt;   (Chemistry)<br>  (Nobel Prize)  --[year]--&gt; (1911)</pre><p>This output is <strong>deterministic and typed</strong> — the NLP model does not guess, it classifies based on trained patterns. The entities are now anchored, not floating strings.</p><p><strong>Stage B — LLM: Disambiguation and Ontology Mapping</strong></p><p>Now the LLM receives a far narrower task. Instead of <em>“read this paragraph and extract everything”</em>, the prompt becomes:</p><blockquote>“Given these pre-identified entities and coarse relations, map them precisely to our ontology. Resolve any ambiguity. Use only these allowed properties: {ontology_properties}. If a mapping is unclear, flag it rather than guessing.”</blockquote><pre>Input to LLM:<br>  Entities: [Marie Curie: PERSON], [Nobel Prize in Chemistry: AWARD], [1911: DATE]<br>  Coarse relations: won, field, year</pre><pre>LLM output (ontology-mapped triples):<br>  :MarieCurie       :won          :NobelPrizeChemistry1911 .<br>  :NobelPrizeChemistry1911  :field  :Chemistry .<br>  :NobelPrizeChemistry1911  :year   &quot;1911&quot;^^xsd:integer .</pre><p>The LLM is now doing what it is genuinely good at — semantic judgement and ontology alignment — not entity detection, which it does inconsistently. Because the entities are already identified and typed, the hallucination surface is dramatically smaller. The LLM cannot invent a new entity; it can only map the ones the NLP pipeline already found.</p><p><strong>Why this combination outperforms LLM-only:</strong></p><p>LLM only NLP Pipeline + LLM Entity detection consistency Variable — same entity named differently across runs Consistent — NER model is deterministic Hallucinated entities Possible — LLM invents entities not in text Blocked — LLM only maps pre-identified entities Ontology property consistency Often drifts across documents Anchored — LLM maps to fixed property list Speed on large corpora Slow — full text per LLM call Fast — NLP handles bulk, LLM handles edge cases Cost High — every token sent to LLM Lower — LLM receives compact structured input</p><p>The output of Stage B is always <strong>candidate triples</strong> — never committed directly to the graph. They move to Pillar 3 for validation.</p><p><strong>Pillar 3: Formal Logic (OWL + SHACL) — for validation and inference</strong></p><p>Every candidate triple — whether from code or an LLM — passes through formal validation before entering the graph.</p><p>SHACL catches structural violations:</p><ul><li>Wrong data type, missing mandatory field, cardinality exceeded</li></ul><p>OWL catches logical contradictions:</p><ul><li>A node classified as both LivingPerson and DeceasedPerson</li><li>A Film with no releaseYear when the ontology requires one</li><li>Two entities declared owl:sameAs that have contradictory properties</li></ul><p>Anything that fails validation is quarantined for human review — not silently dropped, not silently accepted.</p><h4>The Combined Pipeline</h4><pre>Raw data sources<br>      │<br>      ├── Structured (DB, CSV, API)<br>      │         ↓<br>      │   [Deterministic Code]  →  High-confidence triples (no review needed)<br>      │<br>      └── Unstructured (text, docs, web)<br>                ↓<br>          [LLM Extraction]     →  Candidate triples (anchored to ontology)<br>                ↓<br>         [SHACL Validation]    →  Structural checks (type, cardinality, format)<br>                ↓<br>         [OWL Reasoner]        →  Logical consistency checks<br>                ↓<br>         [Confidence Filter]   →  Low-confidence → human review queue<br>                ↓<br>              ✅ Approved triples enter the Knowledge Graph<br>                ↓<br>         [OWL Inference]       →  New facts derived automatically</pre><p>The deterministic path bypasses the LLM entirely — no hallucination risk, no validation overhead. The LLM path carries risk, so every triple it produces is checked before it touches the graph.</p><blockquote><strong><em>The rule of thumb:</em></strong><em> If a piece of code can extract a fact with 100% reliability, write the code. If only a language model can understand the context, use the LLM — but validate the output with formal logic before it enters the graph. The combination of all three is what makes a Knowledge Graph both fast to build and safe to trust.</em></blockquote><h3>Conclusion</h3><p>Knowledge Graphs are the bridge between human intuition and machine calculation. They provide the <strong>structure</strong> that data needs to become knowledge and the <strong>rules</strong> that AI needs to become reliable.</p><p>As we move toward more autonomous and trustworthy AI, the “Web of Data” isn’t just a vision from the past — it’s the infrastructure of the future.</p><blockquote><strong>A note on how this article was made</strong></blockquote><blockquote>All technical research and content are original human work and inflused from OpenHPI — course link: <a href="https://open.hpi.de/courses/knowledgegraphs2023">https://open.hpi.de/courses/knowledgegraphs2023</a><br> AI was used strictly for structural editing and formatting — every claim was human-written, verified, and owned by human first!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf397cde5817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Declarative Pipelines (SDP) in
Spark 4.1+]]></title>
            <link>https://ghoshm21.medium.com/spark-declarative-pipelines-sdp-in-spark-4-1-bde4e2243287?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde4e2243287</guid>
            <category><![CDATA[spark4]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 22:25:26 GMT</pubDate>
            <atom:updated>2026-01-22T22:25:26.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark 4.0 introduces a paradigm shift in data engineering: Spark Declarative Pipelines (SDP). This new framework moves us away from writing complex, imperative scripts that describe <em>how</em> to process data, and towards a clean, declarative model that describes <em>what</em> the result should look like.</p><p>Spark Declarative Pipelines (SDP) is a way to build pipelines by describing what datasets should exist (tables, streaming tables, and materialized views) and letting Spark compute the dependency graph and orchestrate execution. SDP is available in Apache Spark 4.1 and later.<br>This guide covers the core concepts, project structure, a realistic e-commerce example, and how to run SDP on an AWS lakehouse where you may use Iceberg, Delta Lake, and/or Apache Hudi. Also, in this article, we will explore what SDP is, how to set up a project, and walk through a real-world e-commerce example.</p><h4><strong>1. What SDP is (and what it is not)</strong></h4><p>A Pipeline is the primary unit of development and execution in SDP. Instead of writing a script that runs top-to-bottom, you define a collection of objects:</p><p><strong>Pipeline:</strong> a project you run via the spark-pipelines CLI, which can be call/schedule by other orchestrator. <br><strong>Streaming Tables</strong>: For incremental, continuous data processing.<br><strong>Materialized Views</strong>: For batch processing and aggregations.<br><strong>Flows</strong>: The logic connecting data.</p><p>When your pipeline runs, Spark automatically analyzes the dependencies between these objects, builds a Directed Acyclic Graph (DAG), and orchestrates the execution order and parallelization. SDP shifts you from writing imperative scripts (step 1 then step 2 and so on) to declaring datasets and letting Spark determine the run order.</p><h4>2. Install and scaffold a project</h4><p>The easiest way to start is using the new CLI tool included with Spark 4.0.<br>Install the pipelines extras and initialize a project:</p><pre># Local PySpark Installation Guide<br><br>## Prerequisites<br>For Spark 4.0+, the following versions are recommended:<br>  Java: Java 17 or newer (Java 21 is also supported).<br>  Python: Python 3.9 or newer.<br><br>## To check which Java version is currently installed and active, run these commands in your terminal:<br><br>   1. Check the active version:<br>   &gt;&gt; java -version<br><br>   2. Check the compiler version (if installed):<br>   &gt;&gt; javac -version<br><br>   3. List all installed Java versions, If you have multiple versions and want to see them all, use:<br>      update-java-alternatives --list<br><br>  Note: If java -version returns &quot;command not found&quot;, then Java is not yet installed on your system.<br><br><br>python3 --version<br>Note: My current system Python is 3.10<br><br>## Steps<br><br>1.  **Update Package List:**<br>    ```bash<br>    sudo apt update<br>    ```<br><br>2.  **Install Java (OpenJDK 17):**<br>    Spark 4.0 recommends Java 17.<br>    ```bash<br>    sudo apt install openjdk-17-jdk -y<br>    ```<br>    *Verify Java installation:*<br>    ```bash<br>    java -version<br>    ```<br><br>3.  **Install PySpark via pip:**<br>    ```bash<br>    pip3 install pyspark<br>    pip install pyspark[pipelines]<br>    ```<br>    *Note: If you encounter permission errors, use a virtual environment or `pip3 install --user pyspark`.*<br><br>4.  **Verify PySpark Installation:**<br>    Run the following Python command to start a simple Spark session:<br>    ```bash<br>    python3 -c &quot;from pyspark.sql import SparkSession; spark = SparkSession.builder.getOrCreate(); print(&#39;Spark Version:&#39;, spark.version)&quot;<br>    ```<br><br>5. pip install pyspark[pipelines]<br><br>6. spark-pipelines init --name sdp_example<br><br>7. cd sdp_example</pre><p>This command creates a standard directory structure:<br>1. `spark-pipeline.yml`: The brain of your project. Definitions of resources<br>2. `transformations/`: Directory for your Python (`.py`) and SQL (`.sql`) logic. This has all the data files loading, table creations and definitions of transformations.<br>3. `pipeline-storage/`: Directory for internal state (checkpoints and metadata.</p><h4>3. The pipeline spec: spark-pipeline.yml</h4><p>The spec defines where your pipeline code lives and where to store pipeline state (streaming checkpoints). You can also set the default catalogue and database (schema) and supply Spark configuration.</p><pre>name: sdp_example<br>storage: file:///path/to/your/project/pipeline-storage<br>libraries:<br>  - glob:<br>      include: transformations/**</pre><p><em>Storage</em>: Critical for fault tolerance. It stores checkpoints, so if your pipeline crashes, it resumes exactly where it left off.<br><em>libraries</em>: Defines where your logic lives.</p><p>Core Concepts: “The Gotchas”</p><p>Before we write code, it’s crucial to understand the rules of the declarative world.</p><p>No More `DROP` or `ALTER`. If you try to write a `DROP VIEW` or `ALTER TABLE` statement in your SQL files, the pipeline will fail. SDP expects definitions (e.g., `CREATE MATERIALIZED VIEW`), not commands. Basically, you are setting up the definitions of the datasets, like where to read from and how to read the data.</p><p>If you need to wipe everything and start fresh, then you do need to delete the checkpoints. I will explain this in future articles.</p><p><strong>Streaming vs. Batch: </strong><br>Streaming Tables (`<a href="http://twitter.com/sdp">@sdp</a>.table`): Use these for raw data ingestion. They handle “Autoloader” patterns where they watch a folder for new files (JSON/CSV) and process them incrementally. It can also be a real streamining table from kafka.</p><p>Note:Streaming tables cannot infer schema; you must define it explicitly.<br>*Materialized Views (`<a href="http://twitter.com/sdp">@sdp</a>.materialized_view`): Use these for aggregations or static lookups. They read the current state of the data and compute the result.</p><h4>4. Programming model: Python and SQL</h4><p>SDP supports both Python and SQL definitions. Python is commonly used for ingestion because it’s easy to express sources and schemas.</p><p>SQL is great for transformations and aggregations.</p><p>Python (datasets via decorators)</p><pre>from pyspark import pipelines as dp<br>@dp.table(name=&quot;raw_orders&quot;)<br>def raw_orders():<br>return spark.readStream ...</pre><p>SQL (datasets via CREATE statements)</p><pre>CREATE STREAMING TABLE raw_orders AS<br>SELECT * FROM STREAM source_view;<br>CREATE MATERIALIZED VIEW customer_spending AS<br>SELECT ...;</pre><h4>5. Hands-on example: e-commerce analytics</h4><p>Goal: continuously ingest orders (JSON files landing in S3), load customers as batch reference data, and produce a customer spending aggregate.</p><p><strong>5.1 Ingestion (Python)</strong></p><pre>from pyspark import pipelines as dp<br>from pyspark.sql.types import StructType, StructField, IntegerType, DoubleType, TimestampType<br>orders_schema = StructType([<br>StructField(&quot;order_id&quot;, IntegerType(), True),<br>StructField(&quot;customer_id&quot;, IntegerType(), True),<br>StructField(&quot;amount&quot;, DoubleType(), True),<br>StructField(&quot;order_ts&quot;, TimestampType(), True),<br>])<br>@dp.table(name=&quot;raw_orders&quot;)<br>def raw_orders():<br>return (<br>spark.readStream<br>.schema(orders_schema)<br>.json(&quot;s3a://my-datalake-bucket/landing/orders/&quot;)<br>)<br>@dp.materialized_view(name=&quot;customers&quot;)<br>def customers():<br>return (<br>spark.read<br>.option(&quot;header&quot;, True)<br>.csv(&quot;s3a://my-datalake-bucket/ref/customers.csv&quot;)<br>)</pre><p><strong>5.2 Transformation (SQL)</strong></p><pre>CREATE MATERIALIZED VIEW customer_spending AS<br>SELECT<br>c.customer_id,<br>c.name,<br>SUM(o.amount) AS total_spent<br>FROM customers c<br>JOIN raw_orders o<br>ON c.customer_id = o.customer_id<br>GROUP BY c.customer_id, c.name;</pre><h4>6. Running the pipeline</h4><p>Validate the graph (analysis only):</p><pre>spark-pipelines dry-run --spec spark-pipeline.yml</pre><p>Execute the pipeline:</p><pre>spark-pipelines run --spec spark-pipeline.yml</pre><h4>7. Operational gotchas that matter</h4><p>Keep dataset functions pure: do not perform actions (count, collect) or write/stream-start operations inside<br>dataset definitions. Return DataFrames only.<br>Also assume your definitions may be evaluated multiple times during planning. Avoid side effects (network<br>calls, random IDs, time-based logic) in definition code.</p><h4>8. AWS lakehouse integration: Iceberg + Delta + Hudi</h4><p>SDP writes outputs into the configured catalog/database. Your table format depends on the catalog configuration and the runtime dependencies you provide.</p><h4>8.1 Iceberg with AWS Glue Data Catalog (recommended)</h4><p>Iceberg is a strong default on AWS because you can use AWS Glue as the catalog and S3 as the warehouse.</p><pre>name: sdp_iceberg<br>libraries:<br>- glob:<br>include: transformations/**<br>storage: s3://my-datalake-bucket/pipeline-storage/sdp_iceberg<br>catalog: lake<br>database: analytics<br>configuration:<br>spark.sql.catalog.lake: org.apache.iceberg.spark.SparkCatalog<br>spark.sql.catalog.lake.catalog-impl: org.apache.iceberg.aws.glue.GlueCatalog<br>spark.sql.catalog.lake.warehouse: s3://my-datalake-bucket/warehouse/iceberg<br>spark.sql.catalog.lake.io-impl: org.apache.iceberg.aws.s3.S3FileIO</pre><p><strong>8.2 Delta Lake (Spark extensions + Delta catalog)</strong><br>Delta Lake requires Spark SQL extensions and a Delta catalog. Ensure Delta version compatibility with your Spark version.</p><pre>name: sdp_delta<br>libraries:<br>- glob:<br>include: transformations/**<br>storage: s3://my-datalake-bucket/pipeline-storage/sdp_delta<br>catalog: spark_catalog<br>database: analytics<br>configuration:<br>spark.sql.extensions: io.delta.sql.DeltaSparkSessionExtension<br>spark.sql.catalog.spark_catalog: org.apache.spark.sql.delta.catalog.DeltaCatalog</pre><p><strong>8.3 Apache Hudi (CDC/upserts + Glue sync)</strong></p><p>Hudi is often used for CDC and upserts. On AWS, a common pattern is to sync Hudi table metadata into AWS Glue so other engines can query it. When using SDP, you can read from Hudi tables registered in and write outputs as Iceberg/Delta, or keep outputs in Hudi if you manage the required options and dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde4e2243287" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redshift — distribution Key and Short Key]]></title>
            <link>https://ghoshm21.medium.com/redshift-distribution-key-and-short-key-739d63913b8a?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/739d63913b8a</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[data-ware-housing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 21:25:52 GMT</pubDate>
            <atom:updated>2026-01-11T21:25:52.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redshift — distribution Key and Short Key</h3><p>It was only after a particularly bad Friday, when a simple dashboard query quietly consumed 1.5 terabytes of data and then sat in ‘Running’ for almost six minutes on a 6-node<br> RA3.4xlarge cluster — that I truly began to appreciate Redshift’s distribution and sort keys.</p><p>The SQL looked harmless:</p><pre>SELECT  date_trunc(&#39;day&#39;, e.event_ts) AS event_day,<br>        u.country,<br>        COUNT(DISTINCT e.user_id)      AS dau<br>FROM    fact_clickstream e<br>JOIN    dim_user u<br>    ON  e.user_id = u.user_id<br>WHERE   e.event_date BETWEEN &#39;2025-05-01&#39; AND &#39;2025-05-07&#39;<br>GROUP BY 1,2;</pre><p>But the WLM console and system tables were yelling:</p><ul><li>‘DS_DIST_ALL_INNER’ on the large table</li><li>DS_DIST_BCAST_INNER in the plan (for the wrong, large table)</li><li>Row skew on one node</li><li>Unsorted percentage was ugly</li><li>VACUUM jobs were taking longer than some of the ETL itself</li></ul><p>That’s when I stopped treating DISTKEY and SORTKEY as checkboxes and started treating them as the core of Redshift table design.</p><p>This post is basically how I think about distribution key columns and sort key columns now — with real numbers, real pain, and what I actually do in production.</p><p>Note: For professional reasons, the precise details of the production incident from that Friday cannot be disclosed. The actual problem was considerably more complex, involving upwards of ten tables — some spanning multiple terabytes — and driven by over 100 lines of intricate SQL, which ultimately led to a staggering 300% increase in typical query execution times. Therefore, this article employs a replicated, more concise example to convey the key takeaways. Be assured, the insights gained from this simplified scenario are directly applicable to optimising real-world Redshift query performance challenges.</p><h3><strong>The production mess: nice SQL, terrible physical plan</strong></h3><p>Environment details:</p><pre>• Cluster type: RA3<br>• Node type: ra3.4xlarge<br>• Node count: 6<br>• WLM: Auto WLM, 2 main queues – one for ETL, one for BI<br>• Main tables involved:<br>o fact_clickstream<br> ~1.6 TB compressed<br> ~3.2 billion rows<br> DISTSTYLE KEY DISTKEY (tenant_id)<br> COMPOUND SORTKEY (ingest_ts)<br>o dim_user<br> ~120 GB<br> ~150 million rows<br> DISTSTYLE EVEN<br> SORTKEY (user_id)</pre><pre>SELECT  &quot;schema&quot;,<br>        &quot;table&quot;,<br>        diststyle,<br>        distkey,<br>        sortkey1,<br>        sortkey_num,<br>        tbl_rows,<br>        size,<br>        skew_rows,<br>        unsorted<br>FROM    SVV_TABLE_INFO<br>WHERE   &quot;schema&quot; = &#39;public&#39;<br>  AND   &quot;table&quot; IN (&#39;fact_clickstream&#39;, &#39;dim_user&#39;);</pre><p>Rough output (simplified):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWJuqwKsbgueTWfn5bdy6g.png" /><figcaption>Simplified SVV_TABLE_INFO output</figcaption></figure><p>Two red flags immediately:</p><ul><li>skew_rows = 7.9 on fact_clickstream → tenant-based distkey and one tenant was ~55% of the traffic.</li><li>Unsorted = 64% → Our ingest_ts sort key was essentially useless for pruning, as it was monotonically increasing and making VACUUM more expensive over time.</li></ul><p>What the query plan was actually doing:</p><p>I ran:</p><pre>EXPLAIN<br>SELECT date_trunc(&#39;day&#39;, e.event_ts) AS event_day,<br>u.country,<br>COUNT(DISTINCT e.user_id) AS dau<br>FROM fact_clickstream e<br>JOIN dim_user u<br>ON e.user_id = u.user_id<br>WHERE e.event_date BETWEEN &#39;2025–05–01&#39; AND &#39;2025–05–07&#39;<br>GROUP BY 1,2;</pre><p>The key parts of the plan (simplified):</p><pre>XN HashAggregate<br>-&gt; XN Hash Join DS_DIST_BCAST_INNER<br>Hash Cond: (&quot;outer&quot;.user_id = &quot;inner&quot;.user_id)<br>-&gt; XN Seq Scan on fact_clickstream e<br>Filter: (event_date &gt;= &#39;2025–05–01&#39;::date<br>AND event_date &lt; &#39;2025–05–08&#39;::date)<br>-&gt; XN Seq Scan on dim_user u</pre><p>The problem was layered:</p><ol><li><strong>Distribution problem (skew + broadcast)</strong></li></ol><ul><li>fact_clickstream distributed by tenant_id, but we were joining on user_id.</li><li>dim_user was EVEN.</li><li>Result: Redshift had to redistribute/broadcast one side of the join across slices. For big tables, that’s painful.</li></ul><ol><li><strong>Sort key problem (wrong column + unsorted)</strong></li></ol><ul><li>Sort key was ingest_ts, but queries filtered on event_date.</li><li>Plus unsorted was already at 64%, so even if we had filtered on ingest_ts we’d have poor block pruning.</li><li>So we basically got a <strong>full scan</strong> of the 1.6 TB table for every 7-day query.</li></ul><ol><li><strong>VACUUM cost</strong></li></ol><ul><li>Because ingest_ts was monotonically increasing, every new batch appended to the “end” of the sort key. Over time, doing a VACUUM FULL or VACUUM SORT on a multi-TB table was not cheap.</li></ul><p>From SVL_QUERY_SUMMARY (simplified):</p><pre>SELECT rows,<br>bytes,<br>cpu_time,<br>elapsed,<br>workmem,<br>is_diskbased<br>FROM SVL_QUERY_SUMMARY<br>WHERE query = &lt;problem_query_id&gt;;</pre><p>Rough numbers for that dashboard query:</p><ul><li>rows: ~<strong>3.2B</strong></li><li>bytes: ~<strong>1.5 TB</strong></li><li>elapsed: ~<strong>340 sec</strong></li><li>is_diskbased: t on a couple of steps (spills)</li></ul><p>So that’s the situation:<br> <strong>Wrong DISTKEY → skew + data movement.</strong><br> <strong>Wrong SORTKEY → no pruning + expensive VACUUM.</strong></p><h4><strong>Quick mental model: what DISTKEY and SORTKEY really control</strong></h4><p>I think about Redshift like this:</p><ul><li>Distribution style / key<br> Decides which node/slice owns a row.</li><li>EVEN — round-robin across slices.</li><li>KEY — hash on a column; same value → same slice.</li><li>ALL — full copy of the table on every node (great for small dims, terrible for big facts).</li><li>AUTO — let Redshift choose/adjust among ALL/EVEN/KEY as the table grows.</li></ul><p>Distribution directly impacts:</p><ul><li>Join cost (collocated vs broadcast vs redistribute)</li><li>Skew (one node doing most of the work)</li><li>Sort key<br> Decides physical order of rows within each slice.<br> Redshift keeps zone maps (min/max per block), and good sort keys make it skip blocks when your filter predicates match the sort columns.</li></ul><p>You get two flavours:</p><ul><li>COMPOUND — classic leading-column-first order; great if queries filter on the first column(s).</li><li>INTERLEAVED — equal weight to all sort columns; good when filters hit different columns in different queries, but more sensitive to writes and needs VACUUM REINDEX sometimes.</li></ul><p>If you come from Spark:</p><ul><li>DISTKEY ≈ repartition(…, by=column)</li><li>SORTKEY ≈ sortWithinPartitions(…) + zone maps</li></ul><p>The trick is to align:</p><ul><li>DISTKEY with your biggest joins</li><li>SORTKEY with your common filter ranges and groupings</li></ul><p><strong>Step-by-step process I use now</strong></p><p>Over time, I ended up with a fairly mechanical process.</p><p><strong>Step 1 — Find the heavy queries:</strong></p><p>I start with what’s actually hurting:</p><pre>SELECT query,<br>label,<br>starttime,<br>elapsed,<br>rows,<br>bytes<br>FROM SVL_QUERY_SUMMARY<br>WHERE starttime &gt;= dateadd(&#39;day&#39;, -7, current_timestamp)<br>ORDER BY bytes DESC<br>LIMIT 20;</pre><p>Pick the top offenders on bytes / elapsed.<br> That’s how I grabbed the DAU query I mentioned.</p><p><strong>Step 2 — Look at EXPLAIN for data movement:</strong></p><p>EXPLAIN</p><p>&lt;your slow query&gt;;</p><p>Things I scan for:</p><ul><li>DS_DIST_BCAST_INNER — broadcast join of inner table.</li><li>DS_DIST_NONE, DS_DIST_ALL_NONE — signs of distribution mismatches.</li><li>Large Seq Scan on big tables with no mention of pruning or small row counts.</li></ul><p>If a join between two large tables is using DS_DIST_BCAST_INNER, it’s a big hint that <strong>distribution is not aligned</strong>.</p><p><strong>Step 3 — Check table stats and skew:</strong></p><p>Here is the code:</p><pre>SELECT &quot;schema&quot;,<br>&quot;table&quot;,<br>diststyle,<br>distkey,<br>reldiststyle,<br>sortkey1,<br>sortkey_num,<br>tbl_rows,<br>size,<br>skew_rows,<br>skew_sortkey1,<br>unsorted<br>FROM SVV_TABLE_INFO<br>WHERE &quot;schema&quot; = &#39;public&#39;<br>ORDER BY size DESC;</pre><p>What I look at:</p><ul><li>diststyle / reldiststyle — to see if it’s KEY, EVEN, ALL, or one of the AUTO(…) variants.</li><li>skew_rows — ratio of largest slice to smallest; closer to 1 is better. Skew &gt; 4–5 on a large table usually hurts.</li><li>unsorted — if this is &gt; 20–30% on a big fact table, your sort key is probably not doing its job.</li></ul><p>In my case:</p><ul><li>skew_rows = 7.9 for fact_clickstream</li><li>unsorted = 64%</li></ul><p>So even before re-design, I knew:</p><ul><li>DISTKEY on tenant_id is causing skew.</li><li>Sort on ingest_ts is basically broken.</li></ul><p><strong>Step 4 — Decide on distribution keys:</strong></p><p>I ask a very boring question:</p><p><em>“Which columns do my largest tables actually join on, day in and day out?”</em></p><p>For this workload, 80–90% of heavy queries were:</p><ul><li>fact_clickstream <strong>JOIN</strong> dim_user on user_id</li><li>Sometimes also joining dim_country (small table) on country_code</li></ul><p>So the natural design for big tables became:</p><ul><li>DISTKEY (user_id) on fact_clickstream</li><li>DISTKEY (user_id) on dim_user <strong>or</strong> DISTSTYLE ALL if it’s small enough</li></ul><p>Because KEY distribution hashes the column and sends the same values to the same slice, this collocates the joins and removes big redistribute steps.</p><p>I changed the DDL to:</p><pre>CREATE TABLE fact_clickstream_v2 (<br>event_id bigint,<br>user_id bigint,<br>tenant_id integer,<br>event_ts timestamp,<br>event_date date,<br>event_type varchar(50),<br>device_type varchar(20),<br>url varchar(1024),<br>payload varchar(65535)<br>)<br>DISTSTYLE KEY<br>DISTKEY (user_id)<br> -- we&#39;ll fix sort key in the next step<br>;</pre><p>For dim_user (~120 GB), I didn’t want ALL because ALL multiplies storage and maintenance cost on big tables. Best practice is to keep ALL for small &lt;2–3M row dims. <br> So I went with:</p><pre>CREATE TABLE dim_user_v2 (<br>user_id bigint,<br>tenant_id integer,<br>country varchar(2),<br>signup_date date,<br>…<br>)<br>DISTSTYLE KEY<br>DISTKEY (user_id)<br>SORTKEY (user_id);</pre><p>Now both big tables are KEY-distributed on user_id, and joins on user_id can be collocated.</p><p><strong>Step 5 — Decide on sort keys:</strong></p><p>Next question:</p><p><em>“What are the most common filter predicates and groupings on this table?”</em></p><p>For fact_clickstream:</p><ul><li>Almost every query had a <strong>date range filter</strong> on event_date.</li><li>Many queries grouped by event_date, country, device_type.</li><li>Very few filtered on tenant_id directly.</li></ul><p>So the obvious sort key is event_date.</p><p>I kept it simple:</p><pre>CREATE TABLE fact_clickstream_v2 (<br>…<br>)<br>DISTSTYLE KEY<br>DISTKEY (user_id)<br>COMPOUND SORTKEY (event_date, user_id);</pre><p>Why COMPOUND and not INTERLEAVED?</p><ul><li>Queries are <strong>always</strong> filtered on event_date, sometimes also on user_id.</li><li>Compound sort keys are more robust and cheaper to maintain for time-series tables.</li></ul><p>Interleaved sort keys can shine for multi-dimensional querying (different columns filtered each time), but they’re more sensitive to incremental loads and often need VACUUM REINDEX. For a heavy write time-series, I’ve regretted going interleaved more than once.</p><p>Also, using the same column (or related columns) for DISTKEY and leading SORTKEY can be useful when queries both <strong>join and filter</strong> on that column — it reduces network and disk I/O and can enable efficient sort-merge joins instead of hash joins.</p><p>In this design:</p><ul><li>DISTKEY = user_id</li><li>SORTKEY starts with event_date, then user_id</li></ul><p>That’s a good balance between <em>date-based pruning</em> and <em>collocated joins</em>.</p><p><strong>Step 6 — Implement with a deep copy pattern:</strong></p><p>I rarely ALTER huge tables in place first try. I deep copy.</p><p>Here is the code I actually use:</p><pre>BEGIN;<br>CREATE TABLE fact_clickstream_v2<br>(LIKE fact_clickstream);<br>ALTER TABLE fact_clickstream_v2<br>ALTER DISTSTYLE KEY;<br>ALTER TABLE fact_clickstream_v2<br>ALTER DISTKEY user_id;<br>ALTER TABLE fact_clickstream_v2<br>ALTER COMPOUND SORTKEY (event_date, user_id);<br>INSERT INTO fact_clickstream_v2<br>SELECT *<br>FROM fact_clickstream;<br>ANALYZE fact_clickstream_v2;<br>VACUUM SORT ONLY fact_clickstream_v2;<br>COMMIT;<br>For the dimension:<br>BEGIN;<br>CREATE TABLE dim_user_v2<br>(LIKE dim_user);<br>ALTER TABLE dim_user_v2<br>ALTER DISTSTYLE KEY;<br>ALTER TABLE dim_user_v2<br>ALTER DISTKEY user_id;<br>ALTER TABLE dim_user_v2<br>ALTER COMPOUND SORTKEY (user_id);<br>INSERT INTO dim_user_v2<br>SELECT *<br>FROM dim_user;<br>ANALYZE dim_user_v2;<br>VACUUM SORT ONLY dim_user_v2;<br>COMMIT;</pre><p>Once done, I switch over:</p><pre>ALTER TABLE fact_clickstream RENAME TO fact_clickstream_old;<br>ALTER TABLE fact_clickstream_v2 RENAME TO fact_clickstream;<br>ALTER TABLE dim_user RENAME TO dim_user_old;<br>ALTER TABLE dim_user_v2 RENAME TO dim_user;</pre><p><strong>Step 7 — Re-check stats and re-run the query:</strong></p><p>After the copy + vacuum:</p><pre>SELECT &quot;table&quot;,<br>diststyle,<br>distkey,<br>sortkey1,<br>tbl_rows,<br>size,<br>skew_rows,<br>unsorted<br>FROM SVV_TABLE_INFO<br>WHERE &quot;table&quot; IN (&#39;fact_clickstream&#39;, &#39;dim_user&#39;);</pre><p>New rough stats:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egXDmhPy7bQZpo0cEv_Vjw.png" /><figcaption>New table Stats</figcaption></figure><ul><li>Skew dropped from <strong>7.9 → 1.3</strong> on the big fact table.</li><li>unsorted from <strong>64% → 4%</strong>.</li><li>Slight space improvement due to better sort/compression (1.6 TB → 1.55 TB).</li></ul><p>Now the same DAU query:</p><pre>SELECT date_trunc(&#39;day&#39;, e.event_ts) AS event_day,<br>u.country,<br>COUNT(DISTINCT e.user_id) AS dau<br>FROM fact_clickstream e<br>JOIN dim_user u<br>ON e.user_id = u.user_id<br>WHERE e.event_date BETWEEN &#39;2025–05–01&#39; AND &#39;2025–05–07&#39;<br>GROUP BY 1,2;</pre><p>New metrics from SVL_QUERY_SUMMARY:</p><ul><li>rows: ~<strong>900M</strong> (only the 7 days’ data, thanks to pruning)</li><li>bytes: ~<strong>400 GB</strong></li><li>elapsed: <strong>38–45 sec</strong> consistently</li><li>No is_diskbased spills</li></ul><p>And the new EXPLAIN shows a collocated join:</p><pre>XN HashAggregate<br>-&gt; XN Hash Join<br>Hash Cond: (&quot;outer&quot;.user_id = &quot;inner&quot;.user_id)<br>-&gt; XN Seq Scan on fact_clickstream e<br>Filter: (event_date &gt;= &#39;2025–05–01&#39;::date<br>AND event_date &lt; &#39;2025–05–08&#39;::date)<br>-&gt; XN Seq Scan on dim_user u</pre><p>No more DS_DIST_BCAST_INNER between the two big tables.</p><p><strong>Comparing different distribution strategies:</strong></p><p>Here is roughly how I think about distribution styles now, based on docs and real usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mdILowqvyoGBe3hWqLSxw.png" /><figcaption>Quick Tips on the Pros/Cons</figcaption></figure><p>A couple of rules I keep:</p><ul><li>If a table is <strong>&gt;100 GB</strong>, I’m very careful about ALL(This also depends on the cluster sizes too).</li><li>If two large tables join on col_x 80% of the time, they both get DISTKEY (col_x) if possible.</li><li>If there’s no obvious join column and the table is more “log-like”, I go EVEN or AUTO and lean on good sort keys.</li></ul><p><strong>Comparing sort key strategies:</strong></p><p>Sort keys are trickier, but the practical rules I use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrwfT0AqIjbfqmdmjSBrEg.png" /><figcaption>Pros ans Cons</figcaption></figure><p>The biggest mistake I’ve made:</p><ul><li>Using <strong>interleaved</strong> on a table with a <strong>monotonically increasing timestamp</strong>, heavy daily loads, and no regular VACUUM REINDEX. It works great for some weeks, then slowly dies under unsorted entropy.</li></ul><p><strong>DISTSTYLE AUTO, ATO and when I trust them:</strong></p><p>Redshift’s <strong>Automatic Table Optimization (ATO)</strong> looks at your workload and can pick/change distribution and sort keys when you use DISTSTYLE AUTO and SORTKEY AUTO.<a href="https://docs.aws.amazon.com/redshift/latest/dg/t_Creating_tables.html?utm_source=chatgpt.com">AWS Documentation+2Amazon Web Services, Inc.+2</a></p><p>For existing tables, you can enable it like this:</p><p>ALTER TABLE fact_clickstream ALTER DISTSTYLE AUTO;</p><p>ALTER TABLE fact_clickstream ALTER SORTKEY AUTO;</p><p>A couple of practical notes from my side:</p><ul><li>I love AUTO for <strong>new</strong> or <strong>non-critical</strong> tables where I don’t yet know patterns.</li><li>For <strong>core TB-scale fact tables</strong>, I usually:</li><li>Start with a <strong>manual, conservative design</strong> (KEY on main join, SORT on date).</li><li>Maybe set DISTSTYLE AUTO later so Redshift can tweak effective distribution, but I still monitor it with SVV_TABLE_INFO / PG_CLASS_INFO.</li></ul><p>ATO is helpful, but it’s not a substitute for understanding your join graph and filter patterns.</p><p><strong>VACUUM, ANALYZE, and ongoing cost:</strong></p><p>A lot of people redesign dist/sort keys and then forget the boring parts:</p><ul><li>ANALYZE — updates stats so optimizer can pick good plans.</li><li>VACUUM — maintains sort order and reclaims space.</li></ul><p>On big tables I usually do:</p><p>ANALYZE fact_clickstream;</p><p>VACUUM SORT ONLY fact_clickstream;</p><p>Some quick lessons:</p><ul><li><strong>Wide sort keys</strong> (many columns) → more data to move around during vacuum.</li><li>Highly unsorted tables can make VACUUM FULL very expensive; sometimes a deep copy is cheaper.</li><li>Interleaved sort keys may require VACUUM REINDEX, which rewrites the table’s sort.</li></ul><p>So when I choose sort keys, I always weigh:</p><p>“Is the pruning benefit worth the long-term VACUUM cost on a 1–3 TB table?”</p><p>Most of the time, a simple COMPOUND SORTKEY (event_date) is enough.</p><p><strong>A very short recipe you can follow tomorrow:</strong></p><p>If I had to compress all this into a checklist for tuning one big table, it would be:</p><ol><li>Identify top-heavy queries from SVL_QUERY_SUMMARY (by bytes/elapsed).</li><li>Inspect EXPLAIN — note joins and any DS_DIST_* operators.</li><li>List join columns between your largest tables — pick a primary one.</li><li>Choose DISTKEY:</li></ol><ul><li>Collocate big joins → DISTKEY (join_col) on both sides.</li><li>No clear join → use EVEN or DISTSTYLE AUTO.</li></ul><ol><li>Choose SORTKEY:</li></ol><ul><li>Time-series → COMPOUND SORTKEY (date[, user_id]).</li><li>Highly ad-hoc → consider INTERLEAVED, with caution.</li></ul><ol><li>Deep copy the table with new dist/sort keys; INSERT … SELECT, ANALYZE, VACUUM SORT ONLY.</li><li>Measure again (rows/bytes/elapsed) and compare to your baseline.</li></ol><p>If the bytes scanned didn’t drop and the join data movement is still high, the bottleneck might be elsewhere (SQL logic, bad predicates, missing filters).</p><p><strong>Conclusion:</strong></p><p>At some point, I realised Redshift performance is less about “tuning queries” and more about putting rows on the right node and in the right order.</p><ul><li>Distribution keys decide <em>who</em> owns the data.</li><li>Sort keys decide <em>how</em> it’s laid out on disk.</li></ul><p>Once you align DISTKEY with your main joins and SORTKEY with your main filters, most of the big stupid queries suddenly become boring — they stop shuffling terabytes and start behaving like normal analytics workloads.</p><p>I’ll probably clean up these examples into a small Redshift design repo and push it to GitHub at some point.</p><p><strong>Links:</strong></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html">https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html">https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html</a></p><p><a href="https://pages.awscloud.com/rs/112-TZM-766/images/Optimize%20your%20Data%20Warehouse%20Performance%20with%20Amazon%20Redshift%20Autonomics.pdf">https://pages.awscloud.com/rs/112-TZM-766/images/Optimize%20your%20Data%20Warehouse%20Performance%20with%20Amazon%20Redshift%20Autonomics.pdf</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/c_choosing_dist_sort.html">https://docs.aws.amazon.com/redshift/latest/dg/c_choosing_dist_sort.html</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html">https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.htm">https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.htm</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data-compound.html">https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data-compound.html</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/viewing-distribution-styles.html">https://docs.aws.amazon.com/redshift/latest/dg/viewing-distribution-styles.html</a></p><p><a href="https://docs.aws.amazon.com/redshift/latest/dg/identify-tables-with-data-skew-or-unsorted-rows.html">https://docs.aws.amazon.com/redshift/latest/dg/identify-tables-with-data-skew-or-unsorted-rows.html</a></p><p><a href="https://airbyte.com/data-engineering-resources/distkey-and-sortkey-in-redshift">Mastering distkey and sortkey in Redshift for Optimal Performance | Airbyte</a></p><p><a href="https://www.youtube.com/watch?v=CLPv2Yhez_c">https://www.youtube.com/watch?v=CLPv2Yhez_c</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=739d63913b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pendulum: An Intuitive DateTime Library for Python Developers]]></title>
            <link>https://ghoshm21.medium.com/pendulum-an-intuitive-datetime-library-for-python-developers-31cbd1cc4d32?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cbd1cc4d32</guid>
            <category><![CDATA[pendulum]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[better-coding]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 20:13:09 GMT</pubDate>
            <atom:updated>2025-07-08T20:13:09.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulGGfWsxO9A3QiDpNRaMXQ.png" /></figure><h4>Pendulum: An Intuitive DateTime Library for Python Developers</h4><p>Python’s built-in datetime module is powerful, but often verbose and unintuitive. Pendulum is a modern drop-in replacement that offers <strong>cleaner syntax</strong>, <strong>built-in time zone support</strong>, and <strong>human-friendly APIs</strong> for date and time operations. It’s built to make working with time in Python easier and more predictable.</p><h4>Key Features at a Glance</h4><ul><li><strong>Cleaner syntax</strong> — More concise and readable than before datetime</li><li><strong>Automatic time zone handling</strong> — Eliminates the need to manually manage offsets</li><li><strong>Simplified duration arithmetic</strong> — Making time addition or subtraction intuitive</li><li><strong>Immutable by default</strong> — Encourages safer and more predictable code</li><li><strong>Drop-in compatible</strong> — Integrates seamlessly with datetime.datetime objects</li></ul><h4>Installation</h4><pre>pip3 install pendulum</pre><h4>Common Use Cases and Examples</h4><ol><li>Creating DateTime Objects</li></ol><pre>import pendulum<br><br>dt = pendulum.datetime(2025, 7, 8, 15, 30)<br>print(dt)  # 2025-07-08T15:30:00+00:00<br><br># Creating in a specific timezone<br>dt_paris = pendulum.datetime(2025, 7, 8, 15, 30, tz=&quot;Europe/Paris&quot;)<br>print(dt_paris)  # 2025-07-08T15:30:00+02:00</pre><p>2. Working with Durations</p><p>Pendulum makes date arithmetic readable and expressive:</p><pre>now = pendulum.now()<br>future = now.add(days=3, hours=5)<br><br>print(future.diff_for_humans())  # in 3 days</pre><p>3. Parsing ISO8601 or Custom Strings</p><pre># Parsing ISO8601<br>dt = pendulum.parse(&quot;2025-07-08T15:30:00Z&quot;)<br>print(dt)  # 2025-07-08T15:30:00+00:00<br><br># Parsing a custom format<br>dt_custom = pendulum.from_format(&quot;08-07-2025&quot;, &quot;DD-MM-YYYY&quot;)<br>print(dt_custom.to_date_string())  # 2025-07-08</pre><p>4. Timezone Conversion</p><pre>utc_dt = pendulum.datetime(2025, 7, 8, 15, 30, tz=&quot;UTC&quot;)<br>local_dt = utc_dt.in_timezone(&quot;America/New_York&quot;)<br><br>print(local_dt)  # 2025-07-08T11:30:00-04:00</pre><p>5. Periods vs Durations</p><p>Pendulum can distinguish between fixed <strong>durations</strong> and actual <strong>calendar periods</strong>:</p><pre>start = pendulum.datetime(2025, 1, 1)<br>end = pendulum.datetime(2025, 3, 1)<br><br>period = pendulum.period(start, end)<br>print(period.months)  # 2</pre><p>6. Scheduling Daily Email Reminders (e.g., in a task manager)</p><pre>import pendulum<br><br>user_timezone = &quot;Asia/Kolkata&quot;<br>now = pendulum.now(user_timezone)<br><br>next_8am = now.next(pendulum.MONDAY).set(hour=8, minute=0)<br>print(f&quot;Next reminder will be sent at: {next_8am.to_datetime_string()}&quot;)<br># This will show messages a very readable like “3 hours ago” or “2 weeks ago”.</pre><p>When Should You Use Pendulum?</p><ul><li>Involves <strong>complex scheduling or calendar logic</strong></li><li>Needs to <strong>support multiple time zones effortlessly</strong></li><li>Requires <strong>user-friendly date formatting</strong> (e.g., “in 5 days”)</li><li>Deals with <strong>intervals and periods</strong> in reports or logs</li></ul><p>Pendulum replaces the clunky parts of datetime with a modern, developer-friendly API. It’s one of those libraries that, once you start using, you won’t want to go back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cbd1cc4d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO PARSE XML DATA TO A SAPRK DATAFRAME]]></title>
            <link>https://ghoshm21.medium.com/how-to-parse-xml-data-to-a-saprk-dataframe-d2d5973a3cd4?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2d5973a3cd4</guid>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 20:31:46 GMT</pubDate>
            <atom:updated>2022-03-14T20:31:46.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>Purpose</h3><p>In one of my projects, I had a ton of XML data to perse and process. XML is an excellent format with tags, more like key-value pair. JSON also is almost the same, but more like a strip down version of XML, So JSON is very lightweight while XML is heavy.<br>Initially, we thought of using python to parse the data and convert it to JSON for the spark to process. However, the challenge is the size of the data. The entire 566GB of data would take a long time for python to perse.<br>So the obvious choice was the pyspark. We want to perse the data with the schema to a data frame for post-processing. However, I don’t think, out of the box pysaprk support XML format.<br>This document will demonstrate how to work with XML in pyspark. This same method should work in spark with scala without significant changes.</p><h4>Option 1:-</h4><p>Use spark-xml parser from data bricks<br>Data bricks have 2 xml parser; one spark compiles with scala 2.11 and another one with scala 2.12.<br>Please make sure you use the correct one.<br>I have spark compiled with scala 2.11<br>We can include the dependency in a pom or sbt file. Then open the spark-shell(submit) with “ — packages com.databricks:spark-xml_2.11:0.6.0”<br>Ref: <a href="https://stackoverflow.com/questions/50429315/read-xml-in-spark">https://stackoverflow.com/questions/50429315/read-xml-in-spark</a></p><h4>Option 2:-</h4><p>Like my current organization, if you have difficulties in compiling the code with maven or sbt because of the dependency to download from the internet, then you can use the jar file from data bricks website.</p><p>scala 2.11: <a href="https://repo1.maven.org/maven2/com/databricks/spark-xml_2.11/0.6.0/spark-xml_2.11-0.6.0.jar">https://repo1.maven.org/maven2/com/databricks/spark-xml_2.11/0.6.0/spark-xml_2.11-0.6.0.jar</a><br>scala 2.12: <a href="https://repo1.maven.org/maven2/com/databricks/spark-xml_2.12/0.6.0/spark-xml_2.12-0.6.0.jar">https://repo1.maven.org/maven2/com/databricks/spark-xml_2.12/0.6.0/spark-xml_2.12-0.6.0.jar</a></p><p>While launching the spark-shell or submitting it, please include the JAR with <strong>— jars full/path/of the/jar</strong></p><p><strong><em>pyspark — jars /home/sandipan/Downloads/spark_jars/spark-xml_2.11–0.6.0.jar</em></strong></p><h4>How to parse the data:-</h4><p>Very simple, read the xml with the format option and spark should infer the schema.</p><p><strong><em>df = spark.read \<br> .format(“com.databricks.spark.xml”) \<br> .option(“rootTag”, “SmsRecords”) \<br> .option(“rowTag”, “sms”) \<br> .load(“full/path/of/the/xml”)</em></strong></p><p>Note:- the “rootTag” is the starting of the xml tag or the main (toor) tag while the “rowTag” is the main row tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pwYI7aWl5LnPoARy.png" /><figcaption>Input data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*ArywdfltIgH-7T1a.png" /><figcaption>Code and schema</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HvkjirDW2wv9xJBT.png" /><figcaption>After parsing the data</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2d5973a3cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Streaming — AWS Kinesis]]></title>
            <link>https://ghoshm21.medium.com/data-streaming-aws-kinesis-41f97ce3d316?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f97ce3d316</guid>
            <category><![CDATA[datastream-api]]></category>
            <category><![CDATA[kinesis-firehose]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kinesis]]></category>
            <category><![CDATA[boto3]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 11:10:08 GMT</pubDate>
            <atom:updated>2023-09-22T08:52:25.462Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Data Streaming — AWS Kinesis</strong></h3><p>In my current organisation, we had implemented Kafka from end to end, from acquiring resources, installing Kafka, developing the producer, consumer and streaming applications. We also maintain the Kafka cluster along with all the applications. This approach is a colossal effort. Not every situation have the luxury of time and resources to take the above policy. In the time/effort crunch situation, AWS Kinesis can help to achieve the goal.</p><p>Kinesis is an AWS managed streaming platform that can be acquired, developed and handled efficiently and quickly.</p><p>In this article, I will put together a use case of real-time streaming using Kinesis data stream. I will use Python as a programming language.</p><p>The concept is straightforward. We have a data producer(Twitter), which we would like to capture and stream the data through a streaming application (Kinesis data stream). Then, a consumer will capture the data and process it through two machine learning models to extract sentiment and keywords from the Twitter text. Finally, we will save the final output to an S3 bucket. We can also save the raw Twitter data to the S3 bucket for future use. To do this, we will use Kinesis Firehose.</p><p>Before we move forward, let&#39;s go through few of Kinesis main components.</p><p><strong>The AWS Kinesis Overview</strong></p><ul><li>Kinesis is an AWS managed alternative to Apache Kafka</li><li>Great for application logs, metrics, IoT, clickstreams</li><li>Great for &quot;real-time&quot; big data streaming</li><li>Great for streaming processing frameworks (Spark, NiFi, etc. )</li><li>Data is automatically replicated synchronously to 3 AZ</li><li>Kinesis Streams: low latency streaming ingest at scale</li><li>Kinesis Analytics: perform real-time analytics on streams using SQL</li><li>Kinesis Firehose: load streams into S3, Redshift, ElasticSearch &amp; Splunk etc.</li><li>Kinesis Video Streams: securely stream video from connected devices to AWS for analytics, machine learning (ML), playback, and other processing</li></ul><p>Kinesis has three parts, a producer, a data stream and a consumer. Kinesis Firehose is a particular type of consumer that reads the data from the data stream, processes the data with lambda functions(optional), compress(optional), and store in a destination like an s3 bucket.</p><p>We can interact with Kinesis in three different ways — Kinesis SDK, Kinesis producer Library(KPL) and Kinesis agent</p><p><strong>The Kinesis SDK(both producer and consumer)</strong></p><ul><li>Boto3 for Python is an example of this. We can use API calls like putRecord(s) to put the data into the stream.</li><li>There are many vendor-specific 3rd party lib built on the SDK, like Kafka connects, spark, flume, nifi etc.</li></ul><blockquote>Kinesis Producer SDK — PutRecord(s)</blockquote><ul><li>Frequently used APIs are PutRecord (one) and PutRecords (many records)</li><li>PutRecords uses batching and increases throughput. You can also compress the data and reduce the data load size</li><li>ProvisionedThroughputExceeded if we go over the limits</li><li>You can use this SDK with Android, iOS, etc…</li><li>Use case: low throughput, higher latency, simple API, easy to use with AWS Lambda</li><li>You can use managed AWS sources for Kinesis Data Streams, like — Cloud watch, IoT, Kinesis data analytics etc.</li><li>Users need to build the logic for data distribution, exception handling and data compression</li></ul><blockquote>Kinesis consumer SDK — GetRecord(s)</blockquote><ul><li>Classic Kinesis — Consumers poll records from a shard(Kinesis)</li><li>Each shard has 2 MB total aggregate throughput</li><li>GetRecords returns up to 10MB of data, then throttle for 5 seconds or up to 10000 records</li><li>Maximum of 5 GetRecords API calls per shard per second = 200ms latency</li><li>If five consumers in a location consume data from the same shard, means every consumer can poll once a second and receive less than 400kbs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIuhDIX53VCDpxtHWzUT9Q.png" /><figcaption>multiple consumer fetching data from the same shard</figcaption></figure><p><strong>Kinesis Producer Library (KPL)</strong></p><ul><li>Kinesis producer library — It&#39;s a JAVA/C++ based library. I haven&#39;t seen any wrapper code for Python yet.</li><li>Best for long-running high-performance producers</li><li>Great for automation and configurable retry mechanism</li><li>Synchronous or Asynchronous API (use async for better performance)</li><li>CloudWatch metrics for monitoring</li><li>Automated batching — increase throughput, decrease cost</li><li>Collect Records and Write to multiple shards in the same PutRecords API call, so you pay less for the larger amount of data</li><li>Aggregate and compress — increased latency and efficiency (also pay less).</li><li>Capability to store multiple records in one record (go over 1000 records per second limit)</li><li>Increase the &#39;recordMaxBufferedTime&#39; to collect multiple records and then aggregate and compress to increase payload size and improve throughput (maximize I MB/s limit)</li><li>Users must implement all the compression/decompression mechanism</li><li>KPL Records must be de-coded with KCL or a special helper library</li><li>This is one of the best approaches for higher efficiency, throughput, with a lot of users control, while paying less $ amount</li></ul><p><strong>Kinesis Client Library (KCL)</strong></p><ul><li>Java-first library but exists for other languages too (Golang, Python, Ruby)</li><li>Read records from Kinesis produced with the KPL (de-aggregation)</li><li>Share multiple shards with multiple consumers in one &quot;group&quot;, shard discovery</li><li>Checkpointing feature to resume progress</li><li>Leverages DynamoDB for coordination and checkpointing (one row per shard). Make sure you provision enough WCU / RCU or use On-Demand for DynamoDB Otherwise, DynamoDB may slow down KCL</li><li>Record processors will process the data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gug_CfpbAxRXLLXbvbNdww.png" /><figcaption>Dynamodb for checkpoint coordination</figcaption></figure><p><strong>Kinesis Agent (Both producer and consumer)</strong></p><ul><li>Monitor Log files and sends them to Kinesis Data Streams</li><li>Java-based agent, built on top of KPL</li><li>Install in Linux-based server environments</li><li>Write from multiple directories and write to multiple streams</li><li>Routing feature based on directory/logfile</li><li>Pre-process data before sending to streams (single line, CSV to JSON, log to JSON… )</li><li>The agent handles file rotation, checkpointing, and retry upon failures</li><li>Emits metrics to CloudWatch for monitoring</li><li>Best for aggregating high-frequency logs data and monitor near real-time</li></ul><p><strong>Kinesis Firehose</strong></p><p>Firehoses are the opposite of Data Streams; they distribute records/data to specified endpoints configured in the Firehose from a selected source. We can also specify any transformations or formatting we&#39;d like to apply to the data before it&#39;s pushed out in a Firehose. Firehose supports lambda functions so we can use a lambda function to achieve any inline transformation. It also supports compressions techniques and multiple destination types.</p><p><strong>Streams vs Firehose</strong></p><p>Amazon Kinesis offers two main products to choose from, <a href="https://aws.amazon.com/kinesis/data-streams/">Kinesis Streams</a> and <a href="https://aws.amazon.com/kinesis/data-firehose/">Kinesis Firehose</a>.</p><p>To work with Kinesis Streams, you&#39;ll use the Kinesis Producer Library (KPL) to put data into the stream. Then, you can connect it to almost any application or process.</p><p>Kinesis Streams is not a fully managed service, which means your team need to scale it as required, manually by adding more shards. In addition, the data only stay in the stream for seven days(max), the default is 24 hours. You need to carefully plan it well in advance considering the data throughput, compression, destination types and $ values.</p><p>Kinesis Firehose is simpler to implement. Data from Firehose can be saved into Amazon S3, Amazon Redshift, or even Elasticsearch using the Kinesis Agent, and from there, you can process the data. If the data is stored in Amazon S3 or another AWS data storage system, you can leave it there for much longer than seven days. You can decide how long it stays in the system. This approach is suitable for log time rotation of data(hot/cold data layer).</p><p><strong>What is Shard?</strong></p><p>Shard is the base throughput unit of an Amazon Kinesis data stream. Consider this as a pipe, through which data flow in a stream from source to destination. One shard provides a capacity of 1MB/sec data input and 2MB/sec data output. Thus, one shard can support up to 1000 PUT records per second. You will specify the number of shards needed when you create a data stream. The user needs to fix the number of shards required while creating the data stream based on the requirements(keep in mind the compression and aggregation of input records can increase the throughput).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDA_06oDYGryWso-cYS0vQ.png" /><figcaption>Multiple Shards</figcaption></figure><p>Once we have multiple shards per application, the critical concept is distributing the data across multiple shards for better performance and throughput. Our aim would be to keep every shard occupancy maximum. Using the proper unique Partition key we can achieve this.</p><p><strong>What is Partition Key?</strong></p><p>The partition key is used to segregate and route records to different shards of a data stream to balance the shards utilizations. A partition key is specified by your data producer while adding data to an Amazon Kinesis data stream. For example, assume you have a data stream with two shards (shards 1 and 2). You can configure your data producer to use two partition keys (key A and key B) so that all records with key A are added to shard 1, and all records with key B are added to shard 2. For example, if we use employee_id as the portion key, data would be well distributed between multiple shards. On the other hand, if we chose dept_id, then the distribution of records might not be balanced between shards, as some departments might have more employees than others. While splitting a big record in multiple chunks, we can use the same key as the partition key value, so all the chinks end up in the same shards. Then the consumer can easily capture those chunks and stitch those to recreate the original data quickly.</p><p><strong>What is the sequence number?</strong></p><p>A sequence number is a unique identifier for each record. The sequence number is assigned by Amazon Kinesis when a data producer calls PutRecord or PutRecords operation to add data to an Amazon Kinesis data stream. Sequence numbers for the same partition key generally increase over time; the longer the time period between <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html">PutRecord</a> or <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html">PutRecords</a> requests, the larger the sequence numbers become. To put together a split record from the data stream you can use the same partition key and gradually increased sequence numbers.</p><h4>Sample Application and implementations</h4><p>Here is the diagram of the sample application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JylTzjvAoX8VNr6d9xjFKw.png" /><figcaption>Sample application</figcaption></figure><ol><li>My source system is Twitter.</li><li>I will use EC2 machines for the producer and consumer. Both producer and consumer can be a serverless lambda function.</li><li>I will write a python producer using boto3 to read the data from Twitter API and push it to the Kinesis data stream.</li><li>I will use a python boto3 consumer to consume the stream and unwarp data into a JSON.</li><li>On the consumer side, I will use python code to clean and pre-process the data to perper for the machine learning models.</li><li>I have two models to run. One for getting the sentiment of the text and another one for extracting the keywords. Both can be replaced by AWS lambda.</li><li>Finally, I will save the final data to an S3 bucket.</li><li>To reduce the size of the payload, I will compress the data in the stream using gzip. You can use snappy too.</li></ol><h4>Get Twitter API access</h4><p>First, you will need Twitter API access to capture the Twitter data using Python.</p><p>You can get this access by following <a href="https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api">https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api</a></p><p>Once you acquire the access, collect the access key, access token, consumer key and consumer token. You will need this to capture the data from Twitter API.</p><blockquote>I am using tweepy python package for capturing the data</blockquote><h4>Create a new user</h4><p>We need a user who will have AWS API, CLI and SDK access, so we can use the same user to connect to the Kinesis data stream from producer and consumer EC2 instances. This user also needs Kinesis and S3 full access to read/write to and from Kinesis and S3. Here are few captures of the AWS steps. Also, once you have completed the steps, do not forget to download and save the AWS access key and secret. Also, don’t forget to add this key file in gitignore file, so you don&#39;t accidentally publish the keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTYAUUodx7baHXLycKlJng.png" /><figcaption>New user with programmatic access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52ADNSJkpwOBplstIou4NQ.png" /><figcaption>The new users should have Kinesis full access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rcfkdxkn62u90HzIWWIETg.png" /><figcaption>The new users should have S3 full access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRlrof4O_bFlaqBdw2SOGw.png" /><figcaption>Final step</figcaption></figure><h4>Launch Producer and Consumer EC2 machine</h4><p>Let’s create two EC2 instances, one for the producer and another one for the consumer. I don’t need any specific role/policies for ec2 to access kinesis and s3.<br>The below capture shows the steps to create the EC2 instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQRP87GQN69HQEV8uxUjvA.png" /><figcaption>Use Ubuntu image for the EC2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGzv6-ZyZ9Yi103d_SWIzQ.png" /><figcaption>I am using free EC2, t2 micro</figcaption></figure><p>I have specified the number of instances on the configuration page as two and keeping all other options to default. Note, I have not specified any IAM role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evklc2Ft6gTC1qumPsOGag.png" /><figcaption>Config details</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WA1u_t4TPiFs4c9JqZC_hA.png" /><figcaption>RAM size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGiHyo2CoBVdNBb1zh5jTg.png" /><figcaption>Put some tags</figcaption></figure><p>In the security group, we are opening all the required ports. Note, I am giving access to the entire world. This is not recommended in production. The EC2 instances should be behind custom VPC, subnet, route table, and internet gateway to secure the networks in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fYGxg94dKogl4ZKq5bxkg.png" /><figcaption>open ports. Be careful in production</figcaption></figure><p>Finally, please review and launch. Also, save the key-pair to log in to the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txt90znleR3TceK0WAV-LQ.png" /></figure><p>After a few min, all the instances would be running. Now we are ready to login to producer EC2 to set up the producer process.</p><p>Before login, please change the permission of the .pem file to 400, which you have downloaded in the above step.</p><blockquote>chmod 400 *****.pem</blockquote><h4>Producer</h4><p>Let&#39;s log in and start setting up our code.</p><blockquote>ssh -i ****.pem ubuntu@public.ip.for.producer</blockquote><blockquote>sudo apt-get update &amp;&amp; sudo apt-get upgrade</blockquote><blockquote>sudo apt install python3-pip</blockquote><p>Create a ‘requirements.txt’ file under the home dir ‘/home/ubuntu’. We will put all the required python packages here and use pip3 to install them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*ZXKW8cC-tQAC7I38kFjF9Q.png" /><figcaption>requirements.txt</figcaption></figure><blockquote>pip3 install -r ./requirements.txt</blockquote><p>Now we are ready for the producer code. Here is the code capture. You can have the full code from the GitHub location, which is mentioned toward the end of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Kvoac-h76UTpZ982773jA.png" /><figcaption>Code part — 1</figcaption></figure><p>First, I am importing a few packages, including ‘tweepy’ and ‘boto3’. Note that I have kept all the keys, ids and tokens in a file called ‘settings.py’. Using this method, I am encapsulating all the secrets and not hardcoding or passing them as parameters. I can hide this file and limit the access for other users, so my keys can be secure. Also, don&#39;t forget to add this file to the gitignore file.<br>Then I am creating a Kinesis client called client. I will use this client to create the data stream and push the data into this stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIR2YGckykoeeEpmdjYDNA.png" /><figcaption>Code part — 2</figcaption></figure><p>Next, I am defining two functions to create a stream and get the status of the stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewi5hPgIuGTe1Ns3A6XkDw.png" /><figcaption>Code part — 3</figcaption></figure><p>Next, I am using tweepy’s StdOutListener class to push the Twitter data to the stream. First, I capture the data, then dumps it as a JSON, convert it to a bytes stream, and then compress the data with the gzip method. I am using uuid as the partition key. This is a great trick to uniformly distribute the data into multiple shards. I could have used twit id as the partition key; however, I do not want to parse the data here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bYeuKjCb6dXgtSst9uZTw.png" /><figcaption>Code part — 4</figcaption></figure><p>This is the main part of the code. First, I create the Kinesis data stream, then wait until it’s become active. Then I started collecting the data and kept pushing the data to the stream. You can use the filter methods to filter the Twitter data for any topic. Here I am using the new Bond movie name.<br>Now, let’s start the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*9ougCQnSKDkoAaWb4KPn3g.png" /><figcaption>Running the code for first time</figcaption></figure><p>We can stop the code at any time and re-run it easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Yxyu52KTA5FMkljqsgo57w.png" /><figcaption>Rerunning the code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*1pnf5UYWkr7kNuxLnSe_yg.png" /><figcaption>Code dir structure</figcaption></figure><p>Once the code we run, a new data stream was created in AWS with 2 shards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5bL2JqwnSg-gYCwb2Fogg.png" /><figcaption>New Data Stream in AWS</figcaption></figure><h4>Firehose</h4><p>Before moving to the consumer, let’s create a firehose delivery stream, which will pick up the raw data from the Kinesis data stream (twitter_ds) and collect it into an S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ze9CvyZDm12VY0riGFe2w.png" /><figcaption>Firehose — settings 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4GOE4A71RWT9GmSBzhecA.png" /><figcaption>Firehose — settings 2</figcaption></figure><p>Once the Firehose started, you can see that it began to accumulate data into the S3 bucket in a few minutes. Note that all the data is in gzip format as our producer is compressing the data before sending it to the data stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGWmxPHBLphmG5qyNLKqSw.png" /><figcaption>Data into S3</figcaption></figure><p>We can download the data and open it. Once downloaded, please de-compress with gzip to get the raw data. I convert the file name to .zip to open in WinZip (or similar) software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vedcPigwoJB9oPSyRNZVTw.png" /><figcaption>Download the data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2Xt7Ot1ZsJADsgini1wlQ.png" /><figcaption>de-compress and open it notepad</figcaption></figure><p>Now we can create a consumer python code.</p><h4>Consumer</h4><p>We can use boto3 for the consumer as well. boto3 is easy to implement. However, this approach quickly becomes complicated if the stream has multiple shards and records are split into multiple parts. Also, users need to implement the checkpoint manually. Using Kinesis Client Library (KCL) for Python simplifies the process. <br>Here is a working simple consumer code using boto3. I am using multiple shards and I am keeping the records limit as 1. This is not a good practice as we will pay more for the numerous call to the API. If we increase the limit, then we can get more data in one API call. We also use ‘NextShardIterator’ for looping through the stream for the data, if no data present then the code print a message stating no data available, and wait for 5 sec before checking again. I am writing the final data into a text file. I am using ShardIteratorType as ’TRIM_HORIZON’. More about this on <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kinesis.html#Kinesis.Client.get_records">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kinesis.html#Kinesis.Client.get_records</a></p><p>Here is the sample capture of running both producer and consumer code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBX38Gw3RvbtoQ9QWT8Gwg.png" /><figcaption>Producer code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjqncOTxTKFeFe0ZsLBaSg.png" /><figcaption>Consumer code</figcaption></figure><h4>Kinesis or Kafka</h4><p>It’s very difficult to say which one is better, however from my point of view, onboarding kinesis is easy and has a great amount of flaxibitlyt from a programing point of view. We can use a python program to create a topic, producer and consumer. However, keep in mind that kinesis has data limitations. Your design consideration must consider the limitation very carefully, as once you have the topic created, you can not change it.</p><p>Github: <a href="https://github.com/ghoshm21/spark_book/tree/main/ch06_Clud_computation/Kinesis_dataStream">https://github.com/ghoshm21/spark_book/tree/main/ch06_Clud_computation/Kinesis_dataStream</a></p><p>TBD — Parsing the consumer data and run the ML on the data.</p><p>Please contact me for anything — contact@sandipan.tech</p><p>Resources:</p><ul><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kinesis.html#Kinesis.Client.get_records">Kinesis - Boto3 Docs 1.18.63 documentation</a></li><li><a href="https://stackoverflow.com/questions/22100206/consuming-a-kinesis-stream-in-python">Consuming a kinesis stream in python</a></li><li><a href="https://stackoverflow.com/questions/62887366/how-to-use-gzip-to-compress-json-data-in-python-program">how to use GZIP to compress JSON data in python program?</a></li><li><a href="https://docs.aws.amazon.com/code-samples/latest/catalog/python-kinesis-streams-kinesis_stream.py.html">kinesis_stream.py</a></li><li><a href="https://blog.sqreen.com/streaming-data-amazon-kinesis/">Streaming data with Amazon Kinesis - Sqreen Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f97ce3d316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Computations — Quick data analysis with AWS Athena, Glue and Databricks spark]]></title>
            <link>https://ghoshm21.medium.com/cloud-computations-quick-data-analysis-with-aws-athena-glue-and-databricks-spark-be34f7135bbf?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be34f7135bbf</guid>
            <category><![CDATA[databriks]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[athena]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 17:16:37 GMT</pubDate>
            <atom:updated>2025-12-02T11:04:22.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cloud Computations — Quick data analysis with AWS Athena, Glue and Databricks spark</h3><p>Throughout my carrier, I always had a situation that I had to fix failing production jobs. Most of the time, the debug involved analysis of input data to figure out the error in the raw data.</p><p>For the last ten years, I have also been doing data analysis to provide quick business insights. This often involves running a complex query on an extensive set of data.</p><p>Most of the time, we do not have access to the production environment to debug a job or install the required packages. It’s also advisable not to debug jobs in the production environment as it might have a negative performance impact or completely break the job.</p><p>We have been using a few tools to debug, mainly Hive, Presto, Tableau, etc. These tools are not always the best option as often it’s required to have custom code/ser-der/package need to be used for debugging falling jobs because of data issues. I like to use spark, however; the spark does not have a pretty GUI, which data analytics love. We can defiantly use iPython notebook or Zeppelin. But both tools required a considerable amount of time to set up. Often, these tools are not available in production.</p><p>So, I was looking for an alternative that can be set up quickly, have a pretty GUI, and are easily scalable.</p><p>I was looking into Cloud (AWS) and came across Athena and Glue. So I tried the use case. I have considered Twitter data (5.5GB and letter 20GB for scalability) for the input data, which I had collected last year. This data is complex enough and should be able to serve our test purpose.</p><p><strong>Athena:</strong></p><ul><li>Serverless, so no need to set up and manage the infrastructure</li><li>Supports standard SQL, so need to learn a new language</li><li>Store the data in S3 and use the same data for analysis in Athena. No need to pre-processing the data</li><li>Hive in the backend, so support all hive properties and have wide varieties of data support(CSV, JSON, ORC, Avro, and Parquet etc)</li><li>We can easily use hive serializer deserializer to parse custom data format</li><li>As this is a managed service the perforce might not be same over the time</li><li>External table — by default it creates an external table. You can not create an internal table, even if you change the table structure command. This is done to avoid accidental deletion of the table and dropping the entire data from S3</li><li>It saved every query we run in Athena in a temp/work dir under the user-specified s3 location. I think we need to have some mechanism to delete these dirs/files in regular intervals. Else this will spin into a monster eating all the S3 budget</li></ul><p>To test this service, I kept the input data in the S3 bucket. Then create an Athena table from the S3 bucket. I chose the data format like JSON and it asked me to enter the columns name manually. This is a challenging job for my use case as the JSON has over 300 columns. It’s challenging to enter 300 columns manually. I hoped the UI could parse the file(or first row as column name in CSV) to infer the schema. This could have been an excellent facility for creating a table with many columns. However, scanning files to infer schema can take longer and cost more if you have a sizeable amount of data. I’ve found writing queries manually is a better option than using the GUI.</p><p>I also noticed the GUI cannot run multiple queries together, like a script. This is ridiculous. If I wanted to run a script, then I must run one query at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkpnW9Nk0aIDL0HdUE7-5Q.png" /><figcaption>Fig 1: Athena with creating columns manually</figcaption></figure><p>I started looking for an alternative solution and came across AWS GLUE.</p><p><strong>GLUE</strong>:</p><ul><li>Serverless, so no need to set up and manage the infrastructure</li><li>It is a data integration/ETL/Metadata management tool, so it can be used in a wide range of use cases</li><li>Can read the data from S3, parse and load to Athena</li><li>Support wide varieties of data (CSV, JSON, ORC, Avro, and Parquet etc.)</li><li>Can schedule a crawler to get new data from pre-defined location, then parse and load to proper hive location or partition</li></ul><p>So I set up a GLUE crawler to get the JSON data to a hive table. Then use that table to query in Athena. However, GLUE did not parse the nested JSON like I was except. I could have written a hive query to parse the nested data and flat the structure. However, this would have taken more time and will quickly become unmanageable. Also, querying the table in Athena produced the below error. Looks like the data is not parsed correctly (I know this is a proper file as I had parsed this data before and used it for Machine Learning).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAmjYXITgHWowDm45Q7cKg.png" /><figcaption>Fig 2: Schema problem with table create by GLUE</figcaption></figure><p>I had used Databricks before and wanted to try this for the use case. Databricks have a free community edition and can be configured to read data from S3. The community edition has a data limit of 5GB. If we keep our data in S3, then this limitation will not apply here.</p><p>Once you log into the community edition, create a cluster. I chose the below configuration. This step will take 5–10 minutes to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HG9w5sDcrkWR27mRMNo-ng.png" /><figcaption>Fig 3: Creating Databricks community edition cluster</figcaption></figure><p>For the Databricks cluster to have read and write access to S3, we must have an IAM user/role having read and write access to s3. We need to have both reads and write as we want Databricks to write the output data to s3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lsiz2fSvIXKpPn5LIuEi0w.png" /><figcaption>Fig 4: IAM role page in AWS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCJCbATGMEo-R7qvOyuyCA.png" /><figcaption>Fig 5: IAM — policies in AWS</figcaption></figure><p>We can use the access id and key to read/write data from S3. Here is the code to do this.</p><blockquote>import url lib</blockquote><blockquote># unmount if already mounted</blockquote><blockquote># dbutils.fs.unmount(“/mnt/corona_s3”)</blockquote><blockquote># get the S3 mounted to the local DataBriks dir</blockquote><blockquote>access_key = “xxxxxxxxx”</blockquote><blockquote>secret_key = “xxxxxxxx”</blockquote><blockquote># parse the special char</blockquote><blockquote>encoded_secret_key = urllib.parse.quote(secret_key).replace(“/”, “%2F”)</blockquote><blockquote>aws_bucket_name = “sandipan-atena”</blockquote><blockquote>local_mount_name = “corona_s3”</blockquote><blockquote>dbutils.fs.mount(“s3a://%s:%s@%s” %(access_key, encoded_secret_key, aws_bucket_name), “/mnt/%s” %local_mount_name)</blockquote><blockquote># display the files</blockquote><blockquote>display(dbutils.fs.ls(“/mnt/corona_s3/corona/”))</blockquote><blockquote># run few sql</blockquote><blockquote>data_loc = “/mnt/corona_s3/corona/*.json”</blockquote><blockquote>data = spark.read.json(data_loc)</blockquote><blockquote>data.createOrReplaceTempView(“data”)</blockquote><blockquote>data.printSchema()</blockquote><blockquote># Query to get the data points</blockquote><blockquote>extract_data = spark.sql(“””select user.screen_name as user_screen_name,</blockquote><blockquote>user.location as user_location,</blockquote><blockquote>extended_tweet.full_text extended_tweet_full_text,</blockquote><blockquote>retweeted_status.user.screen_name retweeted_status_user_screen_name,</blockquote><blockquote>retweeted_status.text retweeted_status_text,</blockquote><blockquote>retweeted_status.extended_tweet.full_text retweeted_status_extended_tweet_full_text,</blockquote><blockquote>quoted_status.user.screen_name quoted_status_user_screen_name,</blockquote><blockquote>quoted_status.text quoted_status_text,</blockquote><blockquote>quoted_status.extended_tweet.full_text quoted_status_extended_tweet_full_text,</blockquote><blockquote>place.country place_country,</blockquote><blockquote>place.country_code place_country_code,</blockquote><blockquote>timestamp_ms</blockquote><blockquote>from data”””)</blockquote><blockquote># some sample data</blockquote><blockquote>extract_data.show(10,False)</blockquote><blockquote># Write to final data</blockquote><blockquote>extract_data.coalesce(2).write.mode(“Overwrite”).parquet(“/mnt/corona_s3/corona_extract/”)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_w5Dcf0v_CoFdNYkoEPnAw.png" /><figcaption>Fig 6: Running query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2k6JoxlLpLUGkkRhABApQ.png" /><figcaption>Fig 7: Query running with stages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02cnqP24s8FD-PgUktvu5Q.png" /><figcaption>Fig 8: Writing the output data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqyD7lQJYWONn6d2khNskA.png" /><figcaption>Fig 9: Final output</figcaption></figure><p>Once the output is ready, we can use the AWS GLUE crawler to crawl the data and create/update an Athena Hive table exposed to business users.</p><p>I have used Databricks’ community edition, which has no consistent performance due to its free nature. However, the paid version can easily replace the free version.</p><p>The entire code you can get from git location:- “<a href="https://github.com/ghoshm21/spark_book/tree/main/ch06_Clud_computation">https://github.com/ghoshm21/spark_book/tree/main/ch06_Clud_computation</a>”</p><p>Please contact ‘<a href="/service/mailto:contact@sandipan.tech">g</a>hoshm21@gmail.com’ for any suggestions or help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be34f7135bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark — Write single file per (hive) partitions]]></title>
            <link>https://ghoshm21.medium.com/spark-write-single-file-per-hive-partitions-3d0ee1559a80?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0ee1559a80</guid>
            <category><![CDATA[spark-optimization]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-performance]]></category>
            <category><![CDATA[spark-sql]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 19:19:10 GMT</pubDate>
            <atom:updated>2021-06-25T19:37:09.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark — Write single file per (hive) partitions.</h3><p>I had faced the problem of small files in Hadoop too many times during the spark ETL process, which is writing data to partitioned Hive tables.</p><p>Having too many small files in HDFS(Hive) will decrease general Hadoop performances and query performance.</p><p>Here is a solution I have been using for some time.</p><p>To illustrate the problem, I have used bellow data sets, which I had generated using the ‘Generate_Data’ script from the ‘Get_test_data’ section.</p><p><a href="https://github.com/ghoshm21/spark_book/tree/main/Get_test_data/Generate_Data">ghoshm21/spark_book</a></p><p>Records count of data points:</p><p>Customer = 143000000 Size = 30 GB</p><p>Order = 429010505 Size = 14 GB</p><p>Product = 38718 Size = 10 MB</p><p>order_product = 473966231 Size = 23 GB</p><p>I wanted to merge all the data points into a ‘customer-order-product’ table. This is a de-normalized table in the Hive. I wanted to keep the data partitioned by the order_date column.</p><p>I am using 6 nodes Hadoop cluster, in GCP, with ‘Hive 3.1.2’ and spark 3.1.1 and python 3.8 version.</p><p>Here is the schema of the tables —</p><blockquote>CREATE EXTERNAL TABLE IF NOT EXISTS CUSTOMER(</blockquote><blockquote>`row_id` INT,</blockquote><blockquote>`full_name` STRING,</blockquote><blockquote>`name` STRING,</blockquote><blockquote>`gender` STRING,</blockquote><blockquote>`address` STRING,</blockquote><blockquote>`email` STRING,</blockquote><blockquote>`telephone` STRING,</blockquote><blockquote>`city` STRING,</blockquote><blockquote>`state` STRING,</blockquote><blockquote>`birth_date` STRING,</blockquote><blockquote>`cust_id` STRING,</blockquote><blockquote>`user_create_date` STRING</blockquote><blockquote>)</blockquote><blockquote>ROW FORMAT DELIMITED</blockquote><blockquote>FIELDS TERMINATED BY ‘|’</blockquote><blockquote>STORED AS TEXTFILE</blockquote><blockquote>LOCATION ‘./data/spark_test_data_new/ghosh/customer’</blockquote><blockquote>;</blockquote><blockquote>CREATE EXTERNAL TABLE IF NOT EXISTS ORDERS(</blockquote><blockquote>`order_id` STRING,</blockquote><blockquote>`cust_id` STRING,</blockquote><blockquote>`order_date` STRING,</blockquote><blockquote>`shipping_date` STRING,</blockquote><blockquote>`delivery_date` STRING,</blockquote><blockquote>`shipping_company` STRING</blockquote><blockquote>)</blockquote><blockquote>ROW FORMAT DELIMITED</blockquote><blockquote>FIELDS TERMINATED BY ‘|’</blockquote><blockquote>STORED AS TEXTFILE</blockquote><blockquote>LOCATION ‘./data/spark_test_data_new/ghosh/order’</blockquote><blockquote>;</blockquote><blockquote>CREATE EXTERNAL TABLE IF NOT EXISTS ORDERS_PRODUCT(</blockquote><blockquote>`order_id` STRING,</blockquote><blockquote>`uniq_id` STRING,</blockquote><blockquote>`quantity` INT</blockquote><blockquote>)</blockquote><blockquote>ROW FORMAT DELIMITED</blockquote><blockquote>FIELDS TERMINATED BY ‘|’</blockquote><blockquote>STORED AS TEXTFILE</blockquote><blockquote>LOCATION ‘./data/spark_test_data_new/ghosh/order_product’</blockquote><blockquote>;</blockquote><blockquote>CREATE EXTERNAL TABLE IF NOT EXISTS PRODUCT(</blockquote><blockquote>`uniq_id` STRING,</blockquote><blockquote>`product_name` STRING,</blockquote><blockquote>`manufacturer` STRING,</blockquote><blockquote>`price` FLOAT,</blockquote><blockquote>`description` STRING</blockquote><blockquote>)</blockquote><blockquote>ROW FORMAT DELIMITED</blockquote><blockquote>FIELDS TERMINATED BY ‘|’</blockquote><blockquote>STORED AS TEXTFILE</blockquote><blockquote>LOCATION ‘./data/spark_test_data_new/ghosh/product’</blockquote><blockquote>tblproperties(‘skip.header.line.count’=’1&#39;)</blockquote><blockquote>;</blockquote><blockquote># CREATE FINAL TABLE</blockquote><blockquote>CREATE EXTERNAL TABLE IF NOT EXISTS CUSTOMER_ORDERS_PRODUCT(</blockquote><blockquote>`row_id` INT,</blockquote><blockquote>`full_name` STRING,</blockquote><blockquote>`name` STRING,</blockquote><blockquote>`gender` STRING,</blockquote><blockquote>`address` STRING,</blockquote><blockquote>`email` STRING,</blockquote><blockquote>`telephone` STRING,</blockquote><blockquote>`city` STRING,</blockquote><blockquote>`state` STRING,</blockquote><blockquote>`birth_date` STRING,</blockquote><blockquote>`cust_id` STRING,</blockquote><blockquote>`user_create_date` STRING,</blockquote><blockquote>`order_id` STRING,</blockquote><blockquote>`shipping_date` STRING,</blockquote><blockquote>`delivery_date` STRING,</blockquote><blockquote>`shipping_company` STRING,</blockquote><blockquote>`uniq_id` STRING,</blockquote><blockquote>`quantity` INT,</blockquote><blockquote>`product_name` STRING,</blockquote><blockquote>`manufacturer` STRING,</blockquote><blockquote>`price` FLOAT,</blockquote><blockquote>`description` STRING,</blockquote><blockquote>`total_sales` FLOAT</blockquote><blockquote>)</blockquote><blockquote>PARTITIONED BY (`order_date` DATE)</blockquote><blockquote>STORED AS ORC</blockquote><blockquote>LOCATION ‘./data/spark_test_data_new/ghosh/customer_orders_product’</blockquote><blockquote>tblproperties(‘orc.compress’=’SNAPPY’);</blockquote><blockquote>;</blockquote><p>I have kept the final table as partition by order date as most of the reporting and the ad-hoc query would be run based on the ‘order date’. Keeping the column as the partition column will improve the hive query performance.</p><p>ORC is a columnar file format that is very efficient for reading, writing and processing hive/Hadoop data. In ORC format, to select few columns, the data reader does not require to read the entire row; it can very efficiently read the individual columns mentioned in the query. So this is very fast for denormalized tables, where users select a set of columns rather than the entire columns set.</p><p><strong>Spark Process</strong></p><p>Here is the process in a nutshell.</p><ol><li>Read the data —</li></ol><blockquote>product = spark.read.table(“product”)</blockquote><blockquote>orders_product = spark.read.table(“orders_product”)</blockquote><blockquote>orders = spark.read.table(“orders”)</blockquote><blockquote>customer = spark.read.table(“customer”)</blockquote><p>2. Register as a temp table —</p><blockquote>product.createOrReplaceTempView(“product”)</blockquote><blockquote>orders_product.createOrReplaceTempView(“orders_product”)</blockquote><blockquote>orders.createOrReplaceTempView(“orders”)</blockquote><blockquote>customer.createOrReplaceTempView(“customer”)</blockquote><p>3. Create the merge data set from base tables —</p><blockquote>merge_data = spark.sql(“””select</blockquote><blockquote>cust.row_id ,</blockquote><blockquote>cust.full_name ,</blockquote><blockquote>cust.name ,</blockquote><blockquote>cust.gender ,</blockquote><blockquote>cust.address ,</blockquote><blockquote>cust.email ,</blockquote><blockquote>cust.telephone ,</blockquote><blockquote>cust.city ,</blockquote><blockquote>cust.state ,</blockquote><blockquote>cust.birth_date ,</blockquote><blockquote>cust.cust_id ,</blockquote><blockquote>cust.user_create_date ,</blockquote><blockquote>ord.order_id ,</blockquote><blockquote>ord.shipping_date ,</blockquote><blockquote>ord.delivery_date ,</blockquote><blockquote>ord.shipping_company ,</blockquote><blockquote>ordp.uniq_id ,</blockquote><blockquote>ordp.quantity ,</blockquote><blockquote>prod.product_name ,</blockquote><blockquote>prod.manufacturer ,</blockquote><blockquote>prod.price ,</blockquote><blockquote>prod.description ,</blockquote><blockquote>(prod.price * ordp.quantity) as total_sales ,</blockquote><blockquote><strong>cast(ord.order_date as date) as order_date</strong></blockquote><blockquote>FROM customer as cust</blockquote><blockquote>inner join orders as ord</blockquote><blockquote>on cust.cust_id = ord.cust_id</blockquote><blockquote>inner join orders_product as ordp</blockquote><blockquote>on ordp.order_id = ord.order_id</blockquote><blockquote>inner join product as prod</blockquote><blockquote>on prod.uniq_id = ordp.uniq_id</blockquote><blockquote>“””)</blockquote><blockquote>merge_data.createOrReplaceTempView(“merge_data”)</blockquote><p>4. Set the spark for dynamic partition —</p><blockquote>spark.conf.set(“hive.exec.dynamic.partition”, “true”)</blockquote><blockquote>spark.conf.set(“hive.exec.dynamic.partition.mode”, “nonstrict”)</blockquote><p>Without the above statements, the spark process will not be able to insert data in the portions.</p><p>5. Insert into the final table —</p><blockquote>spark.sql(“””insert overwrite table CUSTOMER_ORDERS_PRODUCT partition(order_date)</blockquote><blockquote>select</blockquote><blockquote>row_id,</blockquote><blockquote>full_name,</blockquote><blockquote>name,</blockquote><blockquote>gender,</blockquote><blockquote>address,</blockquote><blockquote>email,</blockquote><blockquote>telephone,</blockquote><blockquote>city,</blockquote><blockquote>state,</blockquote><blockquote>birth_date,</blockquote><blockquote>cust_id,</blockquote><blockquote>user_create_date,</blockquote><blockquote>order_id,</blockquote><blockquote>shipping_date,</blockquote><blockquote>delivery_date,</blockquote><blockquote>shipping_company,</blockquote><blockquote>uniq_id,</blockquote><blockquote>quantity,</blockquote><blockquote>product_name,</blockquote><blockquote>manufacturer,</blockquote><blockquote>price,</blockquote><blockquote>description,</blockquote><blockquote>total_sales,</blockquote><blockquote>order_date</blockquote><blockquote>from merge_data”””)</blockquote><p>Here is the capture of the number of partitions and the number of files per partition. This process has created 511400 files, almost 200 small files per partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1IDzdHiXVGqU6fVVTxZLg.png" /><figcaption>total number of partition dir (2558) and files(511400)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnAqpUZd7xsu4mhFbgBOfA.png" /><figcaption>Number of files(200) per partition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuEJEwVz5E-pjTcWwn7Gdg.png" /><figcaption>size of each file</figcaption></figure><p>The data set has 2557 unique ‘order_date’. So the final table will have 2557 partitions. I am using the default spark shuffle partition, which is 200. This means in every partition; we will have almost 200 files; in total, the spark generated 511400 small files. This is really bad for the name node and hive/spark process.</p><p>One way to solve the small files problem is to create single file par partitions. In this way, we will have only 2557 files instead of 511400.</p><p>To solve this problem, we can repartition the final data (merge_data DF in the code) by partition column. This will force the spark to re-shuffle the data and put all the same ‘order_date’ data to the same executor/partition. During the spark write operation, the executor will write the data to the particular hive partition. One downside is that as we are forcing the spark to do data shuffle, which can be time-consuming.</p><p>Here is the code.</p><blockquote><strong>merge_data_parti = merge_data.repartition(“order_date”)</strong></blockquote><blockquote>merge_data_parti.createOrReplaceTempView(“merge_data_parti”)</blockquote><blockquote>merge_data_parti = merge_data.repartition(“order_date”)</blockquote><blockquote>merge_data_parti.createOrReplaceTempView(“merge_data_parti”)</blockquote><blockquote>spark.sql(“””insert overwrite table CUSTOMER_ORDERS_PRODUCT partition(order_date)</blockquote><blockquote>select</blockquote><blockquote>row_id,</blockquote><blockquote>full_name,</blockquote><blockquote>name,</blockquote><blockquote>gender,</blockquote><blockquote>address,</blockquote><blockquote>email,</blockquote><blockquote>telephone,</blockquote><blockquote>city,</blockquote><blockquote>state,</blockquote><blockquote>birth_date,</blockquote><blockquote>cust_id,</blockquote><blockquote>user_create_date,</blockquote><blockquote>order_id,</blockquote><blockquote>shipping_date,</blockquote><blockquote>delivery_date,</blockquote><blockquote>shipping_company,</blockquote><blockquote>uniq_id,</blockquote><blockquote>quantity,</blockquote><blockquote>product_name,</blockquote><blockquote>manufacturer,</blockquote><blockquote>price,</blockquote><blockquote>description,</blockquote><blockquote>total_sales,</blockquote><blockquote>order_date</blockquote><blockquote>from merge_data”””)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opz8kka_094akjvHyqRK3w.png" /><figcaption>total number of partition dir (2558) and files(2557)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XehLsNaGV1KKteBNPzUi6w.png" /><figcaption>Number of files(one) per partition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZYrv53N0fvuohwsDYYPKg.png" /><figcaption>size of each file (23 MB)</figcaption></figure><p>Repartition by partition column should solve the problem!! We can not use coalesce as keeping the data under its own partition needs data to be shuffled. Coalesce will not help here. Also, keep in mind as you are pushing spark to have one spark partition per partitioned data, the performance of the spark job will degrade. This will become worse if you have skewed data. Bellow is the capture of the spark job from the SQL above with skewed data in the orders table for the date 2020–01–01. This date has 10 GB of orders data. This will significantly slow down the spark process and will generate an enormous amount of shuffle files. In my cluster, with the skewed data, above SQL did not run. It runs for 10 hours, creates 300 GB of shuffle file, then eventually fail. In my next article, I will discuss how to optimize spark for skewed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DYB5A0Av6yj1tOsWh8WLw.png" /><figcaption>Enormous shuffle file due to skewed data. check out spill to memory and disk.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkPIH0-WpZwrheMbVPQTGQ.png" /><figcaption>Fail due to skewed data</figcaption></figure><p>Please checkout the git location for the updated code — <a href="https://github.com/ghoshm21/spark_book">https://github.com/ghoshm21/spark_book</a></p><blockquote>Please email me for any feedback/comment/help — contact@sandipan.tech</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0ee1559a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Spark 3 on Windows 10]]></title>
            <link>https://ghoshm21.medium.com/how-to-install-spark-3-on-windows-10-3666c71b4733?source=rss-db159899ba8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3666c71b4733</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[windows-10]]></category>
            <dc:creator><![CDATA[Sandipan Ghosh]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 19:16:52 GMT</pubDate>
            <atom:updated>2021-03-10T19:16:52.500Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using spark for a long time. It is an excellent, distributed computation framework. I use this regularly at work, and I also have it installed on my local desktop and laptop.</p><p>This document is to show the installation steps for installing spark 3+ on Windows 10 in a sudo distributed mode.</p><p><strong>Steps:-</strong></p><p>1. Install WSL2</p><p>a. <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">https://docs.microsoft.com/en-us/windows/wsl/install-win10</a></p><p>2. Install Ubuntu 20.4 LTS from the Microsoft store.</p><p>3. Install the windows terminal form the Microsoft store. This step is optional. You can use PowerShell or MobaXterm</p><p>4. Fire up the Ubuntu from WSL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*GNnx2el9meYNJVzzF-U9EA.png" /><figcaption>open Ubuntu terminal from windows terminal</figcaption></figure><p>5. Once logged in, then go to home dir <em>“ cd ~ ”</em></p><p>6. For spark, we need</p><p>a. Python3</p><p>b. Java</p><p>c. Latest Scala</p><p>d. Spark with Hadoop binary zip file</p><ol><li>Let’s download and install all the prerequisite</li><li>install python</li></ol><blockquote>sudo apt-get install software-properties-common</blockquote><blockquote>sudo apt-get install python-software-properties</blockquote><ol><li>install Java (open JDK)</li></ol><blockquote>sudo apt-get install openjdk-8-jdk</blockquote><ol><li>Check the java and javac version</li></ol><blockquote>java -version</blockquote><blockquote>javac -version</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*yYe9-55IVP_olg0W.png" /><figcaption>Check the Java and Javac version</figcaption></figure><ol><li>Install Scala</li><li>get scala binary for Unix</li></ol><blockquote>wget <a href="https://downloads.lightbend.com/scala/2.13.3/scala-2.13.3.tgz">https://downloads.lightbend.com/scala/2.13.3/scala-2.13.3.tgz</a></blockquote><blockquote>tar xvf scala-2.13.3.tgz</blockquote><ol><li>edit bashrc file to add Scala</li></ol><blockquote>vi ~/.bashrc</blockquote><ol><li>add these lines in the end</li></ol><blockquote>export SCALA_HOME=Path-where-scala-file-is-located#/root/scala-2.13.3</blockquote><blockquote>export PATH=$PATH:$SCALA_HOME/bin</blockquote><ol><li>Once done, save and close the file</li><li>Let&#39;s check the scala version</li></ol><blockquote>source ~/.bashrc</blockquote><blockquote>scala -version</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*uwxSOSMYH88gOGacYyiM6Q.png" /><figcaption>check the Scala Version</figcaption></figure><ol><li>get the spark package</li><li>I downloaded the spark from the source</li></ol><blockquote>wget “<a href="https://www.blogger.com/blog/post/edit/4570874966255939448/2337034178408735777#">https://archive.apache.org/dist/spark/spark-3.1.1/spark-3.1.1-bin-hadoop3.2.tgz</a>”</blockquote><blockquote>tar xvf spark-3.1.1-bin-hadoop3.2.tgz</blockquote><blockquote>vi ~/.bashrc</blockquote><blockquote>export SPARK_HOME=”/home/sandipan/spark-3.1.1-bin-hadoop3.2&quot;</blockquote><blockquote>export PATH=$PATH:$SPARK_HOME/bin</blockquote><ol><li>Once done, save and close the file, then run the below command to load the profile</li></ol><blockquote>source ~/.bashrc</blockquote><ol><li>Start Spark Services</li></ol><blockquote>cd $SPARK_HOME</blockquote><ol><li>start the master Server</li></ol><blockquote>./sbin/start-master.sh</blockquote><ol><li>once you start the master server you will get a message saying it had started.</li><li>you can see the spark status in the web console of master using local <a href="http://localhost:8080/">http://localhost:8080</a></li><li>there you will see the master url</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjnOFa2qxgIj-Zd4pohRXA.png" /><figcaption>Get the master URL</figcaption></figure><ol><li>Mine looks like:- “spark://LAPTOP-7DUT93OF.localdomain:7077”</li><li>we can start a slave using bellow command</li></ol><blockquote>SPARK_WORKER_INSTANCES=3 SPARK_WORKER_CORES=2 SPARK_WORKER_MEMORY=7G ./sbin/start-worker.sh spark://LAPTOP-7DUT93OF.localdomain:7077</blockquote><ol><li>SPARK_WORKER_INSTANCES = how many worker instances you want to start</li><li>SPARK_WORKER_CORES = how many cores per instances you want to give. Generally, I give 1 core.</li><li>SPARK_WORKER_MEMORY = Memory per worker. Be very careful with this parameter. My laptop has 32 GB of memory, so I keep 3GB to 4GB for Windows, 2 GB for the driver program and the rest for the worker node.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsAzibYW86OyN7ZBt8hxqg.png" /><figcaption>Started worker nodes</figcaption></figure><ol><li>open the pyspark shell</li></ol><blockquote>SPARK_HOME/bin/pyspark — master spark://LAPTOP-7DUT93OF.localdomain:7077 — executor-memory 6500mb</blockquote><blockquote>SPARK_HOME/bin/spark-shell — master spark://LAPTOP-7DUT93OF.localdomain:7077 — executor-memory 6500mb</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WZB5F8j8mg8xJAmWPbncQ.png" /><figcaption>Starting a pyspark shell</figcaption></figure><ol><li>to stop all the workers</li></ol><blockquote>SPARK_WORKER_INSTANCES=3 SPARK_WORKER_CORES=2 ./sbin/stop-worker.sh spark://LAPTOP-7DUT93OF.localdomain:7077</blockquote><ol><li>OR TRY</li></ol><blockquote>kill -9 $(jps -l | grep spark | awk -F ‘ ‘ ‘{print $1}’)</blockquote><p>Running a few codes</p><p>let&#39;s load a CSV file with sales data and run a count check</p><blockquote>sales_data = spark.read.csv(‘/mnt/e/Training_Data/5m-Sales-Records/5mSalesRecords.csv’).option(“header”, “true”)</blockquote><blockquote>sales_data.count()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b4Y1iiPqbYrZWemTT370g.png" /><figcaption>running the job</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQZ3_Ar2r8l03vyoZbjuSw.png" /><figcaption>Checking the count</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkTiZ4c0ajkn2iv7X81Z5g.png" /><figcaption>worker nodes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyyKF9kfC2jq9P_pKoUa2w.png" /><figcaption>Some of my jobs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcQAQIfjNMpwoEtlE3z-nA.png" /><figcaption>Executor view</figcaption></figure><p>Conclusion:-</p><p>This is an extremely easy way to use the spark on your laptop or desktop running windows 10.</p><p>We can follow the same steps for Ubuntu or any other Linux distrubutions.</p><p>You can use docker for the same approach and just spin a pre-build docker file.</p><p>Please do drop an email for any suggestion or help</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3666c71b4733" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>