Module: Elastics::SearchQuery
- Includes:
- QueryHelper
- Defined in:
- lib/elastics/search_query.rb
Overview
Helpers to build search query.
class Query
include Elastics::SearchQuery
def phrase_query
{bool: {should: [
{multi_match: {
}}
]}}
{math: {message: params[:query_string]}}
end
def query_filters
[
{term: {published: true}},
terms_array_query(:tag, params[:tags], execution: :and),
some_complex_filter,
]
end
def aggregations
{
tag: {terms: {
field: :tag,
size: 10,
shard_size: 10,
}},
}
end
end
result = Model.search_elastics Query.new(params).as_json
Instance Attribute Summary collapse
Instance Method Summary
collapse
#normalize_filters, #normalize_query, #terms_array_query, #terms_query
Instance Attribute Details
#params ⇒ Object
Returns the value of attribute params.
43
44
45
|
# File 'lib/elastics/search_query.rb', line 43
def params
@params
end
|
Instance Method Details
#aggregations ⇒ Object
81
82
|
# File 'lib/elastics/search_query.rb', line 81
def aggregations
end
|
#as_json ⇒ Object
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
# File 'lib/elastics/search_query.rb', line 49
def as_json
page = params[:page] || 1
per_page = params[:per_page] || 10
result = {
from: (page - 1) * per_page,
size: per_page,
fields: [],
query: query,
sort: sort,
}
post_filter = self.post_filter
result[:post_filter] = post_filter if post_filter
aggregations = self.aggregations
result[:aggregations] = aggregations if aggregations
result
end
|
#initialize(params) ⇒ Object
45
46
47
|
# File 'lib/elastics/search_query.rb', line 45
def initialize(params)
@params = params
end
|
#phrase_query ⇒ Object
71
72
|
# File 'lib/elastics/search_query.rb', line 71
def phrase_query
end
|
#post_filter ⇒ Object
78
79
|
# File 'lib/elastics/search_query.rb', line 78
def post_filter
end
|
#query ⇒ Object
Builds query from phrase_query & query_filters.
67
68
69
|
# File 'lib/elastics/search_query.rb', line 67
def query
normalize_query(phrase_query, query_filters.compact)
end
|
#query_filters ⇒ Object
74
75
76
|
# File 'lib/elastics/search_query.rb', line 74
def query_filters
[]
end
|
#sort ⇒ Object
Takes ‘params` and returns it compatible with elastics. Wraps scalars into array, hashes are converted into arrays, array are passed as is.
{name: :asc, _score: :desc} => [{name: :asc}, {_score: :desc}]
:created_at => [:created_at]
90
91
92
93
94
95
96
97
|
# File 'lib/elastics/search_query.rb', line 90
def sort
val = params[:sort]
case val
when Hash then val.map { |x| Hash[[x]] }
when Array then val
else val ? [val] : []
end
end
|