<?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 Çağrı S. on Medium]]></title>
        <description><![CDATA[Stories by Çağrı S. on Medium]]></description>
        <link>https://medium.com/@bencagri?source=rss-fe0f009b5701------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6L-XWSWSlKIvK-jiV-EHlQ.jpeg</url>
            <title>Stories by Çağrı S. on Medium</title>
            <link>https://medium.com/@bencagri?source=rss-fe0f009b5701------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:44:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bencagri/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[AMEL — Adaptive Matching Expression Language]]></title>
            <link>https://medium.com/@bencagri/amel-adaptive-matching-expression-language-cddd446658fd?source=rss-fe0f009b5701------2</link>
            <guid isPermaLink="false">https://medium.com/p/cddd446658fd</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[insuretech]]></category>
            <category><![CDATA[healthtech]]></category>
            <category><![CDATA[igaming]]></category>
            <dc:creator><![CDATA[Çağrı S.]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 09:38:15 GMT</pubDate>
            <atom:updated>2026-01-22T09:38:15.794Z</atom:updated>
            <content:encoded><![CDATA[<h3>AMEL — Adaptive Matching Expression Language</h3><p>I’ve recently open sourced a tool I’ve been working on: <strong>AMEL — Adaptive Matching Expression Language</strong> 🚀 #opensource</p><p>Ever wondered how your team could <strong>update business rules without redeploying code</strong>?<br> Or how you could <strong>detect fraud, optimize pricing, or personalize user experiences in real time</strong> with a single flexible engine?<br> What if your developers and analysts could <strong>define complex logic visually instead of hardcoding it</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOV05rSuibqaW0kZcRIIjQ.jpeg" /></figure><p>AMEL is a lightweight <strong>DSL (Domain Specific Language)</strong> and engine for defining, compiling, and evaluating business logic, rules, and calculations on structured data.</p><p>Instead of hardcoding decisions into your services, you describe them with expressions and execute them dynamically on your payloads.</p><p>The goal is simple:<br>Make complex decision logic flexible, observable, and easy to evolve.</p><p>AMEL is highly customizable and fits many real world domains. Here are a few examples.</p><p><strong>1) Financial Services — Fraud Detection</strong><br> <em>Problem</em>: Banks need to detect fraudulent transactions in real time while minimizing false positives that frustrate real customers.</p><p>With AMEL you can define rules like:<br> • High value transactions from new accounts<br> • Geographic anomaly detection<br> • Velocity abuse patterns<br> • Custom scoring functions for risk evaluation</p><p><strong>2) Healthcare — Clinical Decision Support</strong><br> <em>Problem</em>: Hospitals need automated alerts for patient deterioration, drug interactions, and protocol compliance without overwhelming clinicians with noise.</p><p>With AMEL you can express logic such as:<br> • Vital sign deterioration thresholds<br> • Drug interaction checks<br> • Protocol compliance rules<br> • Context aware alert scoring</p><p><strong>3) E-Commerce — Dynamic Pricing &amp; Promotions</strong><br> <em>Problem</em>: Retailers need sophisticated promotion rules that consider customer lifetime value, inventory levels, competitor pricing, and margin requirements.</p><p>With AMEL you can build logic for:<br> • Dynamic discounts based on customer segments<br> • Inventory aware pricing<br> • Campaign eligibility rules<br> • Margin protection conditions</p><p><strong>4) Insurance — Underwriting &amp; Claims</strong><br> <em>Problem</em>: Insurance companies need to automate policy pricing, eligibility checks, and claims fraud detection while remaining compliant with regulations.</p><p>With AMEL you can define:<br> • Risk based pricing rules<br> • Policy eligibility logic<br> • Claims anomaly detection<br> • Compliance driven decision flows</p><p><strong>5) Manufacturing — Quality Control &amp; IoT</strong><br> <em>Problem</em>: Factories need real time monitoring of equipment, predictive maintenance alerts, and quality control rules that adapt to different product specifications.</p><p>With AMEL you can express:<br> • Sensor threshold rules<br> • Predictive maintenance triggers<br> • Quality deviation detection<br> • Product specific validation logic</p><p><strong>6) Logistics — Route Optimization &amp; Delivery Rules</strong><br> <em>Problem</em>: Logistics companies need dynamic delivery rules based on package characteristics, customer SLAs, driver availability, weather, and traffic conditions.</p><p>With AMEL you can define:<br> • Priority routing logic<br> • SLA breach detection<br> • Cost vs speed optimization<br> • Operational exception rules</p><p><strong>7) HR &amp; Workforce — Employee Management</strong><br> <em>Problem</em>: HR teams need automated rules for shift scheduling, overtime compliance, performance reviews, and benefits eligibility.</p><p>With AMEL you can express:<br> • Shift assignment logic<br> • Overtime compliance rules<br> • Performance scoring<br> • Benefit eligibility conditions</p><p><strong>8) Gaming — Player Engagement &amp; Anti-Cheat</strong><br> <em>Problem</em>: Game companies need real time rules for matchmaking fairness, detecting cheaters or botting, and personalizing player experiences to maximize engagement.</p><p>With AMEL you can define:<br> • Matchmaking conditions<br> • Behavioral anomaly detection<br> • Reward personalization logic<br> • Anti cheat rule evaluation</p><p>What’s next for AMEL is even more exciting: I’m working on turning it into a <strong>visual rule and decision builder SaaS</strong>, so teams can design logic without touching code.</p><p>If you’re interested in rule engines, decision systems, fraud, automation, or visual logic builders, I’d love your feedback.</p><p>Open source project: <a href="https://github.com/bencagri/amel">https://github.com/bencagri/amel</a></p><p>Let’s make business logic easier to build and safer to change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cddd446658fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Calculate Trending Topics with SQL: A Step-by-Step Guide to Our Hotness Algorithm]]></title>
            <link>https://medium.com/@bencagri/how-to-calculate-trending-topics-with-sql-a-step-by-step-guide-to-our-hotness-algorithm-9f30cfb6d664?source=rss-fe0f009b5701------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f30cfb6d664</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[trending-topic]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Çağrı S.]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 15:05:39 GMT</pubDate>
            <atom:updated>2024-10-30T08:36:08.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*at_-rDazbmTNRa6Mi7ldTQ.jpeg" /></figure><p>Community platforms thrive on fresh, engaging discussions. But how can we surface the hottest, most relevant topics at any given time? In this post, we’ll walk through how to calculate a “hotness score” for each topic using SQL. This score factors in user engagement (likes and dislikes) and a time decay function to ensure that new, popular topics rise to the top while older discussions slowly fade.</p><p>In our last blog post, <a href="https://medium.com/@bencagri/unlocking-the-secrets-of-trending-content-how-community-platforms-calculate-whats-hot-or-4a33e4c2e58e">“Algorithms: How Community Platforms Calculate What’s Hot (or Trending)?”</a> we discussed the logic behind calculating a “hotness score” for topics on community platforms like reddit. This score combines user engagement (likes, dislikes) with a time decay factor to keep things fresh. Today, we’ll go one step further and look at how to bring this algorithm to life with SQL.</p><p>Using SQL, we’ll create a query to calculate this score, breaking down each part so you can understand how each metric — post count, net votes, and time decay — contributes to ranking trending topics.</p><p>By the end, you’ll have a complete SQL query that ranks topics by their hotness and shows you why certain discussions trend higher than others!</p><h3>Step 1: Counting Posts per Topic</h3><p>The first step is to determine how active each topic is by counting the number of posts associated with it. This “post count” is a rough indicator of how much attention a topic has received.</p><p>Here’s the SQL for counting posts per topic:</p><pre>SELECT <br>    topics.id,<br>    topics.name,<br>    COUNT(p.id) AS Post_Count<br>FROM <br>    topics<br>JOIN <br>    posts AS p ON topics.id = p.topic_id<br>GROUP BY <br>    topics.id;</pre><p>This query joins the topics table with the posts table and counts the number of posts (COUNT(p.id)) associated with each topic. We also use GROUP BY to ensure we get a count for each unique topic.</p><h3>Step 2: Calculating Net Votes for Each Topic</h3><p>Next, we’ll calculate the “net votes” for each topic. Net votes represent the difference between the number of likes and dislikes a topic has received. This is an important factor because it tells us whether a topic is positively or negatively received.</p><pre>SELECT <br>    topics.id,<br>    topics.name,<br>    COUNT(p.id) AS Post_Count,<br>    SUM(p.likes - p.dislikes) AS Net_Votes<br>FROM <br>    topics<br>JOIN <br>    posts AS p ON topics.id = p.topic_id<br>GROUP BY <br>    topics.id;</pre><p>Here, SUM(p.likes - p.dislikes) calculates the net votes for each topic, adding all likes and subtracting all dislikes across posts. This gives us a quick sense of a topic’s popularity.</p><h3>Step 3: Applying Logarithmic Scaling to Net Votes</h3><p>Simply counting net votes can skew results, as topics with a high number of votes will dominate the list. To manage this, we apply a logarithmic scaling to the net votes, which smooths the impact of additional votes. This helps newer topics gain traction, even if they don’t yet have thousands of votes.</p><p>The SQL to apply logarithmic scaling is as follows:</p><pre>SELECT <br>    topics.id,<br>    topics.name,<br>    COUNT(p.id) AS Post_Count,<br>    SUM(p.likes - p.dislikes) AS Net_Votes,<br>    CASE <br>        WHEN SUM(p.likes - p.dislikes) = 0 THEN 0<br>        ELSE LOG(GREATEST(SUM(p.likes - p.dislikes), 1)) <br>    END AS Log_Scaled_Votes<br>FROM <br>    topics<br>JOIN <br>    posts AS p ON topics.id = p.topic_id<br>GROUP BY <br>    topics.id;</pre><p>In this part of the query, LOG(GREATEST(SUM(p.likes - p.dislikes), 1)) applies logarithmic scaling to net votes, ensuring that even a low or negative number of votes is transformed in a way that favors recent engagement.</p><h3>Step 4: Adding a Time Decay Factor</h3><p>To keep the list fresh, we use a time decay factor that gradually lowers the score of older topics. This decay factor is based on the difference between the current time and the time the topic was created.</p><p>Here’s how we implement the time decay factor:</p><pre>SELECT <br>    topics.id,<br>    topics.name,<br>    COUNT(p.id) AS Post_Count,<br>    SUM(p.likes - p.dislikes) AS Net_Votes,<br>    CASE <br>        WHEN SUM(p.likes - p.dislikes) = 0 THEN 0<br>        ELSE LOG(GREATEST(SUM(p.likes - p.dislikes), 1)) <br>    END AS Log_Scaled_Votes,<br>    (EXTRACT(EPOCH FROM NOW()) - EXTRACT(EPOCH FROM topics.created_at)) / 45000 AS Time_Decay<br>FROM <br>    topics<br>JOIN <br>    posts AS p ON topics.id = p.topic_id<br>GROUP BY <br>    topics.id;</pre><p>The EXTRACT(EPOCH FROM NOW()) - EXTRACT(EPOCH FROM topics.created_at) expression calculates the age of each topic in seconds. Dividing by 45000 reduces the impact of age on the score, creating a smoother decay effect.</p><h3>Step 5: Combining Engagement and Time Decay into the Hotness Score</h3><p>Now, let’s bring it all together. The hotness score combines the logarithmic scaling of net votes and the time decay factor. Topics with high engagement and recent activity will score higher and appear at the top of the trending list.</p><p>Here’s the full query:</p><pre>SELECT <br>    topics.id,<br>    topics.name AS Name,<br>    topics.slug AS Slug,<br>    COUNT(p.id) AS Post_Count,<br>    CASE <br>        WHEN SUM(p.likes - p.dislikes) = 0 THEN 0<br>        ELSE LOG(GREATEST(SUM(p.likes - p.dislikes), 1)) <br>            + ((EXTRACT(EPOCH FROM NOW()) - EXTRACT(EPOCH FROM topics.created_at)) / 45000) <br>    END AS hotness_score<br>FROM <br>    topics<br>JOIN <br>    posts AS p ON topics.id = p.topic_id<br>JOIN <br>    topic_channels ON topics.id = topic_channels.topic_model_id<br>WHERE <br>    topics.deleted_at IS NULL<br>    AND p.created_at &gt;= &#39;2024-09-05 02:10:10&#39;<br>    AND topic_channels.channel_model_id IN (1, 982)<br>GROUP BY <br>    topics.id<br>ORDER BY <br>    hotness_score DESC<br>LIMIT 100;</pre><p>This SQL query combines engagement and freshness to identify trending topics. It’s a powerful approach that balances popularity and recency, ensuring that your community platform is always serving up the most engaging, timely discussions. Try adapting this query to your own database structure to see which topics are heating up!</p><p>This algorithm has already been implemented on <a href="https://dasfutbol.com/">dasfutbol</a> for trending topics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f30cfb6d664" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms: How Reddit’s Hotness Algorithm Calculates Hot Topics?]]></title>
            <link>https://medium.com/@bencagri/unlocking-the-secrets-of-trending-content-how-community-platforms-calculate-whats-hot-or-4a33e4c2e58e?source=rss-fe0f009b5701------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a33e4c2e58e</guid>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Çağrı S.]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 10:09:10 GMT</pubDate>
            <atom:updated>2024-11-26T14:12:30.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*BjppaeIeocDgJvFqGH_uTQ.jpeg" /></figure><p>In the fast-paced world of community platforms, staying relevant can make or break a discussion. As new posts flood in and older conversations fade away, a pressing question emerges: <strong>What makes a topic “trending”?</strong> Behind every trending post or hot topic is a sophisticated algorithm that weighs a variety of factors to decide which content rises to the top and captures attention. One such algorithm, widely used by platforms, is a dynamic formula that balances engagement and time decay.</p><p>In this article, we’ll break down the nuts and bolts of this “hotness score” algorithm and how it determines the most engaging, relevant, and popular content for users to discover.</p><h3>The Goal: Prioritizing Engagement and Freshness</h3><p>The purpose of any content-ranking algorithm is to present users with the most <strong>engaging</strong> and <strong>timely</strong> content. But how can a platform balance these two competing goals? You want content with high engagement, like posts with lots of likes and comments, but you also need to keep things fresh by promoting newer discussions.</p><p>This algorithm achieves that balance by taking two key factors into account:</p><ol><li><strong>User Engagement</strong> — Measured by the net number of likes and dislikes on posts.</li><li><strong>Time Decay</strong> — Giving more weight to newer topics so that fresh content can rise quickly.</li></ol><p>Let’s dig into how this works!</p><h3>Step 1: Counting the Buzz — Post Volume and Engagement</h3><p>The foundation of the algorithm is built on understanding how much engagement a topic generates. For each topic, the number of associated posts is counted. Each post can be liked or disliked by users, and the <strong>difference</strong> between these likes and dislikes gives us a measure of how positively or negatively the content is perceived.</p><p>Here’s how it works:</p><ul><li><strong>Post Count:</strong> The number of posts related to each topic gives a rough idea of how much activity is happening.</li><li><strong>Net Votes:</strong> This is the sum of the difference between likes and dislikes for each post. A high number of net positive votes means the content is generally liked, while negative votes pull the topic’s score down.</li></ul><p><strong>Formula for Net Votes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*iJW8K6PgDl8OzvZQulbc7g.png" /></figure><p>But just counting votes isn’t enough. Without some sort of scaling, a topic that’s been around for years might always stay on top. This is where logarithmic scaling and time decay come into play.</p><h3>Step 2: Logarithmic Scaling — The Power of Diminishing Returns</h3><p>If the algorithm simply added up likes and dislikes, popular topics would snowball and dominate forever. To prevent this, the algorithm uses <strong>logarithmic scaling</strong>, which rewards engagement but with <strong>diminishing returns</strong>.</p><p>What does that mean? The more likes a topic receives, the smaller the impact of additional likes becomes. For example, going from 1 to 10 likes might have a significant impact, but going from 100 to 110 likes matters much less. This ensures that viral topics with thousands of likes don’t completely overshadow newer, smaller discussions.</p><p><strong>Logarithmic Scaling Formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*PumC-SGQMW5_5_B4R9Z-AQ.png" /></figure><p>Why the logarithm? The logarithmic function grows rapidly at first but then flattens out, ensuring that older, highly-liked topics don’t dominate indefinitely.</p><h3>Step 3: Time Decay — Keeping Things Fresh</h3><p>To ensure new topics get a fair shot at becoming trending, the algorithm applies a <strong>time decay factor</strong>. This factor works by reducing a topic’s hotness score as time passes. In other words, <strong>the older a topic, the less “hot” it becomes</strong>, no matter how popular it was initially.</p><p>Time decay is calculated using the difference between the current time and the topic’s creation time. The algorithm then divides this by a constant (in this case, 45,000) to control the rate at which older topics lose relevance.</p><p>Time Decay Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCQLI8TJv3zcNE6FDyEw3A.png" /></figure><p>The time decay factor ensures that <strong>new content has an advantage</strong> — topics that are only a few hours or days old can rise to the top quickly if they gain traction. However, without sufficient engagement, they’ll fade just as fast.</p><h3>Step 4: The Final Hotness Score — Balancing Engagement and Freshness</h3><p>The magic happens when these two elements — logarithmic scaling and time decay — are combined. The <strong>hotness score</strong> is a sum of both factors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2CF_Uoyh4f_BoqI2De9CQ.png" /></figure><p>This equation means that the hotter the topic, the more it’s likely to have <strong>high engagement in a short period of time</strong>. If a topic has a high number of positive votes but is older, the time decay will push it down in favor of newer content that’s gaining attention. This balance keeps the platform dynamic, always surfacing relevant content that is <strong>both fresh and popular</strong>.</p><h3>Why Does This Matter?</h3><p>For users, this algorithm makes community platforms more engaging by showing them the <strong>most relevant, up-to-date content</strong>. Whether it’s a rapidly growing discussion on breaking news or a debate on a trending topic, users want to be part of the conversation while it’s still fresh. For content creators, understanding how this works helps optimize when and how to engage their audience.</p><p>In short, this hotness score algorithm is the engine that keeps communities alive, ensuring that <strong>timely, engaging discussions</strong> always take center stage.</p><h3>Whats next?</h3><p>We will implement this logic with SQL and see if it works on <a href="https://medium.com/@bencagri/how-to-calculate-trending-topics-with-sql-a-step-by-step-guide-to-our-hotness-algorithm-9f30cfb6d664">next chapter.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a33e4c2e58e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Multi-Table Full Text Search with GORM]]></title>
            <link>https://medium.com/@bencagri/implementing-multi-table-full-text-search-with-gorm-632518257d15?source=rss-fe0f009b5701------2</link>
            <guid isPermaLink="false">https://medium.com/p/632518257d15</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Çağrı S.]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 11:00:34 GMT</pubDate>
            <atom:updated>2020-02-10T08:17:45.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Polymorphic Full Text Search on PostgreSql with Golang</h3><p>Easily searching across an application’s data is a pervasive need. If you are lucky, you can get away with simple sorting or searching on a single column, but it is more likely that you need full text search across multiple models, all from a single search field.</p><p>Search has been a problem for content related systems. But nowadays, we have many solutions for this. In <a href="https://github.com/sociozat/sociozat">Sociozat</a> project, for search, i implemented full text search for polymorphic relationship documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*hIuA2S0_yaBInJN1EFfTIA.png" /><figcaption>search sample with polymorphic documents</figcaption></figure><p><a href="https://gorm.io/">Gorm</a> is fantastic ORM library for <a href="https://golang.org/">Golang</a>. It supports postgres, mysql and sqlite. The solution for getting results polymorphic relationship is simple with rdbms. Lets Get Started …</p><h3>SQL Changes</h3><p>We need different where statements for different kind of rdbms, and also we will look for different types of documents (ie topic, user, channel). To do that, we need to construct a database view which presents a polymorphic relationship to the individual result and the text column being searched.</p><p>Lets create a view table first.</p><pre>CREATE VIEW searches AS<br>  SELECT<br>    &#39;topic&#39; AS type,<br>    topics.name as title,<br>    topics.slug<br>  FROM topics</pre><pre>  UNION</pre><pre>  SELECT<br>    &#39;user&#39; as type,<br>    users.username as title,<br>    users.slug<br>  FROM users</pre><pre>  UNION</pre><pre>  SELECT<br>    &#39;channel&#39; as type,<br>    channels.name as title,<br>    channels.slug<br>  FROM channels<br>;</pre><p>We can use this sql for both <a href="https://www.postgresql.org/docs/9.4/sql-createview.html">postgres</a> and <a href="https://dev.mysql.com/doc/refman/8.0/en/create-view.html">mysql</a>. Unfortunately, creating view table is not enough. We also need full-text indexes.</p><h4>Postgres</h4><pre>CREATE INDEX index_channels_on_name ON channels USING gin(to_tsvector(&#39;simple&#39;, name));<br>CREATE INDEX index_topics_on_name ON topics USING gin(to_tsvector(&#39;simple&#39;, name));<br>CREATE INDEX index_users_on_name ON users USING gin(to_tsvector(&#39;simple&#39;, username));</pre><p>From here, we add ginindices to the columns on which we are searching. In our case similar indices to these made the difference between a 3–5 second lookup and ~100ms.</p><blockquote>P.S. you can also use <em>gist</em> type, consider there are some performance differences. it depends on your usage. More details are in <a href="https://www.postgresql.org/docs/9.4/textsearch-indexes.html">documentation</a>.</blockquote><h4>Mysql</h4><pre>ALTER TABLE `channels` ADD FULLTEXT INDEX `index_channels_on_name` (`name`);<br>ALTER TABLE `topics` ADD FULLTEXT INDEX `index_topics_on_name` (`name`);<br>ALTER TABLE `users` ADD FULLTEXT INDEX `index_users_on_name` (`username`);</pre><h3>Implementing in Go.</h3><p>We need a gorm model to search in our searches view table. Lets create a gorm model.</p><pre>type SiteSearchResult struct {                        <br>    Type  string `json:&quot;type&quot;`                        <br>    Slug  string `json:&quot;slug&quot;`<br>    Title string `json:&quot;title&quot;`<br>}<br>                                       <br>func (s SiteSearchResult) TableName() string {<br>    return &quot;searches&quot;                       <br>}</pre><p>now we can do search. this is for mysql where clause for full text search.</p><pre>results := []models.SiteSearchResult{}</pre><pre>//for mysql<br>if err := db.Table(&quot;searches&quot;).Where(&quot;WHERE MATCH (title) AGAINST (? IN BOOLEAN MODE)&quot;, term).Find(&amp;results).Error; err != nil {<br>   return results<br>}</pre><pre>//for postgres<br>if err := db.Table(&quot;searches&quot;).Where(&quot;title @@ to_tsquery(?)&quot;, term).Find(&amp;results).Error; err != nil{<br>   return results<br>}</pre><pre>//for sqlite<br>if err := db.Table(&quot;searches&quot;).Where(&quot;title MATCH ?&quot;, term).Find(&amp;results).Error; err != nil{<br>   return results<br>}</pre><p>In Sociozat, I used an <a href="https://github.com/sociozat/sociozat/blob/master/app/repositories/search.go#L24">adapter pattern</a> to support all rdbms. You can use for your database.</p><h4>Additional</h4><p>UNION might not be a good approach if you have too much search request. <br>In this case you should switch to elasticsearch or solr or similar soulutions.</p><h3>Conclusion</h3><p>For polymorphic relationship documents, creating a view table supported with full-text indexes might be a good approach if you dont have too many requests or you have limited resources.</p><p>For single search query this might be the easiest solution for multi table searches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632518257d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>