From 626c4264997b621ffac001259c6c4f9afc499d9c Mon Sep 17 00:00:00 2001 From: cjcolvar Date: Tue, 5 Mar 2024 15:08:38 -0500 Subject: [PATCH] Optimize collection media object counts --- app/controllers/admin/collections_controller.rb | 13 ++++++++++++- app/presenters/admin/collection_presenter.rb | 5 +++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/controllers/admin/collections_controller.rb b/app/controllers/admin/collections_controller.rb index 5d7cfa02c9..041922e7bf 100644 --- a/app/controllers/admin/collections_controller.rb +++ b/app/controllers/admin/collections_controller.rb @@ -36,7 +36,18 @@ def load_and_authorize_collections builder.user = user end response = repository.search(builder) - @collections = response.documents.collect { |doc| ::Admin::CollectionPresenter.new(doc) }.sort_by { |c| c.name.downcase } + + # Query solr for facet values for collection media object counts and pass into presenter to avoid making 2 solr queries per collection + count_query = "has_model_ssim:MediaObject" + count_response = ActiveFedora::SolrService.get(count_query, { rows: 0, facet: true, 'facet.field': "isMemberOfCollection_ssim", 'facet.limit': -1 }) + counts_array = count_response["facet_counts"]["facet_fields"]["isMemberOfCollection_ssim"] rescue [] + counts = counts_array.blank? ? {} : [counts_array].to_h + unpublished_query = count_query + " AND workflow_published_sim:Unpublished" + unpublished_count_response = ActiveFedora::SolrService.get(unpublished_query, { rows: 0, facet: true, 'facet.field': "isMemberOfCollection_ssim", 'facet.limit': -1 }) + unpublished_counts_array = unpublished_count_response["facet_counts"]["facet_fields"]["isMemberOfCollection_ssim"] rescue [] + unpublished_counts = unpublished_counts_array.blank? ? {} : [unpublished_counts_array].to_h + + @collections = response.documents.collect { |doc| ::Admin::CollectionPresenter.new(doc, media_object_count: counts[doc.id], unpublished_media_object_count: unpublished_counts[doc.id]) }.sort_by { |c| c.name.downcase } end # GET /collections diff --git a/app/presenters/admin/collection_presenter.rb b/app/presenters/admin/collection_presenter.rb index 9bdadcd387..c4b07064bb 100644 --- a/app/presenters/admin/collection_presenter.rb +++ b/app/presenters/admin/collection_presenter.rb @@ -15,8 +15,10 @@ class Admin::CollectionPresenter attr_reader :document - def initialize(solr_doc) + def initialize(solr_doc, media_object_count: nil, unpublished_media_object_count: nil) @document = solr_doc + @media_object_count = media_object_count + @unpublished_media_object_count = unpublished_media_object_count end delegate :id, to: :document @@ -33,7 +35,6 @@ def description document["description_tesim"]&.first end - # TODO: do these counts in one large query for all collections on the index page to avoid having to do them here def media_object_count @media_object_count ||= MediaObject.where("collection_ssim" => name).count end