Class: SearchController

Inherits:
ApplicationController show all
Defined in:
frontend/app/controllers/search_controller.rb,
public/app/controllers/search_controller.rb

Defined Under Namespace

Classes: InvalidSearchParams

Constant Summary collapse

DEFAULT_SEARCH_FACET_TYPES =
['repository', 'primary_type', 'subjects', 'published_agents', 'langcode']
DEFAULT_SEARCH_OPTS =
{
#    'sort' => 'title_sort asc',
  'resolve[]' => ['repository:id', 'resource:id@compact_resource', 'ancestors:id@compact_resource', 'linked_instance_uris:id'],
  'facet.mincount' => 1
}
DEFAULT_TYPES =
%w{archival_object digital_object digital_object_component agent resource repository accession classification subject}
YEAR_FIELD_REGEX =
/^\d{1,4}$/

Instance Method Summary collapse

Methods inherited from ApplicationController

#archivesspace, can_access?, permission_mappings, set_access_control

Instance Method Details

#advanced_searchObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'frontend/app/controllers/search_controller.rb', line 9

def advanced_search
  criteria = params_for_backend_search

  queries = advanced_search_queries.reject {|field|
    (field["value"].nil? || field["value"] == "") && !field["empty"]
  }

  if not queries.empty?
    if criteria['aq']
      existing_filter = ASUtils.json_parse(criteria['aq'])
      criteria['aq'] =  JSONModel::JSONModel(:advanced_query).from_hash({
                            query: JSONModel(:boolean_query)
                                     .from_hash({
                                                  :jsonmodel_type => 'boolean_query',
                                                  :op => 'AND',
                                                  :subqueries => [existing_filter['query'], AdvancedQueryBuilder.build_query_from_form(queries)['query']]
                                                })
                          }).to_json
    else
      criteria["aq"] = AdvancedQueryBuilder.build_query_from_form(queries).to_json
    end
    criteria['facet[]'] = SearchResultData.BASE_FACETS
  end

  respond_to do |format|
    format.json {
      @search_data = Search.all(session[:repo_id], criteria)
      render :json => @search_data
    }
    format.js {
      @search_data = Search.all(session[:repo_id], criteria)
      if params[:listing_only]
        render_aspace_partial :partial => "search/listing"
      else
        render_aspace_partial :partial => "search/results"
      end
    }
    format.html {
      @search_data = Search.all(session[:repo_id], criteria)
      render "search/do_search"
    }
    format.csv {
      uri = "/repositories/#{session[:repo_id]}/search"
      csv_response( uri, Search.build_filters(criteria), "#{t('search_results.title').downcase}." )
    }
  end
end

#do_searchObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'frontend/app/controllers/search_controller.rb', line 57

def do_search
  criteria = params_for_backend_search.merge({"facet[]" => SearchResultData.BASE_FACETS.concat(params[:facets]||[]).uniq})

  context_criteria = params["context_filter_term"] ? {"filter_term[]" => params["context_filter_term"]} : {}

  # linker typeaheads should always sort by score
  context_criteria["sort"] = "score desc" if params["linker"]

  @search_data = Search.all(session[:repo_id], criteria, context_criteria)
  @hide_sort_options = params[:hide_sort_options] == "true"
  @hide_csv_download = params[:hide_csv_download] == "true"

  respond_to do |format|
    format.json {
      render :json => @search_data
    }
    format.js {
      if params[:listing_only]
        render_aspace_partial :partial => "search/listing"
      else
        render_aspace_partial :partial => "search/results"
      end
    }
    format.html {
      # default render
    }
    format.csv {
      criteria = params_for_backend_search.merge({"facet[]" => SearchResultData.BASE_FACETS})
      uri = "/repositories/#{session[:repo_id]}/search"

      # The 'context' field (shown as the "Found in" column for text searches) does not actually exist in the backend;
      # it is derived from the 'ancestors' field at runtime. If it shows up in the fields for the CSV download, we
      # need special processing to populate it properly. (See ANW-1509)
      if criteria['fields[]'].include? 'context'
        criteria['fields[]'].delete 'context'
        criteria['fields[]'].append *ContextConverter.ancestor_fields

        send_data csv_export_with_context(uri, Search.build_filters(criteria)),
          filename: "#{t('search_results.title').downcase}.#{Time.now.to_i}.csv"
      else
        # the old way (should generally be faster)
        csv_response(uri, Search.build_filters(criteria), "#{t('search_results.title').downcase}.")
      end
    }
  end
end

#searchObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'public/app/controllers/search_controller.rb', line 21

def search
  @repo_id = params.fetch(:rid, nil)
  repo_url = "/repositories/#{@repo_id}"
  @base_search = @repo_id ? "#{repo_url}/search?" : '/search?'
  fallback_location = @repo_id ? app_prefix(repo_url) : app_prefix('/search?reset=true');
  @new_search = fallback_location

  if params[:reset] == 'true' || !params.has_key?(:q)
    @reset = true
    params[:rid] = nil
    @search = Search.new(params)
    return render 'search/search_results'
  end

  search_opts = default_search_opts(DEFAULT_SEARCH_OPTS)
  search_opts['fq'] = ["repository:\"#{repo_url}\" OR used_within_published_repository::\"#{repo_url}\""] if @repo_id
  begin
    set_up_advanced_search(DEFAULT_TYPES, DEFAULT_SEARCH_FACET_TYPES, search_opts, params)
#NOTE the redirect back here on error!
  rescue Exception => error
    Rails.logger.debug(error.message)
    p error
    flash[:error] = I18n.t('search_results.error')
    redirect_back(fallback_location: root_path ) and return
  end
  page = Integer(params.fetch(:page, "1"))
  Rails.logger.debug("base search: #{@base_search}")
  Rails.logger.debug("query: #{@query}")

  @results = archivesspace.advanced_search(@base_search, page, @criteria)

  if @results['total_hits'].blank? || @results['total_hits'] == 0
    flash[:notice] = I18n.t('search_results.no_results')
    fallback_location = URI(fallback_location)
    fallback_location.query = URI(@base_search).query + "&reset=true"
    redirect_to(fallback_location.to_s)
  else
    process_search_results(@base_search)
    if @results['total_hits'] > 1
      @search[:dates_within] = true if params.fetch(:filter_from_year, '').blank? && params.fetch(:filter_to_year, '').blank?
      @search[:text_within] = true
    end
    @sort_opts = []
    all_sorts = Search.get_sort_opts
    all_sorts.keys.each do |type|
      @sort_opts.push(all_sorts[type])
    end
    # If there are any repositories in the results, get counts of their collections
    @counts = {}
    @results.records.each do |result|
      if result['primary_type'] == 'repository'
        @counts[result.uri] = get_collection_counts(result.uri)
      end
    end
    render 'search/search_results'
  end
end