DEV: Option to preload topic custom fields in Search class

DEV: Option to preload topic custom fields in Search class

diff --git a/lib/search.rb b/lib/search.rb
index 2c478c5..2535b6b 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -4,6 +4,9 @@ class Search
   INDEX_VERSION = 2.freeze
   DIACRITICS ||= /([\u0300-\u036f]|[\u1AB0-\u1AFF]|[\u1DC0-\u1DFF]|[\u20D0-\u20FF])/
 
+  cattr_accessor :preloaded_topic_custom_fields
+  self.preloaded_topic_custom_fields = Set.new
+
   def self.per_facet
     5
   end
@@ -242,6 +245,11 @@ class Search
 
     find_grouped_results unless @results.posts.present?
 
+    if preloaded_topic_custom_fields.present? && @results.posts.present?
+      topics = @results.posts.map(&:topic)
+      Topic.preload_custom_fields(topics, preloaded_topic_custom_fields)
+    end
+
     @results
   end

GitHub sha: daf5a268

If there multiple posts belong to the same topic, will this result in a more expensive query?

2 Likes

The preload_custom_fields method uses the objects id as key, so this should be fine.

1 Like