From 298eb468713232034014d0c545e9700c044c08bb Mon Sep 17 00:00:00 2001 From: Matchu Date: Wed, 26 Jun 2013 21:37:12 -0700 Subject: [PATCH] speed up scoped_loaded_collection in item search a bit Reduces items#index.json by about 10ms per request on my box, development with cache_classes=true. The time isn't huge, but is worthwhile. --- app/flex/flex_search_extender.rb | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/app/flex/flex_search_extender.rb b/app/flex/flex_search_extender.rb index 89cf1c85..39adae17 100644 --- a/app/flex/flex_search_extender.rb +++ b/app/flex/flex_search_extender.rb @@ -11,22 +11,23 @@ module FlexSearchExtender def scoped_loaded_collection(options) options[:scopes] ||= {} @loaded_collection ||= begin - records = [] + records_by_class_and_id_str = {} # returns a structure like {Comment=>[{"_id"=>"123", ...}, {...}], BlogPost=>[...]} - h = Flex::Utils.group_array_by(collection) do |d| - d.mapped_class(should_raise=true) - end + h = collection.group_by { |d| d.mapped_class(should_raise=true) } h.each do |klass, docs| + record_ids = docs.map(&:_id) scope = options[:scopes][klass.name] || klass.scoped - records |= scope.find(docs.map(&:_id)) - end - class_ids = collection.map { |d| [d.mapped_class.to_s, d._id] } - # Reorder records to preserve order from search results - records = class_ids.map do |class_str, id| - records.detect do |record| - record.class.to_s == class_str && record.id.to_s == id.to_s + records = scope.find(record_ids) + records.each do |record| + records_by_class_and_id_str[record.class] ||= {} + records_by_class_and_id_str[record.class][record.id.to_s] = record end end + + # Reorder records to preserve order from search results + records = collection.map do |d| + records_by_class_and_id_str[d.mapped_class][d._id] + end records.extend Flex::Result::Collection records.setup(self['hits']['total'], variables) records