From a32afcccd0d34883b88f51a46f0ba0f1fb427adc Mon Sep 17 00:00:00 2001 From: multiple creatures Date: Fri, 10 Jan 2020 21:27:32 -0600 Subject: speed up search with caching --- app/services/search_service.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/app/services/search_service.rb b/app/services/search_service.rb index 73ff785c9..0ef3f4a00 100644 --- a/app/services/search_service.rb +++ b/app/services/search_service.rb @@ -24,6 +24,7 @@ class SearchService < BaseService def search_for results = Status.search_for(@query.gsub(/\A#/, ''), @account, @limit, @offset) + cache_collection results, Status end def perform_accounts_search! @@ -96,5 +97,25 @@ class SearchService < BaseService following: Account.following_map(account_ids, account.id), domain_blocking_by_domain: Account.domain_blocking_map_by_domain(domains, account.id), } + end + + def cache_collection(raw, klass) + return raw unless klass.respond_to?(:with_includes) + + raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation) + cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id) + uncached_ids = raw.map(&:id) - cached_keys_with_value.keys + + klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!) + + unless uncached_ids.empty? + uncached = klass.where(id: uncached_ids).with_includes.each_with_object({}) { |item, h| h[item.id] = item } + + uncached.each_value do |item| + Rails.cache.write(item, item) + end + end + + raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact end end -- cgit