elasticsearch_plugin_controller.rb
2.21 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class ElasticsearchPluginController < ApplicationController
no_design_blocks
SEARCHABLE_TYPES = { :all => { label: _("All Results")},
:community => { label: _("Communities")},
:event => { label: _("Events")},
:person => { label: _("People")}
}
SEARCH_FILTERS = { :lexical => { label: _("Alphabetical Order")},
:recent => { label: _("More Recent Order")},
:access => { label: _("More accessed")}
}
def index
search()
render :action => 'search'
end
def search
define_searchable_types
define_search_fields_types
@query = params[:q]
@results = []
if @selected_type == :all
SEARCHABLE_TYPES.keys.each do |type|
results type.to_s
end
else
results @selected_type
end
end
private
def get_query text, klass
query = {}
unless text.blank?
text = text.downcase
fields = klass::SEARCHABLE_FIELDS.map do |key, value|
if value[:weight]
"#{key}^#{value[:weight]}"
else
"#{key}"
end
end
query = {
query: {
match_all: {
}
},
filter: {
regexp: {
name: {
value: ".*" + text + ".*" }
}
},
suggest: {
autocomplete: {
text: text,
term: {
field: "name",
suggest_mode: "always"
}
}
}
}
end
query
end
def results model
begin
klass = model.to_s.classify.constantize
rescue
return
end
query = get_query params[:q], klass
@results |= klass.__elasticsearch__.search(query).records.to_a
end
def define_searchable_types
@searchable_types = SEARCHABLE_TYPES
@selected_type = params[:selected_type].nil? ? :all : params[:selected_type].to_sym
end
def define_search_fields_types
@search_filter_types = SEARCH_FILTERS
@selected_filter_field = params[:selected_filter_field].nil? ? SEARCH_FILTERS.keys.first : params[:selected_filter_field].to_sym
end
end