<?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 Hari Krishnan on Medium]]></title>
        <description><![CDATA[Stories by Hari Krishnan on Medium]]></description>
        <link>https://medium.com/@sherlockcodes?source=rss-ad99d14d0986------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YCKZH0MYRPkYDvZkdnWD2g.jpeg</url>
            <title>Stories by Hari Krishnan on Medium</title>
            <link>https://medium.com/@sherlockcodes?source=rss-ad99d14d0986------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:56:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sherlockcodes/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[Darpan — Behavioural product for retail traders]]></title>
            <link>https://medium.com/@sherlockcodes/darpan-behavioural-product-for-retail-traders-e41056892c14?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/e41056892c14</guid>
            <category><![CDATA[human-behavior]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[pshychology]]></category>
            <category><![CDATA[startups-in-india]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 11:22:05 GMT</pubDate>
            <atom:updated>2026-10-14T11:22:05.362Z</atom:updated>
            <content:encoded><![CDATA[<p>I became interested in a problem that many retail traders face: repeating the same mistakes despite knowing better.</p><p>I saw this pattern in my own experience. After a big win, I’d become overconfident and give back some of what I’d earned. After a loss, I’d try to recover it, often making things worse. And when I should have stopped trading, I’d find another reason to enter one more trade.</p><p>The frustrating part wasn’t just the money I lost. It was how easily I fell into the same patterns, even when I knew what I should have done differently.</p><p>I kept looking at my P&amp;L to understand what went wrong. But the numbers only told me how much I’d made or lost, not why I’d made the decisions that led to those outcomes.</p><p>That got me thinking: what if the problem wasn’t always my strategy, the market, or the latest headline? What if my own behaviour was playing a bigger role than I realised?</p><p>The more I reflected on my experience, the more I became interested in the behavioural side of trading. Overconfidence after a winning streak, revenge trading after a loss, impulsive entries, and overtrading are all familiar struggles for retail traders. Yet, most trading platforms focus on charts, indicators, order execution, and financial performance — not the behavioural patterns behind our decisions.</p><p>Even when we review our weekly P&amp;L, we tend to see a collection of green and red blocks. We can identify our profitable and losing days, but it’s much harder to understand the emotions, impulses, and decisions that shaped them. Did we follow our plan? Did we take unnecessary risks after a loss? Did a profitable trade reward a bad decision and encourage us to repeat it?</p><p>These questions rarely have straightforward answers, and the patterns behind them can be uncomfortable to confront.</p><p>I realised I wanted something that could help me look beyond the numbers and recognise the behaviours I kept repeating.</p><p>That’s what led me to build <strong>Darpan</strong>.</p><p><em>Darpan</em> means <em>mirror</em> in Sanskrit. The idea was to create a product that reflects a trader’s behaviour back to them — not just their financial results. Sometimes, the biggest obstacle isn’t Trump, SEBI, or the market. It’s our own behaviour — and our inability to recognise the patterns behind our decisions</p><p>Darpan started with a simple question: <strong>What if traders could understand not just how they performed, but why they kept making the same mistakes?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMNK1YKeGzPcgo-9dSu2sA.png" /></figure><h3>What Darpan Actually Does</h3><p>Darpan is built around a simple idea: your trading results tell only part of the story. To understand why you keep repeating certain mistakes, you need to look at the decisions behind those results.</p><p>I explored this idea through behavioural analysis, weekly trading audits, and features that evolved with user feedback.</p><h3>Capturing the Behaviour Behind the Trades</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwjZ5dmhcsGPL9_E1kNGfA.png" /></figure><p>A P&amp;L heatmap tells you where you made or lost money. Darpan explores what happened between those numbers and the decisions that produced them.</p><p>Why did you enter before your setup was confirmed? Why did an intraday trade become an overnight position? Why did you take five trades when your plan allowed only three? These are the questions that help distinguish an isolated loss from a recurring behavioural pattern.</p><p>Because the heatmap never asks the real questions. It doesn’t ask why you entered ten minutes before your setup was even confirmed, just because you didn’t want to “miss the move.” It doesn’t ask why a trade that was supposed to be intraday quietly became a carry-forward position — not because your thesis changed, but because you couldn’t stomach booking the loss, so you told yourself “let’s just see how it opens tomorrow.” It doesn’t ask why you took your fifth trade of the day when your plan said three, or why the trade right after a loss always seems to be bigger than the one before it.</p><p>I know these patterns because I’ve lived every one of them.</p><p>Early entry isn’t a technical mistake — it’s impatience wearing a chart pattern as a disguise. Carry-forward isn’t a strategy — it’s hope doing the job that a stop-loss was supposed to do. Overtrading isn’t conviction — it’s restlessness that’s mistaken activity for edge. And revenge trading isn’t even about the market anymore — it’s you, arguing with your own ego, trying to make the last candle apologize to you.</p><p>None of this shows up as a line item on your P&amp;L. It shows up as a pattern — the same mistake, dressed differently, every week. And until someone points it out to you in plain language, you’ll keep calling it ‘bad luck’ instead of what it actually is: a behaviour you’re capable of changing, once you can see it.</p><h3>The Weekly Audit — the report card that doesn’t flatter you</h3><p>Once a week, Darpan looks at everything — every order, every rupee of P&amp;L, every journal entry, how the market actually behaved that week — and writes you a verdict. Not a motivational recap. A forensic one.</p><p>It’ll tell you your “behavioral archetype” for the week, in the same cold tone a risk officer would use on a desk, not a coach. It’ll show you things your P&amp;L screen physically cannot show: that your biggest winning trades this week had your <em>worst</em> discipline scores — which sounds like a compliment until you realize it means you got paid for a mistake and your brain just filed it as “this works now.” It’ll tell you if 100% of your weekly loss came from one instrument you keep returning to. It’ll hand you three rules for the next week — not generic ones, ones pulled directly from what actually broke this week: a no-trade window right after market open if that’s where you keep bleeding, a hard cap on overnight exposure if your carry-forwards are the leak.</p><p>It’s not there to cheer you up. It’s there to be the version of you that remembers last Tuesday, when the rest of you would rather not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p1pdRki35qFYF3JcWCLFQ.png" /></figure><h3>Evolving Darpan with User Feedback</h3><p>With AI making experimentation faster, I could explore ideas that went beyond the original product. Based on user feedback and suggestions, I gradually expanded Darpan with features such as risk profiling to help traders understand their behavioural tendencies, forensic reports that examine trading activity alongside broader market signals like crude oil and USD/INR movements, and personal challenges to encourage more disciplined trading.</p><p>Each feature explored a different way to help traders understand their decisions, recognise recurring patterns, and build better habits.</p><h3>What building Darpan taught me</h3><p>Building Darpan taught me that identifying a real problem is only the beginning.I knew the problem personally. I built a product around it. I spoke to users, collaborated with a trading influencer, and launched a free cohort. For a while, it seemed promising. But getting people to try a product and getting them to use it consistently are two very different things.</p><p>The biggest unanswered question isn’t whether trading behaviour can be analysed. It’s whether traders will keep coming back to confront patterns they’d often rather ignore — and whether that feedback can help them change. I’m still figuring out what comes next. One possibility is to open-source Darpan so others can experiment with it, improve it, and see whether the idea resonates beyond my initial cohort.</p><p>If you’re a retail trader who has struggled with overtrading, revenge trading, or giving back your profits, I’d love to hear from you.</p><p>Would you use a tool that analysed not just your trading results, but the behaviour behind them? What would make you come back to it every week?</p><p>Curious? <a href="https://darpanhq.in/">https://darpanhq.in/</a></p><p>#Trading #Startups #Investing #Psychology</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e41056892c14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing E-commerce orders using Heat Maps]]></title>
            <link>https://medium.com/zefo-tech/visualizing-e-commerce-orders-using-heat-maps-b2e0dfdd79e5?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e0dfdd79e5</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 08:35:17 GMT</pubDate>
            <atom:updated>2019-02-07T07:05:21.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>Visualizing E-commerce Orders using Heat Maps</h3><p>In a Big Data world, Numbers are interesting. But what’s more interesting than just numbers? Visualization. In this blog post, I am going to share how I used a heat map to visualize orders we processed in the year 2018.</p><p>I have used Jupyter-notebook, pyspark, and google’s gmaps API for this experiment. If you’re using Jupyter notebook already and want to explore the visualization of heatmap for your own use case. You can get started with below commands to install gmaps library and enable all extensions required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b6a75e92b9da5a283bfa0e83a3c686/href">https://medium.com/media/96b6a75e92b9da5a283bfa0e83a3c686/href</a></iframe><p>I have exported a few selected columns from the order database for this experiment. This is how it looks before data cleanup with out some sensitive data like payment mode, email ids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*DwiWe1nTYFlWU5AL-bdVmg.png" /></figure><p>After cleaning up incomplete data and extracting features from not so obvious attributes. This is how it looks like after initial processing of the data. For example, extracting category from product id and month from order time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*YhRbtXj07iNoitOxzYgeFA.png" /></figure><p>If you have noticed, Order table has only zip codes. Obviously, We need latitude and longitude information for heat map visualization. You can get location information from below site. I find this one reliable to some extent.</p><p><a href="http://www.geonames.org/export/zip/">GeoNames</a></p><p>I have written a simple python wrapper function to get latitude &amp; longitude given a list of zip codes. And, then retrieved all zip codes from the delivered orders and used them to visualize a heat map of orders throughout India like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa5f70315483b3d6fb41c05536942449/href">https://medium.com/media/aa5f70315483b3d6fb41c05536942449/href</a></iframe><p>We deliver products across all categories including furnitures on selected cities like Bangalore, Mumbai, Hyderabad, Delhi, Gurgaon and Noida. And, we deliver Mobile &amp; TV in selected zip codes across India. Which can be clearly seen in the below heat map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AIoz7-oZWQOweQJPRtRlhQ.png" /></figure><p>You can play around with max_intensity and point_radius parameters in heatmap_layer function and visualize heat map as per your need. When you have lesser data points, keep max_intensity higher will help to visualize better.<br>Now I want to visualize orders in at Bangalore. It can be done with the help of passing two more parameters zoom_level and center to <em>gmaps.figure</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ymwT7v9MZvu92uzU6h7xWA.png" /></figure><p>Both are Optional parameters. But when one specified other parameter is mandatory to be passed. Zoom level can be between 0 to 21. You can pass higher zoom level value to visualize orders in the street level. You can zoom in or out always. Center parameter takes a tuple of latitude and longitude where initial focus should be.</p><p>Let’s make it a little more interesting by adding an interactive control in jupyter notebook. It can be done by passing your function name and other parameters required for a given function in the jupyter interactive function which is available under ipywidgets library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*QXhiWkB7lGDjaWrmMHO_cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*vTHbxlxGKBXblDUlkHKaqw.png" /></figure><p>Cool. Isn’t??</p><h4>Conclusion:</h4><p>Heat maps come very handy to answer for some of business questions like below:</p><ol><li>In case of eCommerce company, You might be interested to know from where the majority of your customers buying your product.</li><li>Business or Sales teams can focus more on the region which they expected to be more sales, but no sales or lesser than expected sales.</li><li>If you want to open new experience center/store, heat map can help you make data backed decisions instead of taking heuristic approach.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e0dfdd79e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zefo-tech/visualizing-e-commerce-orders-using-heat-maps-b2e0dfdd79e5">Visualizing E-commerce orders using Heat Maps</a> was originally published in <a href="https://medium.com/zefo-tech">GoZefo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Multiple Servers using ClusterSSH!]]></title>
            <link>https://medium.com/@sherlockcodes/manage-multiple-servers-using-clusterssh-e9671aa1c534?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9671aa1c534</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Thu, 13 Dec 2018 11:32:56 GMT</pubDate>
            <atom:updated>2018-12-15T11:00:44.500Z</atom:updated>
            <content:encoded><![CDATA[<h3>Manage Multiple Servers like a Boss using ClusterSSH.</h3><p>If You’re someone who often need to perform some task or execute same command on multiple remote servers through SSH. Then, cssh ( or ClusterSSH) is your friend!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-jkF8ifkfU3TSBdEgpyBXA.jpeg" /></figure><p>For example, If system logs are not centralized and you have to ssh into all servers one by one and debug the logs, It will get tedious when there are multiple servers.</p><p>These can be solved by just two steps using cssh.</p><ol><li>Login: cssh user website</li><li>grep keyword /path/to/log/file.</li></ol><h4>Installation:</h4><p>You spare no effort in installing ClusterSSH on Ubuntu. A simple<em> sudo apt-get install clusterssh</em> will install it and all its dependencies.</p><h4>Configuration:</h4><p>Once installed, ClusterSSH can be configured via global configuration file /etc/clusters/ or under your user’s home directory .clusterssh/config. I choose the latter. ClusterSSH defines clusters as a group of machines you would like to perform some actions. Keeping that in a mind, you enumerate your clusters at the top of the file in a “clusters” block, and then you describe each cluster in a separate section below.</p><p>for example, I have got two clusters. One to handle website requests and another one to handle all website apis. Then, Configuration will look something like below:</p><blockquote><em>clusters = website backend</em></blockquote><blockquote><em>website = ip1 ip2</em></blockquote><blockquote><em>backend = ip1 ip2 ip3 ip4</em></blockquote><p>After that, You can create a tag for username at which you use to login at the end of config file.</p><blockquote>user = sherlock</blockquote><p>Then, You either require password or pem file to ssh into the machine. if you have pem file , you can alternate ssh_args in .clusterssh file like below:</p><blockquote>ssh_args = -i /path/to/your/pem_file</blockquote><p>Putting it all together. You can finally cssh into cluster you want like below:</p><blockquote>cssh user backend</blockquote><p>Voila! all four machines will be opened separately in four different terminals. You can enter the command you want to execute in parent terminal or click on server you want to execute command only in that. As simple as that.</p><p>But, now you want to execute particular command across all clusters. You can do so by creating another meta cluster tag like below:</p><blockquote>all = website backend</blockquote><p>Which means, you can ssh into all servers from both website and backend clusters by below command:</p><blockquote>cssh user all</blockquote><p>Thanks for reading. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9671aa1c534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What It’s like to work with great Product Managers.]]></title>
            <link>https://medium.com/@sherlockcodes/what-its-like-to-work-with-great-product-managers-5f49cb51252c?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f49cb51252c</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[startup-life]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 12:58:30 GMT</pubDate>
            <atom:updated>2018-12-12T17:42:20.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Product managers are the silent super heroes for any startup. They work across departments, make tough calls, work long hours, and attend multiple meetings in a day. During the initial days of my career, I thought product managers are just for creating tasks and following up with the team to get things done. They are responsible for success, or failure of a product, or you can say the company itself. I am going to share some incidents where I felt a need to write a blog about working with great PMs.</p><h4><strong>Staying on top of things:</strong></h4><p>If you’re a Software Engineer like me, you know how difficult it is to make someone understand why the system behaving like this instead of intended behavior in layman terms. A language which Developers speak is languages of extraterrestrial beings for marketeers and other departments. This is where PMs come to rescue as saviors. There are times where I felt little difficult to make other department managers understand the root cause of the issue before actually solving it. But It never happened with PMs. They just don’t stop by listening, they also come with a solution to solve the issue in the best possible way. They achieve this by staying on top of things always. Be it either in process or technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*zJClUqpqUVimQrpnbB9qxQ.gif" /></figure><h4>Making things happen:</h4><blockquote>Product management is all about making things happen.</blockquote><p>If there is something Product Managers are very good at doing, this comes on top of it. They know how to make things happen. Be it sprinting for a small tasks or running full marathon for big product release. Starting from Product Requirement Document(PRD) , UI/UX discussions, Splitting up tasks, Following up with Tech, Training Operations team and till sending out release notifications. Most of their day goes in meetings, follow-ups and writing documentations. Don’t be surprised If you see their calendar blocked for their lunch ;)</p><blockquote>If you ask me, Every Software Engineer should have qualities of Product Manager.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f49cb51252c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cohort Analysis Using Apache Spark.]]></title>
            <link>https://medium.com/@sherlockcodes/cohort-analysis-using-apache-spark-4f552c25f9a?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f552c25f9a</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[cohorts]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[cohort-analysis]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 11:49:00 GMT</pubDate>
            <atom:updated>2018-08-07T00:43:16.007Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Note: This is just an experiment to figure out customers from which marketing medium like Google, Facebook, Email, SMS have more retention rate and less churn rate percentage.</strong></p><p>A “<strong>C</strong>ohort” is a group of people that share a certain characteristics. <em>Usually, but not always.</em> Practice of studying the activities or habits of specific cohorts over a set period of time is called Cohort Analysis. Usually, Most marketers prefer a month by month analysis over others. But, It can be performed week or day level as well. I choose week as time metric for this experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6PY5rmcVvE0ZiIArLXUx1A.gif" /></figure><p>The Outcome of the analysis can be used to spot the patterns or changes in customer behaviour throughout their journey and why there is a change by comparing result with marketing events calendar. It is actually more of a prediction than analysis. E-commerce companies makes use Cohort Analysis to figure how the brand is performing over a period of time and which Cohort (Age 25 -30 group or Bangalore city customer) group are most valuable to their brand.</p><p>How Cohort Growth metrics stands out from normal Vanity metrics like number of new sessions is that, it will help marketers make business decisions. Problem with Vanity metrics is not just about waste of time analyzing it. It can actually mislead business decisions sometimes. For instance, If the number of new sessions goes up, Is it good that new users visit your site? Or Is it a bad thing that returning users retention rate is going down?</p><blockquote>A million guys walk into a Sillicon Valley bar. None of them buy anything. The bar is declared a rousing success. — Anonymous, Quora</blockquote><h4><strong>Apache Spark:</strong></h4><p>Apache Spark is a Unified analytics engine for large-scale data processing. Runs roughly 10X to 100X faster than a Hadoop MapReduce because of In-memory computation and other spark’s core components like Catalyst Query Optimizer, <strong>D</strong>irected <strong>A</strong>cyclic <strong>G</strong>raph scheduler and its Physical Execution Engine. I will be discussing about it in detail in my upcoming blogs. In the meantime, don’t hesitate to refer the documentation for each <a href="https://databricks.com/blog/2015/04/13/deep-dive-into-spark-sqls-catalyst-optimizer.html">[1]</a>, <a href="https://data-flair.training/blogs/dag-in-apache-spark/">[2]</a>, [3].</p><p>There are two core abstractions in spark needs to be discussed before diving into an implementation aspect of this analysis. One is <strong>R</strong>esilient <strong>D</strong>istributed <strong>D</strong>atasets (RDD) and another one is Data Frames.</p><h4><strong>R</strong>esilient <strong>D</strong>istributed <strong>D</strong>atasets (RDD):</h4><p>A Resilient Distributed Dataset (RDD), the basic abstraction in Spark. Represents an immutable, partitioned collection of elements that can be operated on in parallel. These entities exist in memory and by their very nature are immutable. Due to its immutability nature, new RDD will be created when some transformation applied to it. If there is any failure in transformation or action on RDD during the execution phase, It is possible to roll back to previous functioning state and helps to perform the same action in a different node to achieve fault tolerance.</p><h4><strong>Data Frames:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu0y1tPPOPQ14Ww14odO4Q.png" /></figure><p>RDD by nature don’t have schema attached to it, but they can be extended with help of DataFrames. Data Frames contain schema functionality to the dataset it contains, which helps in handling structured data set. It is relatively faster then RDD since it has more information about dataset it holds. Let’s get into action now.</p><p>I had exported six weeks worth of signed-in users events which comes roughly around two million records from our events database to perform cohort analysis on it to figure out which marketing medium performs better in terms of retaining return users.</p><pre>userId,eventType,productId,eventTime<br>26309c83–19e7, WISHLIST, 184061,1527813154155<br>fc07ec53-ebfe, PRODUCT_VIEW, 162654,1527813154200<br>82b73ce3-e5c0, PRODUCT_VIEW, 183104,1527813163406<br>26309c83–19e7, WISHLIST, 184061,1527813169063<br>82b73ce3-e5c0, PRODUCT_VIEW, 183104,1527813176444<br>2d1c7da8–6967, PRODUCT_VIEW, 184746,1527813186410<br>26309c83–19e7, WISHLIST, 184061,1527813187331<br>20d41d6b-51dc, UTM_PARAMS, utm_source:sms,1527837139873</pre><h4>Creating Spark Session and Data Frame:</h4><p>Spark Session provides a single point of entry to interact with the underlying Spark functionality and allows programming Spark with DataFrame and Dataset APIs. In order to use APIs of SQL, HIVE, and Streaming, no need to create separate contexts as Spark Session includes all the APIs.</p><pre>spark = SparkSession.builder.<br>                     appName(&quot;cohort&quot;).<br>                     config(&quot;spark.some.config.option&quot;,&quot;cohort&quot;).<br>                     getOrCreate()<br>df = spark.read.format(“csv”).<br>                option(“header”, “true”).load(file_path)</pre><p><strong>Join Product View Events and Marketing Events:</strong></p><p>To get customers who are all viewed product from marketing medium, I’ve created two Data frames using below, one to store View actions and another one to store UTM source events. By joining both data frames using common user Ids, We created new Data Frame which now contains all product view events with a corresponding marketing medium source.</p><pre>track_events = df.where(df[&quot;eventType&quot;] == &quot;UTM_PARAMS&quot;)<br>view_events = df.where(df[&quot;eventType&quot;] == &quot;PRODUCT_VIEW&quot;)<br>df1 = track_events.alias(&#39;df1&#39;)<br>df2 = view_events.alias(&#39;df2&#39;)<br>track_plus_view_events = df1.join(df2, df1.userId ==       df2.userId).select([&#39;df1.productId&#39;, &#39;df2.userId&#39;, &#39;df2.eventTime&#39;])</pre><pre>cohort = track_plus_view_events.rdd.map((lambda x: (removeUtmParam(x[&quot;productId&quot;]), x[&quot;userId&quot;], getCohortGroupId(int(x[&quot;eventTime&quot;]))).filter((lambda x: &quot;utm_source&quot; in x[&quot;productId&quot;]))))</pre><p>Spark does something called Lazy Evaluation, Which means all transformation will be applied only when some actions like Show(), take(), count() , write() triggered on RDD. Till then, DAG scheduler will keep working on optimizing what job it needs to execute to reach the action it has been asked to do. If you look at the last line of the above code snippets, map is applied first and then filter. But DAG scheduler in Spark is smart enough to apply filter first on RDD to reduce the number of records to be processed for mapping.</p><h4>Partitioning Cohorts:</h4><p>Time to create Cohorts based on Marketing medium sources like Google, Facebook, SMS, email.</p><pre>cohort_df = cohort.toDF([&quot;source&quot;, &quot;userId&quot;, &quot;cohortId&quot;])<br>cohort_df.write.partitionBy(&quot;source&quot;).csv(&quot;cohorts&quot;)</pre><p>When write action is triggered, all the transformation applied on RDD will be processed as per logical execution plan. Once it is partitioned by source, we can see a different folder for each source like below. Once all sources are partitioned like below, we can divide each source by week by week and just compare who are in the first week are still returning back in an upcoming week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGu7_dRQJSIalqhimIf3BQ.png" /></figure><h4>Cohort Result table:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F27abb98f4b&amp;dntp=1&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F27abb98f4b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="340" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c0626793b60294c023feae45b2c21ad/href">https://medium.com/media/8c0626793b60294c023feae45b2c21ad/href</a></iframe><h4>Some Key Take Aways:</h4><ol><li>Unsurprisingly, there is a big drop in user retention of the SMS medium from second week itself. Considering user mostly won’t usually sign in on the mobile website.</li><li>Churn rate from Email and Criteo medium is gradually reducing unlike others. Which is considerably better compared to other mediums.</li></ol><h4>More where this came from</h4><p>This story is published in <a href="http://blog.usejournal.com/">Noteworthy</a>, where thousands come every day to learn about the people &amp; ideas shaping the products we love.</p><p>Follow our publication to see more product &amp; design stories featured by the <a href="https://usejournal.com/?utm_source=usejournal.com&amp;utm_medium=blog&amp;utm_campaign=guest_post">Journal</a> team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f552c25f9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should start doing RCA?]]></title>
            <link>https://medium.com/@sherlockcodes/why-you-should-start-doing-rca-3d16c51f1a06?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d16c51f1a06</guid>
            <category><![CDATA[root-cause-analysis]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Thu, 16 Nov 2017 10:24:15 GMT</pubDate>
            <atom:updated>2019-03-29T05:20:59.712Z</atom:updated>
            <content:encoded><![CDATA[<p>I have recently moved to a start-up a month ago. During one of team meetings, my CTO kept asking for RCA.. RCA.. I was like, what is RCA?! I thought of not asking so that I don’t look stupid not knowing it in front of other peers. But, Out of curiosity, I have gone ahead asked “What’s RCA?!”. And he replied, “<strong>R</strong>oot <strong>C</strong>ause <strong>A</strong>nalysis”.</p><p>I have analyzed the root cause of a lot of issues in the past. But without knowing the proper RCA format and how it should be done. You should be familiar with the word “Quick fix”. Oh Yeah! You apply fixes to fix the fix you applied last week. Later, that will also break after one or two weeks. Everyone would have done that in the past.</p><p>Now, I’m going to share How RCA will solve this, How RCA should be done and Why you should be doing it from now on.</p><p>What is Root Cause?</p><blockquote>The root cause is the actual cause of a specific problem or set of problems, and when that cause is removed, it prevents the final undesirable effect from occurring.</blockquote><p>What is RCA?</p><blockquote>Root cause analysis (RCA) is a problem-solving method which is used to pinpoint the exact cause of a problem or event.</blockquote><p>I’ll try to explain how RCA can look like with some simple issues I faced.</p><h4>RCA 1 : 503 Service Unavailable</h4><p>What happened?<br><em>503 — Service Unavailable in one of API micro service.</em></p><p>Why it happened?<br><em>Lot of product API calls taking lot of time to process.</em></p><p>Why that happened?<br><em>We’re calling product cache clean API when product catalogue get refreshed for every customer.</em></p><p>Why that happened?<br><em>Clearing product cache entries through API made server to not accept new API calls.</em></p><p><strong>Quick Fix:</strong></p><ul><li><em>Stopped making API calls to clear cache entries.</em></li><li><em>Moved redis.keys() to redis.scan_iter() implementation</em></li></ul><p><strong>Proposed Solution:</strong></p><ul><li><em>Instead of scanning all keys. Put all keys to be deleted in SADD and SMEMBERS to get keys to be deleted.</em></li></ul><p><strong>Estimated ETA:</strong></p><p><em>2–3 days</em></p><p>Let’s say you’re not doing RCA. What could have just happened? You would’ve stopped at quick fix and moved on to a next task/bug in your bucket. Time bomb is not diffused yet. It’s still there. Just that, you extended the timer. It can blow up anytime. <strong>Anytime</strong>.</p><blockquote>Tick… Tick… Tick…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*m_7eTpEouz4a1R0JYNZdFA.jpeg" /><figcaption>HUGE BLOW..</figcaption></figure><p>There are lot of templates available online for elaborated RCA templates. But I feel It’s better to keep it as simple as possible.</p><h4>RCA 2 : Internal Server Error</h4><p>what happened?</p><p><em>500 internal server error at internal tool</em></p><p>why it happened?</p><p><em>Undefined variable declaration caused internal server error during run time.</em></p><p>why that happened?</p><p><em>It’s manual human error. Copied similar code block from another component.</em></p><p>why that happened?</p><p><em>Conditional statement was always evaluated to false. Because of which particular code block didn’t get executed during testing.</em></p><p>why that happened?</p><p><em>No code quality check in place to avoid these kind of human mistakes.</em></p><p><strong>Quick Fix:</strong></p><ul><li>Fixed undefined variable.</li></ul><p><strong>Proposed solution:</strong></p><ul><li>setup circle CI to monitor code quality check for every Pull Request.</li></ul><p><strong>Estimated ETA:</strong></p><p>1–2 days</p><p>If you look closely, Outcome of most of the RCA is actually human error. So by doing proper RCA , You’re preventing same issues to be happening again in the future and also letting your team know about the root cause of the issue.</p><blockquote>IT’S NOT A MISTAKE TO MAKE A MISTAKE, BUT IT’S A MISTAKE TO REPEAT THE SAME MISTAKE.</blockquote><p>Thanks for reading :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtulLxsOXeIz-RtFJ32P5g.png" /></figure><p><strong>This story is published in </strong><a href="http://blog.usejournal.com/"><strong>Noteworthy</strong></a><strong>, where 10,000+ readers come every day to learn about the people &amp; ideas shaping the products we love.</strong></p><p><a href="http://blog.usejournal.com/"><strong>Follow our publication</strong></a><strong> to see more product &amp; design stories featured by the </strong><a href="https://usejournal.com/?/utm_source=usejournal.com&amp;utm_medium=blog&amp;utm_campaign=guest_post&amp;utm_content=hari_krishnan"><strong>Journal</strong></a><strong> team.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wuw1kCUUftwOONwl6PjdjQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d16c51f1a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t be just a developer.]]></title>
            <link>https://medium.com/@sherlockcodes/dont-be-just-a-developer-9cbaf22848e8?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbaf22848e8</guid>
            <category><![CDATA[hackernoon]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[software-engineer]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Wed, 27 Sep 2017 11:38:09 GMT</pubDate>
            <atom:updated>2018-08-07T17:36:08.420Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m working as a Back-end Engineer in a small B2B E-Commerce startup, Yfret Technologies ( &lt; 10 ) . When you work for a startup, you’re expected to wear multiple hats byl default. We don’t have any in-house sales, marketing and support team. Every developer held responsible for managing existing customers and on-boarding new customers. Other than building cool stuffs, I also happily say that I have thoroughly been enjoying the perks of working in a startup. I’m going to share some of those with you all on this blog and I believe this will help you in some way or other.</p><p><strong>Get Your Hands Dirty:</strong><br>When most of software engineers who have similar years of me tries to be better everyday in development. I dared myself also to get my hands dirty by trying out different things. Only when I started trying it out, I got to know that there is a whole new universe out there other than development. If you think handling thousands of requests in a second or managing gigabytes of data in a day is difficult. Try selling what you’ve built. Try bringing in new customers to sign up to your platform. Try talking to existing customer in a conference call for almost an hour . Then, You will understand the real pain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0C31EVbtYkxFek8qfYCefg.gif" /></figure><p>I’ve done solo sales demo. I’ve tried reaching out to potential customer through Linkedin. I’ve supported customers during both integration and on-boarding . So, How I got benefited by doing all this.</p><p>1. It helped me to increase my confidence level to initiate conversation with almost everybody.<br>2. Instead of just thinking in developer perspective about product, started thinking from the customer’s perspective. It helped me to be better product owner.<br>3. Gained more patience! Unofficially, I got a masters degree in Patience now ;)</p><p><strong>Building Connections:</strong></p><p>One thing I like about making connections is that knowledge sharing and discovery. I am lucky to be part of the startup community where knowledge sharing like how to manage money, environment sustainability, founder’s journey happens very frequently. We can not be an expert at every damn thing. Only when you spend time connecting with others, you will get the opportunity to gain their knowledge and share and validate your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JUS5wJG3y3WzSXIOHx28Og.gif" /></figure><p>You never know who you going to meet, until you meet them. If you’re pooling in a cab or having coffee alone in the Cafe or when traveling somewhere, try making conversation with others who you’ve never met before. It might end up laying foundation to move up in a career ladder or start your own business. I have seen casual coffee meet which lead to seed funding for one of my connection’s startup. Life is totally unpredictable. You never know what life is willing to offer you.</p><p>So, Don’t be just a Developer. Be a face of your company. Be like CEO. Throw yourself out and just see what happens. Don’t ever afraid to get your hands dirty! Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbaf22848e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elastic Search: Complex Queries]]></title>
            <link>https://medium.com/zefo-tech/elastic-search-from-beginner-to-intermediate-e4177c4c769f?source=rss-ad99d14d0986------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4177c4c769f</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[dsl]]></category>
            <dc:creator><![CDATA[Hari Krishnan]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 17:58:12 GMT</pubDate>
            <atom:updated>2019-06-11T06:42:32.753Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started to explore Elasticsearch for search and filtering, I came across many blogs generally talking about how to get started, doing basic search and so on. But, what I see common among all the blogs is that, most authors don’t prefer to go little deep to share how things actually works.</p><p>Believe me, It just took me 5 minutes to setup ElasticSearch and get started with basic search. It’s that simple. But, it took me almost a day to understand tokenizer, difference between using term and terms, match vs match_all vs match_phrase, aggregations, range query, and how to build complex filter queries. So, I am going to talk less about how to get started and more and more about how to actually make use of Elasticsearch.</p><p>To understand concepts better, I’m going to take eCommerce product filter as an example for this blog. For example, Getting all mobile phones from brand X and price range between P1 to P2 and P3 to P4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*M4MbllXHAVWcBC6nD9ztEw.jpeg" /><figcaption>Product filter . image credits : zefo</figcaption></figure><p>Please follow installation instruction from <a href="https://www.elastic.co/downloads/elasticsearch">https://www.elastic.co/downloads/elasticsearch</a> to setup ElasticSearch. Once un archived, run bin/elasticsearch to start elasticsearch server. To verify elasticsearch server is up and running, use below command to verify.</p><pre>curl -X GET <a href="http://localhost:9200/">http://localhost:9200/</a></pre><p>You should see some response like below. We’re good to go!</p><pre>{<br> “name” : “8KwKH_k”,<br> “cluster_name” : “elasticsearch”,<br> “cluster_uuid” : “7C0FnVVTTlG9Z80q_WjsGA”,<br> “version” : {<br> “number” : “5.5.2”,<br> “build_hash” : “b2f0c09”,<br> “build_date” : “2017–08–14T12:33:14.154Z”,<br> “build_snapshot” : false,<br> “lucene_version” : “6.6.0”<br> },<br> “tagline” : “You Know, for Search”<br>}</pre><p>Let’s start by creating an index (nothing but database) and bulk insert some dummy products. I already have some dummy products hosted on Github. Use below commands to import them.</p><pre>curl -O <a href="https://raw.githubusercontent.com/sherlockcodes/elasticsearch/master/products.json">https://raw.githubusercontent.com/sherlockcodes/elasticsearch/master/products.json</a><br>curl -s -XPOST &#39;<a href="http://localhost:9200/_bulk?pretty&#39;">http://localhost:9200/_bulk?pretty</a>&#39; — data-binary <a href="http://twitter.com/products">@products</a>.json</pre><p>To verify whether all products are imported or not , use match_all condition and pass an empty query condition object like below.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -d &#39;<br>{<br> &quot;query&quot; : {<br> &quot;match_all&quot; : {}<br> }<br>}&#39;</pre><p>Let’s try getting all mobiles from Micromax brand using below curl command.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -d &#39;<br>{<br>  &quot;query&quot; : {<br>    &quot;match&quot; : {&quot;brand&quot;:&quot;Micromax&quot;}<br>  }<br>}&#39;</pre><p>You should see 2 results from Micromax Brand. Now, Let’s try to get all mobile phones in “Unboxed Phones” condition.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -d &#39;<br>  {<br>  &quot;query&quot; : {<br>    &quot;match&quot; : {&quot;condition&quot;:&quot;Unboxed Phones&quot;}<br>  }<br>}&#39;</pre><p>When you try above search query, You will see mobiles with other conditions in result as well. Strange! Isn’t it?</p><p>Internally, Match condition will split given input into words. If any one of the words is present in the value while searching, a document will be added to the result. While adding a document to the result, it will be scored based on the relevancy of the given input query with the value in the document. Which means most relevant document will appear first in the result. cool!</p><p>But, we want to get only mobiles in Unboxed Phones condition right?. When we want to work with exact values, we will be working with <strong>non-scoring </strong>filtering queries. Filtering queries is very important because they are really fast as they do not calculate relevance (avoid complete scoring process) and the results are cached. So we will use a <strong>constant_score</strong> query to execute the term query in a non-scoring mode and apply a uniform score of <strong>1</strong> like below.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -d &#39;<br>{<br>  &quot;query&quot; : {<br>   &quot;constant_score&quot; : {<br>    &quot;filter&quot; : {<br>     &quot;term&quot; : {<br>      &quot;condition&quot; : &quot;Unboxed Phones&quot;<br>     }<br>    }<br>   }<br>  }<br>}&#39;</pre><p>But still there is a little hiccup. We don’t get any results back! There is nothing wrong with filter and term query, it has to do with the way elastic search indexes the value before inserting. You can use analyze API to see how elastic search tokenizes the value into smaller tokens using the below command.</p><pre>curl -XGET &#39;localhost:9200/mobile/_analyze?pretty&#39; -d &#39;<br>{<br> &quot;field&quot; : &quot;condition&quot;,<br> &quot;text&quot; : &quot;Unboxed Phones&quot;<br>}&#39;</pre><p>The result below shows how “Unboxed Phones” text will be tokenized by elasticsearch.</p><pre>{<br> “tokens” : [<br> {<br> “token” : “unboxed”,<br> “start_offset” : 0,<br> “end_offset” : 7,<br> “type” : “&lt;ALPHANUM&gt;”,<br> “position” : 0<br> },<br> {<br> “token” : “phones”,<br> “start_offset” : 8,<br> “end_offset” : 14,<br> “type” : “&lt;ALPHANUM&gt;”,<br> “position” : 1<br> }<br> ]<br>}</pre><p>Elasticsearch removes all special characters and also lowercases all the letters.</p><p>To prevent this from happening, we need to tell elastic that it is an exact value and it shouldn’t be analyzed to split into tokens. To do this, we have to delete the index first because of incorrect mapping and create a new one.</p><p>DELETE INDEX:</p><pre>curl -XDELETE &#39;localhost:9200/mobile?pretty&#39;</pre><p>CREATE INDEX:</p><pre>curl -XPUT &#39;localhost:9200/mobile&#39; -d &#39;{<br>&quot;mappings&quot;: {<br> &quot;doc&quot;: {<br>        &quot;properties&quot;: {<br>         &quot;condition&quot; : {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;index&quot;: &quot;not_analyzed&quot;<br>          }<br>     }<br>   }<br>  }<br>}&#39;</pre><p>Now, We have to bulk import all the products again and retry the same filtered term query. You should see result with one mobile matching in the result. So far, We’ve covered how to do basic search and filtering, how elastic search tokenizes value, scoring and relevancy.</p><p>Now I would also like to explore mobiles in two different conditions like “Gently Used Phones” and “Unboxed Phones”. We can achieve this by combining two term queries or we can use terms condition to achieve it.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -d &#39;<br>{<br>  &quot;query&quot; : {<br>    &quot;constant_score&quot; : {<br>       &quot;filter&quot; : {<br>        &quot;terms&quot; : {<br>         &quot;condition&quot; : [&quot;Unboxed Phones&quot;,&quot;Gently Used Phones&quot;]<br>       }<br>       }<br>    }<br>  }<br>}&#39;</pre><p>The only difference is that, terms filter results are automatically cached which means that succeeding calls will be faster, since the first call will cache the result of the above filter. Whereas, filter of multiple term filter is not cached automatically, it can be done manually though. But the results that you get back should be the same in both term and terms filter. So, prefer terms over term condition in these type of use cases.</p><p>Let’s make it more complex by querying on multiple fields to include price range to narrow down the filter results. To achieve this, we have to understand how to construct query to satisfy multiple conditions in different fields. For example, If you want to get mobile from brand X &amp; Y and price range between P1 to P2 and P3 to P4.</p><p>To do this in elastic search, we have to use Bool Query AKA complex queries. A query that matches documents matching boolean combinations of other queries. Bool query syntax will look something like below.</p><pre>{<br>“query”:<br> {<br> “bool”:<br>  {<br>  “must”:{<br>  //basically, AND condition in SQL queries.<br>  },<br>  “filter”:{<br>  // Another form of AND condition, But without scoring. <br>  },<br>  “should”:{<br>  // OR condition<br>  },<br>  “must_not”:{<br>  // NOR condition<br>  }<br>  } <br> }<br>}</pre><p>We use the below query to get mobile phones from Micromax &amp; Samsung with price range between 6000 to 10000 and 16000 to 30000.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -H &#39;Content-Type: application/json&#39; -d&#39;<br>{<br>  &quot;query&quot;:{<br>    &quot;bool&quot;:{ <br>      &quot;must&quot;:[<br>         {&quot;terms&quot;:{&quot;brand&quot;:[&quot;micromax&quot;,&quot;samsung&quot;]}}<br>      ] , <br>      &quot;should&quot;:[<br>         { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 6000, &quot;lte&quot;: 10000 } } },<br>         { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 16000, &quot;lte&quot;: 30000 } } }<br>      ]<br>    }<br>  }<br>}&#39;</pre><p>All “<strong>AND”</strong> conditional queries must go inside <strong>must</strong> block. And all “<strong>OR”</strong> conditional queries must go inside <strong>should</strong> block. We can also re-write the above query like below. It is like constructing a query by putting multiple conditional blocks within one block.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -H &#39;Content-Type: application/json&#39; -d&#39;<br>{<br>  &quot;query&quot;:{<br>    &quot;bool&quot;:{ <br>      &quot;must&quot;:[<br>        {&quot;terms&quot;:{&quot;brand&quot;:[&quot;micromax&quot;,&quot;samsung&quot;]}},<br>        {<br>        &quot;bool&quot;:{<br>          &quot;should&quot;:[<br>            { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 6000, &quot;lte&quot;: 10000 } } },<br>            { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 16000, &quot;lte&quot;: 30000 } } }<br>            ] <br>        }<br>        } <br>      ] <br>    }<br>  }<br>}&#39;</pre><p>Let’s try to get some summary of search results for better understanding by using the aggregate framework like below.</p><pre>curl -XGET &#39;localhost:9200/mobile/_search?pretty&#39; -H &#39;Content-Type: application/json&#39; -d&#39;<br>{<br>  &quot;query&quot;:{<br>    &quot;bool&quot;:{ <br>      &quot;must&quot;:[<br>        {&quot;terms&quot;:{&quot;brand&quot;:[&quot;micromax&quot;,&quot;samsung&quot;]}},<br>        {<br>        &quot;bool&quot;:{<br>          &quot;should&quot;:[<br>            { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 6000, &quot;lte&quot;: 10000 } } },<br>            { &quot;range&quot;: { &quot;price&quot;: { &quot;gte&quot;: 16000, &quot;lte&quot;: 30000 } } }<br>            ] <br>        }<br>        } <br>      ] <br>    }<br>  },<br>  &quot;aggs&quot;: {<br>    &quot;by_condition&quot;: {<br>      &quot;terms&quot;: {<br>        &quot;field&quot;: &quot;condition&quot;,<br>        &quot;size&quot;:5<br>      }<br>    },<br>    &quot;by_camera&quot;: {<br>      &quot;terms&quot;: {<br>        &quot;field&quot;: &quot;camera&quot;,<br>        &quot;size&quot;:5<br>      }<br>    }<br>  }<br>}&#39;</pre><p>The size parameter can be set to define how many term buckets should be returned out of the overall terms list. If you are passing size parameter, Each shard will return top terms of given size. Note that aggregations results may not be accurate because of sharding.</p><p>In response, you will see result with aggregate view of search like below:</p><pre>&quot;buckets&quot; : [<br>  {<br>  &quot;key&quot; : &quot;Gently Used Phones&quot;,<br>  &quot;doc_count&quot; : 2<br>  },<br>  {<br>  &quot;key&quot; : &quot;Unboxed Phones&quot;,<br>  &quot;doc_count&quot; : 1<br>  }<br>]</pre><p>So, here we’re at end of this post. We have covered:</p><p>1) How to get started<br>2) Tokenizer<br>3) Term vs Terms query<br>4) Range query<br>5) How to build complex query<br>6) Basic aggregations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4177c4c769f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zefo-tech/elastic-search-from-beginner-to-intermediate-e4177c4c769f">Elastic Search: Complex Queries</a> was originally published in <a href="https://medium.com/zefo-tech">GoZefo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>