1+ module CTGov
2+ class SearchResultsService
3+ def initialize ( api_client = CTGov ::ApiClient ::V2 . new )
4+ unless api_client . is_a? ( CTGov ::ApiClient ::Base )
5+ raise ArgumentError , "Invalid API client. Must inherit from CTGov::ApiClient::Base"
6+ end
7+ @api_client = api_client
8+ end
9+
10+ def fetch_studies_for ( search_term , group : nil , page_size : 1000 )
11+ puts "Fetching search results for: #{ search_term } "
12+
13+ attributes = { term : search_term . downcase }
14+ attributes [ :group ] = group if group . present?
15+ search_term_record = SearchTerm . find_by ( term : attributes [ :term ] ) || SearchTerm . create! ( attributes )
16+
17+ @api_client . search_studies ( query : search_term , page_size : page_size ) do |studies |
18+ persist ( studies , search_term_record )
19+ end
20+ end
21+
22+ def refresh_search_results_for ( group )
23+ raise ArgumentError , "Group parameter is required" if group . blank?
24+
25+ terms = SearchTerm . where ( group : group . downcase )
26+ Rails . logger . info ( "Refreshing #{ terms . count } terms for group: #{ group } " )
27+
28+ terms . each do |term |
29+ fetch_studies_for ( term . term , group : term . group )
30+ end
31+
32+ end
33+
34+ private
35+
36+ def persist ( studies , search_term )
37+ silence_active_record do
38+ nct_ids = studies . map { |study | study . dig ( *@api_client . nct_id_path ) } . compact
39+ valid_nct_ids = Study . where ( nct_id : nct_ids ) . pluck ( :nct_id )
40+
41+ study_results = valid_nct_ids . map do |nct_id |
42+ {
43+ nct_id : nct_id ,
44+ search_term_id : search_term . id ,
45+ created_at : Time . current ,
46+ updated_at : Time . current
47+ }
48+ end
49+
50+ # current logic: remove all existing search results for the term and insert fresh results
51+ ActiveRecord ::Base . transaction do
52+ SearchTermResult . where ( search_term_id : search_term . id ) . delete_all
53+ return if study_results . empty?
54+ SearchTermResult . insert_all ( study_results )
55+ end
56+
57+ Rails . logger . info ( "Imported #{ study_results . size } search results for term: #{ search_term . term } " )
58+ end
59+ rescue => e
60+ Rails . logger . error ( "Error persisting search results: #{ e . message } " )
61+ raise
62+ end
63+ end
64+
65+ end
0 commit comments