Commit dea3ee0a7906e7a7162a434599a422395456620d
1 parent
43fb2b22
Exists in
elasticsearch_sort
Make query generic
Signed-off-by: Macartur Sousa <macartur.sc@gmail.com>
Showing
2 changed files
with
33 additions
and
11 deletions
Show diff stats
plugins/elasticsearch/controllers/elasticsearch_plugin_controller.rb
| ... | ... | @@ -4,15 +4,37 @@ class ElasticsearchPluginController < ApplicationController |
| 4 | 4 | |
| 5 | 5 | def search |
| 6 | 6 | @results = [] |
| 7 | + @query = params[:q] | |
| 8 | + @checkbox = {} | |
| 9 | + if params[:model].present? | |
| 10 | + params[:model].keys.each do |model| | |
| 11 | + @checkbox[model.to_sym] = true | |
| 12 | + klass = model.classify.constantize | |
| 13 | + query = get_query params[:q], klass | |
| 14 | + @results += klass.__elasticsearch__.search(query).records.to_a | |
| 15 | + end | |
| 16 | + end | |
| 7 | 17 | |
| 8 | - @checkbox = {:articles => params[:articles].present?, | |
| 9 | - :communities => params[:communities].present?, | |
| 10 | - :people => params[:people].present? | |
| 11 | - } | |
| 18 | + end | |
| 19 | + | |
| 20 | + private | |
| 21 | + | |
| 22 | + def get_query text, klass | |
| 23 | + query = {} | |
| 24 | + unless text.blank? | |
| 25 | + | |
| 26 | + fields = klass::SEARCHABLE_FIELDS.map {|k, v| "#{k}^#{v[:weight]}"} | |
| 12 | 27 | |
| 13 | - @results += Article.__elasticsearch__.search('{}').records.to_a if params[:articles] | |
| 14 | - @results += Community.__elasticsearch__.search('{}').records.to_a if params[:communities] | |
| 15 | - @results += Person.__elasticsearch__.search('{}').records.to_a if params[:people] | |
| 28 | + query = { | |
| 29 | + query: { | |
| 30 | + multi_match: { | |
| 31 | + query: text, | |
| 32 | + fields: fields | |
| 33 | + } | |
| 34 | + } | |
| 35 | + } | |
| 36 | + end | |
| 37 | + query | |
| 16 | 38 | end |
| 17 | 39 | |
| 18 | 40 | end | ... | ... |
plugins/elasticsearch/views/elasticsearch_plugin/search.html.erb
| ... | ... | @@ -2,17 +2,17 @@ |
| 2 | 2 | |
| 3 | 3 | <%= form_tag controller: "elasticsearch_plugin", action: "search" do %> |
| 4 | 4 | <%= label_tag(:q, _("Search")) %> |
| 5 | - <%= text_field_tag(:q) %> | |
| 5 | + <%= text_field_tag(:q, @query) %> | |
| 6 | 6 | |
| 7 | 7 | <%= submit_tag _("Send") %> |
| 8 | 8 | |
| 9 | - <%= check_box_tag 'communities', 1, @checkbox[:communities] %> | |
| 9 | + <%= check_box_tag 'model[communities]', 1, @checkbox[:communities] %> | |
| 10 | 10 | <%= label_tag('communities', _("communities")) %> |
| 11 | 11 | |
| 12 | - <%= check_box_tag 'people', 1, @checkbox[:people] %> | |
| 12 | + <%= check_box_tag 'model[people]', 1, @checkbox[:people] %> | |
| 13 | 13 | <%= label_tag('people', _("people")) %> |
| 14 | 14 | |
| 15 | - <%= check_box_tag 'articles', 1, @checkbox[:articles] %> | |
| 15 | + <%= check_box_tag 'model[articles]', 1, @checkbox[:articles] %> | |
| 16 | 16 | <%= label_tag('articles', _("articles")) %> |
| 17 | 17 | |
| 18 | 18 | <% end %> | ... | ... |