<?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 Sofi Vasserman on Medium]]></title>
        <description><![CDATA[Stories by Sofi Vasserman on Medium]]></description>
        <link>https://medium.com/@sofi.vasserman?source=rss-dde4e79ffda7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A2KHpUlFl2NGwcJDlSAATg.jpeg</url>
            <title>Stories by Sofi Vasserman on Medium</title>
            <link>https://medium.com/@sofi.vasserman?source=rss-dde4e79ffda7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:04:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sofi.vasserman/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[Leveraging Query Restructuring and Function-Based Indexes to Improve Performance]]></title>
            <link>https://medium.com/data-science/leveraging-query-restructuring-and-function-based-indexes-to-improve-performance-c50d50246964?source=rss-dde4e79ffda7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c50d50246964</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Sofi Vasserman]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 21:00:04 GMT</pubDate>
            <atom:updated>2022-04-05T13:05:50.323Z</atom:updated>
            <content:encoded><![CDATA[<h4>Our journey to optimize query run time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_6YvuWo5yGwELC87bFNZg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Examining the infinite amount of digital data created online, namely blogs, webinars, and so on, requires a <a href="https://medium.com/@sofi.vasserman/blooming-design-bloom-filter-and-its-complement-82b97056d6b0">bloom filter data structure</a> to optimize the run time of some of our validations, and ultimately create value for our customers at <a href="http://www.getbrew.com/">Brew</a>.</p><p>Beyond the use of bloom filters, to ensure we are able to effectively validate data while continually improving search performance in our database, we needed to integrate query restructuring and function-based indexes into our algorithm.</p><p>Note: Because we work with Django and PostgreSQL, all code examples in this blog will use Django ORM as it converts to raw SQL queries, but the principles and takeaways that I will discuss are applicable to any developer who works with an ORM and relational database.</p><p>The Brew platform works with an infinite amount of data generated by an endless number of marketing activities, each of which has a unique URL.<br>Every URL can have several legitimate versions, such as a URL that uses the HTTP or HTTPS scheme, a URL that starts with “www” or one that doesn’t, a URL with a language prefix in the path (e.g “http://example.com/en/page”), a URL that ends with a “html” suffix, etc.</p><p>Since we can receive any of these variations as a link of a potentially new activity and since we want to check whether this is a new activity, we had to check if this URL existed, using one of these versions, in our database. To do that, we constructed a query with regular expressions that covered all common variants to enable these searches. Specifically in Django’s ORM, querying with regular expressions is simple because it has a native field lookup operator that supports them. For example:</p><pre>Entity.objects.filter(url__iregex=&quot;http(s)?:\/\/(www\.)?example\.com&quot;)</pre><p>The query above fetches all URLs that have a HTTP or HTTPS scheme and can either start with “www.” or without it. The usage of the <em>iregex </em>operator instead of <em>regex</em> makes the search case-insensitive.</p><h4><strong>Zooming In On The Problem</strong></h4><p>Using a regular expression in the query worked great for a while, but as our database grew, we noticed some slowness in part of our processes. We began looking into why this slowness occurs and what is going on in our servers at these times. We noticed that the database’s CPU usage was quite high during some of our searches. This was surprising because, in order to optimize the search, we make sure that the columns that are frequently used in queries are indexed. Yet, a high CPU in the database, while running specific queries, implies that an index is not being used in that query. To validate this assumption, we checked the execution plan of the suspicious queries.</p><p>Checking the execution plan can be done with the following command in PostgreSQL:</p><pre>EXPLAIN ANALYZE SELECT * FROM entity_table WHERE link = &#39;https://www.example.com&#39;</pre><p>It can also be visualized with a DB administration tool like pgAdmin.</p><p>The visual explain plans of the queries we were checking looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*kW8LlunDvtayZMjg4cZIxw.png" /><figcaption>Image by author</figcaption></figure><p>The icon used for entity_table represents a full table scan, which means there is no use of indexes. A full table scan is an O(N) operation and can be a very expensive one when trying to search for a data point in a table with millions of rows.</p><p>So why weren’t our indexes used in these queries?</p><p>When using the native field lookup for regex in Django ORM, the ORM translates this operator to the regex operator in the database. So, if we run the following search:</p><pre>Entity.objects.filter(<br>    url__iregex=&quot;http(s)?:\/\/(www\.)?example\.com&quot;<br>)</pre><p>In PostgreSQL it will translate to:</p><pre>SELECT * <br>FROM entity_table <br>WHERE url ~* ‘http(s)?:\/\/(www\.)?example\.com’</pre><p>The regular expression operator in the database, makes the query evaluate the string in each row to see whether it matches the regular expression. This operator can’t use a regular B-tree index (which was the index built for this column) since B-tree indexes are used for equality and simple comparisons, which is not the case in regular expressions.</p><h4>Solving The Problem</h4><p>In prior versions of PostgreSQL (before 9.4), there was no index that could be used for queries with regular expressions. As a result, it was necessary to change the query, to make sure that indexes were used and the query’s run time was optimized.</p><p>To do that, we had to stop using the regular expression&#39;s operator, since it prevented the use of b-tree indexes. However, we still wanted to search for all of the URL variations. To do that, we had to split the query into multiple conditions instead of using one condition with a regular expression. Our previous query turned into this query:</p><pre>Entity.objects.filter(<br>    Q(url__startswith=&quot;http://www.example.com&quot;) |<br>    Q(url__startswith=&quot;https://www.example.com&quot;) |<br>    Q(url__startswith=&quot;http://example.com&quot;) |<br>    Q(url__startswith=&quot;https://example.com&quot;)<br>)</pre><p>This query in the ORM translates to the following query in the database:</p><pre>SELECT * <br>FROM entity_table <br>WHERE url LIKE ‘http://www.example.com%&#39; OR<br>      url LIKE &#39;https://www.example.com%&#39; OR<br>      url LIKE &#39;http://example.com%&#39; OR<br>      url LIKE &#39;https://example.com%&#39;</pre><p>This query now uses the index and even though we have multiple conditions instead of one, it is much more optimized than the previous query, because the index is being used.</p><p><em>Note</em>: even though we are not using the equality operator but rather the LIKE operator, which matches only part of the string, an index can still be used because we anchor the beginning of the string and it can be used as an equality match when searching the index. If we weren’t anchoring the beginning of the string, the index couldn’t be used. <br>For example, the following query:</p><pre>SELECT * <br>FROM entity_table <br>WHERE url LIKE ‘%://www.example.com%&#39;</pre><p>This query will have to run a full table scan, since the beginning of the string is a wildcard, and there is no optimized way to search for this string in a b-tree index when the beginning of the string is not a specific string.</p><p>Now our query is optimized and uses the DB index and our run time is significantly reduced. However, this query is not complete since it misses one functionality that we had before. In the previous query, we used the operator iregex<em> </em>which translated to a case-insensitive regular expression. In the new query, we use the operator startswith, which is case sensitive and doesn’t completely match our use case. To solve this issue we had two options — one is to use the LOWER or UPPER function operators of the ORM and the other is to use the istartswith operator which is the case insensitive equivalent of the startswith operator. Learning our lesson, we didn’t want to use an operator without making sure that it doesn’t degrade the query’s run time. Looking into the translation of this query in the ORM to a database query, we saw the following code:</p><pre>Entity.objects.filter(url__istartswith=&quot;http://example.com&quot;)</pre><p>Translates to the query:</p><pre>SELECT *<br>FROM entity_table<br>WHERE UPPER(url) = UPPER(&quot;http://example.com&quot;)</pre><p><em>Note:</em> In this case, there was no difference between the two optional solutions, since both are using the LOWER or the UPPER database function to make the query case insensitive.</p><p>Using these functions introduces the same issue experienced previously since the regular b-tree index is not used any time we transform the column that we are searching.</p><p>Fortunately, there is an easy solution for that and that is the <strong>function-based index</strong>.</p><p>A function-based index is an index that is created on the results of a function or an expression, instead of on the original value in this column. In our example, we can create a function-based index that is built on the results of the UPPER function on each value in the ‘<em>url</em>’ column in the database. This index will be used any time we use this function on the ‘<em>url</em>’ column in a query and this allows us to optimize the query even when not using the original values in the column.<br>Most, if not all, relational databases support function-based indexes and they can be used in any scenario in which common queries of the table use a function or some kind of simple expression on the column, e.g rounding values in a float column, fetching only the month part of a date, truncating a date to the beginning of the day or even a sum of two columns. Each of these examples will cancel the use of a regular b-tree index and can cause a degradation in the query run-time. Therefore, if these are common queries on your table, you should consider using a function-based index for the common expressions/functions that are being used and this can significantly optimize the query run time¹.</p><h4>Key Takeaways</h4><p>This experience, of run-time degradation due to the wrong usage of the ORM’s operators has reiterated to us how important it is to know our ORM and how it translates our code to queries.<br>ORMs are a great tool and they add a level of abstraction which allows us to continue using an object-oriented paradigm while interacting with our databases. However, we always need to remember that these abstractions come with a price. Simple queries will always work great with ORMs, but more complex queries require a better understanding of how the ORM translates our code. Knowing how the ORM works can help us avoid major pitfalls, like the one that we have encountered.</p><p>Another lesson that can be learned from our experience is how important it is to know how databases perform our queries. Having this knowledge and knowledge of the variety of solutions to optimize a query can help us plan ahead when building our models and prevent optimization problems in advance or easily solve them when we do encounter them.</p><p>¹ Side note for Django developers.</p><p>It is now relatively simple for Django developers to add a function-based index to a model, and it can be declared in the model specification, as of version 3.2. For example:</p><pre>class Entity(models.Model):<br>    url = models.URLField(max_length=2100)<br>    name = models.TextField()<br><br>    class Meta:<br>        indexes = [<br>            models.Index(Upper(&quot;url&quot;))<br>       ]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50d50246964" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/leveraging-query-restructuring-and-function-based-indexes-to-improve-performance-c50d50246964">Leveraging Query Restructuring and Function-Based Indexes to Improve Performance</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blooming Design — Bloom filter and its complement]]></title>
            <link>https://medium.com/@sofi.vasserman/blooming-design-bloom-filter-and-its-complement-82b97056d6b0?source=rss-dde4e79ffda7------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b97056d6b0</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[Sofi Vasserman]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 15:59:07 GMT</pubDate>
            <atom:updated>2021-12-14T11:05:08.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blooming Design — Bloom filter and its complement</h3><h4>The bloom filter, its applications and the bloom filter complement — how does it work and real life use cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bG7uEFiH8MErLNYYjL1DQ.png" /></figure><p>At <a href="https://www.getbrew.com/">Brew</a>, we work with an infinite amount of marketing activities, such as blogs and webinars. To ensure the most effective workflows, the initial validation we always make is to check if this activity is already known to the Brew platform. This optimizes the process and saves significant time before we start running validations and data extractions on the activities we encounter. One of our ways to do this validation is by checking the activity’s URL.<br>Checking whether this URL already exists can be done by scanning the blog posts table, which has an <em>O(N)</em> complexity. This means that this search can become very heavy the more blog posts we have (just think of how many blog posts are published only on this platform).<br>Of course this search can be improved if we index the URL column, which will improve the search time from <em>O(N) </em>complexity to <em>O(logN)</em> complexity (shout out to B-tree indexes). But, even with this improvement, the search time can be quite long and it will get longer the more blog posts we get. Another way to optimize this search is by using a hash table for all values, but the cost of this solution is space complexity.<br>So how can we optimize this search with a balanced time and search complexity? This is where the Bloom filter comes in.</p><h4>Probability vs Efficiency</h4><p>A Bloom filter is a space-efficient probabilistic data-structure that is used to test whether a certain element is a member of a set. In simpler words, a Bloom filter allows us to check whether an element <strong>probably</strong> exists in a set, with an <em>O(1)</em> complexity. A Bloom filter is probabilistic which means we might get a false positive response. In our example, a false positive means that we searched for a URL using the Bloom filter and it returned that the URL exists in the database even though it doesn’t exist. As mentioned before, we will process only URLs that don’t exist already, so when we receive a false positive result, we actually lose some data (there is a solution for that, which will be discussed later). <br>But, we are guaranteed that the Bloom filter will not return a false negative, so we can be sure that we are not processing data that has already been processed.</p><h4>Bloom in action</h4><p>An empty Bloom filter is a bit array of <em>m</em> size, all set to 0. We need a <em>k</em> number of hash functions to calculate hashes for each input. When we receive a new input, we use the hash function on it. Each hash function’s result will be a number between 0 and <em>m</em>, which will represent an index in the bit array. After running the hash functions on an input, we will turn on the bits in the received indices.<br>Let’s assume that we are using a bit array of length 20 and 3 hash functions — <em>h1, h2, h3</em>. Now, we are adding the URL “http://cat.com” to our database. First, we run the hash functions on this address:</p><pre>h1(“http://cat.com”) = 2<br>h2(&quot;http://cat.com”) = 5<br>h3(“http://cat.com”) = 10</pre><p>Now the bit-array will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*8cK-w4FhKLEWW77hyk3UdA.png" /></figure><p>Now we want to add a new URL address — “http://dog.com”. We run the hash functions on the new input:</p><pre>h1(“http://dog.com”) = 3<br>h2(“http://dog.com”) = 5<br>h3(“http://dog.com”) = 13</pre><p>Before adding this new value to our database, we want to be sure that it doesn’t exist. This is done by checking the bits in the indices that we received from the hash functions. If all bits are already on, we can say that the value “http://dog.com” probably exists. If not all bits are on, we can safely process this URL and add it to our database, and of course update the bit array accordingly.<br>Now our bit-array will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*GwvvmtxhoiCOU2t68Z43oA.png" /></figure><p>What happens if we try to add the URL “http://cat.com” again? We first run the hash functions and receive the results: 2, 5, 10. We check the indexes, and since they are all on, we can say that this address probably exists.</p><p>Why do we keep saying “probably exists”? Let’s take a look at another example. Assume we want to add the URL “http://mouse.com”. We run the hash functions on this input and receive the results:</p><pre>h1(“http://mouse.com”) = 2<br>h2(“http://mouse.com”) = 3<br>h3(“http://mouse.com”) = 13</pre><p>Now we check the bit array and see that all bits are on. This means that the Bloom filter will return the answer “URL already exists” even though this URL doesn’t actually exist in our database, since the bits 3 and 13 were turned on by the value “http://dog.com” and the bit 2 was turned on by the value “http://cat.com”, but none of them was turned on by the value “http://mouse.com”.</p><h4>False positives and the potential impacts</h4><p>When using the Bloom filter we will always have a probability of getting a false positive, but we can control this probability by controlling the size of the bit array and the number of hash functions we use. A larger bit array and a larger number of hash functions means less false positives, but it also means less space efficiency and more latency. So, we will have to decide on the acceptable false positive rate and calculate the number of hash functions and the array size according to it. <br>I won’t get into this in this post, but there is a formula that allows us to calculate the dependency between the false positives probability, the number of elements in the set, the number of hash functions that we use and the length of the bit array.<br>Another important thing to note about Bloom filter is that <strong>it doesn’t support deletes. </strong>As we can see in our examples, multiple words can turn the same bit, so in order to remove a word we would have to check whether all bits can be turned off, which can be very inefficient.</p><h4>Test before you scan</h4><p>The example above showed how we can use the Bloom filter to check quickly whether an item is new and can be added to our database. In the example above we never actually check the database, we rely on the Bloom filter’s response in order to tell whether an item is new. But, this comes at a cost of some data loss, since we are not processing the false positive results. We can mitigate this data loss by searching the database when we get a positive result from the Bloom filter and validating whether this value actually exists. If we choose this solution, we solve the data loss issue but lose some of the optimization. Still, using Bloom filter instead of always querying the database to check whether this URL already exists, improves the runtime complexity. It reduces the number of times we need to access the database, and if most of the times we encounter new URLs and the Bloom filter’s false positive rate is low, we rarely access the database for this validation.</p><h4>From false to true positives — Bloom filter complement¹</h4><p>But what happens if I don’t want to get a false positive at all? Let’s assume that we have an <em>allowed list</em> of IPs that can connect to our server. Every time the server gets a request, we want to check quickly whether this IP is in the <br><em>allowed list. </em>In this case, we wouldn’t like to use the Bloom filter, because we might get a false positive, which means we might allow the wrong IP to connect to our server. We can check the database to validate positive results from the Bloom filter, but this will cause the validation to take a longer time and we want to avoid it, since we want to return the response as quickly as possible. This is a classic case in which we can use the Bloom filter complement. <br>A Bloom filter complement is a solution that is based on the Bloom filter and can be used when we are working with a <strong>known set and a known finite complement set</strong>. A list of IPs is a good example for a known set, because we can calculate all available IPs in the world. It doesn’t matter that it is a very large number, it is a closed set that can be calculated which makes it eligible for Bloom filter complement. In this case, our set will be the <em>allowed list </em>of IPs and the complement set will be all existing IPs in the world that are not in the <em>allowed list </em>of IPs. Another prerequisite of the Bloom filter complement is that the set and the complement set can’t be changed often. Let’s assume that a list of allowed IPs doesn’t change quite often.</p><p>So how does this work?<br>The algorithm uses two Bloom filters — one for the allowed list of IPs and one for the complement set. Since these two sets have a different size, we will use a different size for the Bloom filter and a different number of hash functions.<br>When we check an IP, we first check the allowed IPs Bloom filter. If the answer is negative, we can be sure that this IP is not allowed. If we get a positive response, we check the second Bloom filter. If the second response is negative, we can be sure that this IP is allowed, because it is definitely not in the “not-allowed” list. If we receive a positive response from both filters, this necessarily means that one of them is false positive, in this case, we will have to search the database for the definite answer. So this solution doesn’t completely remove the use of the database, but it does reduce it significantly, since we will only access it when we get a positive result from both filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*9h2VnTrqVwgBbRceS56jTg.png" /></figure><p>What happens if an IP is added or removed from the allowed list? In this case, we will have to recalculate both Bloom filters. This is why we will use this data structure only when there aren’t too many changes to the sets.</p><h4>Bloom to optimize</h4><p>Bloom filter is a common data structure that can be used for optimization of searches. These data structures can be used in databases, for example PostgreSQL, which supports Bloom filter indexes, and Redis with its RedisBloom module. Of course, we will choose to use this structure only when we can afford getting a false positive result. In cases where we can’t allow false positives, a Bloom filter is probably not the suitable solution.<br>The Bloom filter complement is an interesting solution that can be suitable for specific cases, but the uses cases for this data structure are not very common.</p><p>[1]: H. Lim, J. Lee and C. Yim, “Complement Bloom Filter for Identifying True Positiveness of a Bloom Filter,” in <em>IEEE Communications Letters</em>, vol. 19, no. 11, pp. 1905–1908, Nov. 2015, doi: 10.1109/LCOMM.2015.2478462</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b97056d6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>