From 070eac16a85e424e332bb069ce57e181480a1d0f Mon Sep 17 00:00:00 2001 From: Alan Guo Xiang Tan Date: Wed, 28 Dec 2022 08:10:36 +0800 Subject: [PATCH] PERF: Optimize the performance of `TopicLink.topic_map` query (#19630) Instead of relying on the `ILIKE` operator to filter out image links, we can instead rely on the `TopicLink#extension` column which allows us to more efficiently filter out image links. This optimization mainly affects topics that are link heavy which is common in topics with alot of replies. When profiling a production instance for a topic with 10K replies and 2.5K `topic_links`, this optimization reduces the query time from ~18ms to around ~4ms. --- app/models/topic_link.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/models/topic_link.rb b/app/models/topic_link.rb index 977de9c2ac8..690779cb06e 100644 --- a/app/models/topic_link.rb +++ b/app/models/topic_link.rb @@ -58,8 +58,7 @@ class TopicLink < ActiveRecord::Base builder.where('ftl.topic_id = :topic_id', topic_id: topic_id) builder.where('ft.deleted_at IS NULL') - # note that ILIKE means "case insensitive LIKE" - builder.where("NOT(ftl.url ILIKE '%.png' OR ftl.url ILIKE '%.jpg' OR ftl.url ILIKE '%.gif')") + builder.where("ftl.extension IS NULL OR ftl.extension NOT IN ('png','jpg','gif')") builder.where("COALESCE(ft.archetype, 'regular') <> :archetype", archetype: Archetype.private_message) builder.where("clicks > 0")