speed up search with caching

master
multiple creatures 2020-01-10 21:27:32 -06:00
parent d6806025a0
commit a32afcccd0
1 changed files with 21 additions and 0 deletions

View File

@ -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