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:
parent
6984201990
commit
298eb46871
1 changed files with 12 additions and 11 deletions
|
@ -11,22 +11,23 @@ module FlexSearchExtender
|
||||||
def scoped_loaded_collection(options)
|
def scoped_loaded_collection(options)
|
||||||
options[:scopes] ||= {}
|
options[:scopes] ||= {}
|
||||||
@loaded_collection ||= begin
|
@loaded_collection ||= begin
|
||||||
records = []
|
records_by_class_and_id_str = {}
|
||||||
# returns a structure like {Comment=>[{"_id"=>"123", ...}, {...}], BlogPost=>[...]}
|
# returns a structure like {Comment=>[{"_id"=>"123", ...}, {...}], BlogPost=>[...]}
|
||||||
h = Flex::Utils.group_array_by(collection) do |d|
|
h = collection.group_by { |d| d.mapped_class(should_raise=true) }
|
||||||
d.mapped_class(should_raise=true)
|
|
||||||
end
|
|
||||||
h.each do |klass, docs|
|
h.each do |klass, docs|
|
||||||
|
record_ids = docs.map(&:_id)
|
||||||
scope = options[:scopes][klass.name] || klass.scoped
|
scope = options[:scopes][klass.name] || klass.scoped
|
||||||
records |= scope.find(docs.map(&:_id))
|
records = scope.find(record_ids)
|
||||||
end
|
records.each do |record|
|
||||||
class_ids = collection.map { |d| [d.mapped_class.to_s, d._id] }
|
records_by_class_and_id_str[record.class] ||= {}
|
||||||
# Reorder records to preserve order from search results
|
records_by_class_and_id_str[record.class][record.id.to_s] = record
|
||||||
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
|
end
|
||||||
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.extend Flex::Result::Collection
|
||||||
records.setup(self['hits']['total'], variables)
|
records.setup(self['hits']['total'], variables)
|
||||||
records
|
records
|
||||||
|
|
Loading…
Reference in a new issue