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.
This commit is contained in:
Emi Matchu 2013-06-26 21:37:12 -07:00
parent 6984201990
commit 298eb46871

View file

@ -11,21 +11,22 @@ 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))
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
class_ids = collection.map { |d| [d.mapped_class.to_s, d._id] }
end
# 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
end
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)