/
solr_service.rb
82 lines (68 loc) · 2.57 KB
/
solr_service.rb
1
2
3
4
5
6
7
8
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
56
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
require 'solr'
require "solrizer"
module ActiveFedora
class SolrService
include Solrizer::FieldNameMapper
include Loggable
load_mappings
attr_reader :conn
def self.register(host=nil, args={})
Thread.current[:solr_service]=self.new(host, args)
end
def initialize(host, args)
host = 'http://localhost:8080/solr' unless host
opts = {:autocommit=>:on}.merge(args)
@conn = Solr::Connection.new(host, opts)
end
def self.instance
raise SolrNotInitialized unless Thread.current[:solr_service]
Thread.current[:solr_service]
end
def self.reify_solr_results(solr_result,opts={})
unless solr_result.is_a?(Solr::Response::Standard)
raise ArgumentError.new("Only solr responses (Solr::Response::Standard) are allowed. You provided a #{solr_result.class}")
end
results = []
solr_result.hits.each do |hit|
classname = class_from_solr_document(hit)
if opts[:load_from_solr]
results << classname.load_instance_from_solr(hit[SOLR_DOCUMENT_ID])
else
results << Fedora::Repository.instance.find_model(hit[SOLR_DOCUMENT_ID], classname)
end
end
return results
end
def self.class_from_solr_document(hit)
model_value = hit[solr_name("has_model", :symbol)].first
if match_data = /info:fedora\/afmodel:(.+)$/.match(model_value)
model_value = match_data[1]
model_value.gsub!('_', '::')
else
raise "has_model assertion incorrectly formatted: #{model_value}"
end
if model_value.include?("::")
eval(model_value)
else
Kernel.const_get(model_value)
end
end
# Construct a solr query for a list of pids
# This is used to get a solr response based on the list of pids in an object's RELS-EXT relationhsips
# If the pid_array is empty, defaults to a query of "id:NEVER_USE_THIS_ID", which will return an empty solr response
# @param [Array] pid_array the pids that you want included in the query
def self.construct_query_for_pids(pid_array)
query = ""
pid_array.each_index do |i|
query << "#{SOLR_DOCUMENT_ID}:#{escape_uri_for_query(pid_array[i])}"
query << " OR " if i != pid_array.length-1
end
query = "id:NEVER_USE_THIS_ID" if query.empty? || query == "id:"
return query
end
def self.escape_uri_for_query(uri)
return uri.gsub(/(:)/, '\\:')
end
end #SolrService
class SolrNotInitialized < StandardError;end
end #ActiveFedora