stadtratmonitor/app/models/paper_search.rb

78 lines
2 KiB
Ruby
Raw Normal View History

2020-03-09 12:13:27 +01:00
# frozen_string_literal: true
2015-10-05 21:12:59 +02:00
2020-03-09 12:13:27 +01:00
class PaperSearch < ActiveRecord::Base
2015-10-10 09:48:18 +02:00
def to_definition
2020-03-09 12:13:27 +01:00
options = { paper_type: paper_type, originator: originator, sort_by: sort_by }
2015-10-10 09:48:18 +02:00
PaperSearch.definition(query, options)
end
2020-03-09 12:13:27 +01:00
def self.definition(q, options = {})
2015-10-05 21:12:59 +02:00
Elasticsearch::DSL::Search.search do
sort do
2020-03-09 12:13:27 +01:00
by '_score' if options[:sort_by] == 'score'
by :published_at, order: 'desc'
2015-10-05 21:12:59 +02:00
end
query do
# search query
2020-03-09 12:13:27 +01:00
if q.blank?
match_all
else
2015-10-05 21:12:59 +02:00
multi_match do
query q
2020-03-09 12:13:27 +01:00
fields %w[name content]
2015-10-05 21:12:59 +02:00
end
end
end
# apply filter after aggregations
post_filter do
bool do
2020-03-09 12:13:27 +01:00
if options[:paper_type].present?
must { term paper_type: options[:paper_type] }
end
if options[:originator].present?
must { term originator: options[:originator] }
end
2015-10-05 21:12:59 +02:00
# catchall when no filters set
2020-03-09 12:13:27 +01:00
unless options[:paper_type].present? || options[:originator].present?
must { match_all }
end
2015-10-05 21:12:59 +02:00
end
end
aggregation :paper_types do
# filter by originator
f = Elasticsearch::DSL::Search::Filters::Bool.new
f.must { match_all }
2020-03-09 12:13:27 +01:00
if options[:originator].present?
f.must { term originator: options[:originator] }
end
2015-10-05 21:12:59 +02:00
filter f.to_hash do
aggregation :paper_types do
terms do
field 'paper_type'
end
end
end
end
aggregation :originators do
# filter by paper_type
f = Elasticsearch::DSL::Search::Filters::Bool.new
f.must { match_all }
2020-03-09 12:13:27 +01:00
if options[:paper_type].present?
f.must { term paper_type: options[:paper_type] }
end
2015-10-05 21:12:59 +02:00
filter f.to_hash do
aggregation :originators do
terms do
field 'originator'
end
end
end
end
end
end
end